import ATProtoKit import Darwin import Foundation import OSLog import Security import UIKit extension ATProtoBlueskyService { func publish(text: String, replyTo: Post?, quotePost: Post?, images: [ImageAttachment]) async throws -> Post { try await publish(text: text, replyTo: replyTo, quotePost: quotePost, images: images, video: nil) } func publish(text: String, replyTo: Post?, quotePost: Post?, images: [ImageAttachment], video: VideoAttachment?) async throws -> Post { guard let current = stored else { throw ServiceError.noSession } let generation = sessionGeneration let finalText = text guard finalText.count <= 300 else { throw ServiceError.postTextTooLong } let createdAt = Date() var record: [String: Any] = [ "$type": "app.bsky.feed.post", "text": finalText, "createdAt": ISO8601DateFormatter().string(from: createdAt) ] let quoteEmbed: [String: Any]? if let quotePost { quoteEmbed = ["$type": "app.bsky.embed.record", "record": try strongReference(for: quotePost)] } else { quoteEmbed = nil } if let replyTo { let parent = try strongReference(for: replyTo) let root: [String: String] if let rootURI = replyTo.replyRootURI, let rootCID = replyTo.replyRootCID { root = ["uri": rootURI, "cid": rootCID] } else { root = parent } record["reply"] = ["root": root, "parent": parent] } do { record["embed"] = try await postEmbed( images: images, video: video, quote: quoteEmbed, generation: generation, account: current) } catch { throw ActionNotSentError(underlying: error) } let facets = await publishFacets(in: finalText) if !facets.isEmpty { record["facets"] = facets.map(Self.encodedFacet) } guard generation == sessionGeneration else { throw ActionNotSentError(underlying: ServiceError.noSession) } let result = try await createRecord(collection: "app.bsky.feed.post", record: record) let postAuthor = Account(handle: current.handle, displayName: current.handle, id: current.did) return Post( id: result.uri, cid: result.cid, author: Post.Author(id: postAuthor.id, name: postAuthor.displayName, handle: postAuthor.handle), text: finalText, likeCount: 0, repostCount: 0, isLiked: false, isReposted: false, imageURLs: [], replyRootURI: replyTo?.replyRootURI ?? replyTo?.id, replyRootCID: replyTo?.replyRootCID ?? replyTo?.cid, replyParentURI: replyTo?.id, replyParentCID: replyTo?.cid, facets: facets, quote: quotePost.map { Post.Quote(postID: $0.id) }, replyIDs: [], createdAt: createdAt) } private func postEmbed( images: [ImageAttachment], video: VideoAttachment?, quote: [String: Any]?, generation: UUID, account: StoredSession ) async throws -> [String: Any]? { guard video == nil || images.isEmpty else { throw ServiceError.mixedMedia } let media: [String: Any] if let video { let blob = try await uploadVideo(video, generation: generation, account: account) media = ["$type": "app.bsky.embed.video", "video": blob] } else if !images.isEmpty { guard images.count <= 10 else { throw ServiceError.tooManyImages } var uploads: [[String: Any]] = [] for image in images { uploads.append(try await uploadImage(image, generation: generation)) } media = Self.imageEmbed(uploads) } else { return quote } if let quote { return ["$type": "app.bsky.embed.recordWithMedia", "record": quote, "media": media] } return media } private func uploadImage(_ image: ImageAttachment, generation: UUID) async throws -> [String: Any] { let upload = try Self.prepareImageForUpload(image) guard generation == sessionGeneration else { throw ServiceError.noSession } let client = try await authenticatedClient() guard generation == sessionGeneration else { throw ServiceError.noSession } do { let blob = try await client.uploadBlob(upload.data, contentType: upload.mimeType) if let id = client.sessionConfiguration?.instanceUUID { await UserSessionRegistry.shared.removeSession(for: id) } let data = try JSONEncoder().encode(blob) guard let object = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { throw ServiceError.invalidUploadResponse } return [ "alt": image.altText, "image": object, "aspectRatio": ["width": upload.width, "height": upload.height] ] } catch { if let id = client.sessionConfiguration?.instanceUUID { await UserSessionRegistry.shared.removeSession(for: id) } throw error } } static func imageEmbed(_ images: [[String: Any]]) -> [String: Any] { if images.count <= 4 { return ["$type": "app.bsky.embed.images", "images": images] } let items = images.map { image in var item = image item["$type"] = "app.bsky.embed.gallery#image" return item } return ["$type": "app.bsky.embed.gallery", "items": items] } }