1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
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
}
}