Skip to content

Instantly share code, notes, and snippets.

@jhowlin
Created July 10, 2024 10:04
Show Gist options
  • Save jhowlin/6c7d2758db7c43d2aa9d90c1eba82996 to your computer and use it in GitHub Desktop.
Save jhowlin/6c7d2758db7c43d2aa9d90c1eba82996 to your computer and use it in GitHub Desktop.
func postStatus(_ composedStatus: ComposedStatus) async throws -> APIStatus {
let instance = try await currentInstance()
let url = instance.instanceURL.appending(path: "/api/v1/statuses")
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
var statusPost = EncodableStatus()
statusPost.status = composedStatus.content.text
if let attachments = composedStatus.content.attachments {
statusPost.media_ids = try await uploadImages(attachments).map(\.id)
}
statusPost.in_reply_to_id = composedStatus.inReplyToID
let data = try JSONEncoder().encode(statusPost)
urlRequest.httpBody = data
try await addAccessToken(url: &urlRequest)
var request = NetworkRequest<APIStatus>(identifier: "Post Status-\(composedStatus.idempotencyKey.uuidString)", urlRequest: urlRequest)
request.parser = parser()
request.displayLabel = "Post Status: \(composedStatus.idempotencyKey.uuidString.prefix(6))"
let result = try await execute(request)
return result
}
func uploadImages(_ images: [ComposedAttachment]) async throws -> [APIMediaAttachment] {
try await withThrowingTaskGroup(of: APIMediaAttachment.self, body: { group in
var allAttachments: [APIMediaAttachment] = []
for image in images {
group.addTask {
try await self.uploadImageData(image.data, mimeType: image.mime)
}
}
for try await attachment in group {
allAttachments.append(attachment)
}
return allAttachments
})
}
func uploadImageData(_ data: Data, mimeType: String = "image/jpeg") async throws -> APIMediaAttachment {
let instance = try await currentInstance()
let url = instance.instanceURL.appending(path: "/api/v2/media")
let boundary = "Boundary-\(UUID().uuidString)"
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
var bodyData = Data()
bodyData.append("--\(boundary)\r\n".data(using: .utf8)!)
bodyData.append("Content-Disposition: form-data; name=\"file\"; filename=\"img.jpg\"\r\n".data(using: .utf8)!)
bodyData.append("Content-Type: \(mimeType)\r\n\r\n".data(using: .utf8)!)
bodyData.append(data)
bodyData.append("\r\n".data(using: .utf8)!)
bodyData.append("--\(boundary)--".data(using: .utf8)!)
urlRequest.httpBody = bodyData
try await addAccessToken(url: &urlRequest)
var request = NetworkRequest<APIMediaAttachment>(identifier: "Upload image-\(boundary)", urlRequest: urlRequest)
request.parser = parser()
request.displayLabel = "Upload image: \(boundary.suffix(6))"
let result = try await execute(request)
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment