import ATProtoKit import Foundation extension ATProtoBlueskyService { func uploadVideo(_ video: VideoAttachment, generation: UUID, account: StoredSession) async throws -> [String: Any] { _ = try Self.videoSize(video) guard let host = account.pdsURL.host else { throw ServiceError.invalidURL } let client = try await authenticatedClient() defer { if let id = client.sessionConfiguration?.instanceUUID { Task { await UserSessionRegistry.shared.removeSession(for: id) } } } let auth = try await client.getServiceAuthentication( from: "did:web:\(host)", expirationTime: 1800, lexiconMethod: "com.atproto.repo.uploadBlob" ) guard generation == sessionGeneration else { throw ServiceError.noSession } var components = URLComponents(string: "https://video.bsky.app/xrpc/app.bsky.video.uploadVideo")! components.queryItems = [ URLQueryItem(name: "did", value: account.did), URLQueryItem(name: "name", value: "\(video.id.uuidString).mp4") ] guard let url = components.url else { throw ServiceError.invalidURL } var request = URLRequest(url: url) request.httpMethod = "POST" request.timeoutInterval = 600 request.setValue("Bearer \(auth.token)", forHTTPHeaderField: "Authorization") request.setValue("video/mp4", forHTTPHeaderField: "Content-Type") let data: Data let response: URLResponse switch video.source { case .data(let videoData): request.httpBody = videoData (data, response) = try await dispatchAuthenticated(request, generation: generation) case .file(let fileURL): (data, response) = try await dispatchAuthenticatedUpload(request, fileURL: fileURL, generation: generation) } let status = try Self.videoJobResponse(data, response: response, wrapped: false) return try await waitForVideoBlob(status, generation: generation) } private static func videoSize(_ video: VideoAttachment) throws -> Int { guard video.mimeType == "video/mp4" else { throw ServiceError.invalidVideo } let size: Int switch video.source { case .data(let data): size = data.count case .file(let url): guard url.isFileURL, let attributes = try? url.resourceValues(forKeys: [.fileSizeKey, .isRegularFileKey]), attributes.isRegularFile == true, let fileSize = attributes.fileSize else { throw ServiceError.invalidVideo } size = fileSize } guard size > 0 else { throw ServiceError.invalidVideo } guard size <= 300_000_000 else { throw ServiceError.videoTooLarge } return size } private func waitForVideoBlob(_ initialStatus: [String: Any], generation: UUID) async throws -> [String: Any] { var status = initialStatus for attempt in 0..<300 { guard generation == sessionGeneration else { throw ServiceError.noSession } if let blob = status["blob"] as? [String: Any] { return blob } if status["state"] as? String == "JOB_STATE_FAILED" || (status["error"] != nil && status["error"] as? String != "already_exists") { throw ServiceError.requestFailed( status["message"] as? String ?? "Bluesky could not process this video. Try another video.") } guard let jobID = status["jobId"] as? String, !jobID.isEmpty else { throw ServiceError.invalidUploadResponse } if attempt > 0 { try await Task.sleep(nanoseconds: 1_000_000_000) } var poll = URLComponents(string: "https://video.bsky.app/xrpc/app.bsky.video.getJobStatus")! poll.queryItems = [URLQueryItem(name: "jobId", value: jobID)] guard let pollURL = poll.url else { throw ServiceError.invalidURL } let (pollData, pollResponse) = try await dispatchAuthenticated( URLRequest(url: pollURL), generation: generation) status = try Self.videoJobResponse(pollData, response: pollResponse, wrapped: true) } throw ServiceError.videoProcessingTimedOut } static func videoJobResponse(_ data: Data, response: URLResponse, wrapped: Bool) throws -> [String: Any] { guard let http = response as? HTTPURLResponse else { throw ServiceError.invalidResponse } let object = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] let status = object?["jobStatus"] as? [String: Any] ?? (wrapped ? nil : object) let alreadyExists = status?["error"] as? String == "already_exists" && status?["jobId"] is String guard (200..<300).contains(http.statusCode) || alreadyExists else { throw ServiceError.requestFailed( status?["message"] as? String ?? object?["message"] as? String ?? "Bluesky could not upload this video. Try again.") } guard let status else { throw ServiceError.invalidUploadResponse } return status } }