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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
import Foundation
import XCTest
@testable import OldFella
extension ATProtoServiceTests {
func testVideoUploadUsesServiceTokenAndPublishesProcessedBlob() async throws {
let suite = "VideoUpload.\(UUID().uuidString)"
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
let configuration = URLSessionConfiguration.ephemeral
configuration.protocolClasses = [StubURLProtocol.self]
let session = URLSession(configuration: configuration)
let expiry = Int(Date().addingTimeInterval(3600).timeIntervalSince1970)
let payload = Data("{\"exp\":\(expiry)}".utf8).base64EncodedString().replacingOccurrences(of: "=", with: "")
let token = "header.\(payload).signature"
StubURLProtocol.clearRequests()
StubURLProtocol.handler = { request in
try self.videoUploadResponse(request, token: token)
}
defer {
StubURLProtocol.handler = nil
session.invalidateAndCancel()
defaults.removePersistentDomain(forName: suite)
}
let service = ATProtoBlueskyService(defaults: defaults, session: session)
_ = try await service.signIn(handle: "reader.example", appPassword: "test-password", authFactorToken: nil)
do {
_ = try await service.publish(
text: "Mixed", replyTo: nil, quotePost: nil, images: [ImageAttachment(data: Data([1]))],
video: VideoAttachment(data: Data([1])))
XCTFail("Expected mixed media to fail")
} catch {
XCTAssertTrue(error is ActionNotSentError)
}
XCTAssertFalse(
StubURLProtocol.recordedRequests.contains { $0.url?.path == "/xrpc/com.atproto.repo.createRecord" })
_ = try await service.publish(
text: "Video", replyTo: nil, quotePost: nil, images: [], video: VideoAttachment(data: Data([1, 2, 3, 4])))
let request = try XCTUnwrap(
StubURLProtocol.recordedRequests.first { $0.url?.path == "/xrpc/com.atproto.repo.createRecord" })
let body = try XCTUnwrap(StubURLProtocol.recordedBody(for: try XCTUnwrap(request.url)))
let object = try XCTUnwrap(JSONSerialization.jsonObject(with: body) as? [String: Any])
let record = try XCTUnwrap(object["record"] as? [String: Any])
let embed = try XCTUnwrap(record["embed"] as? [String: Any])
XCTAssertEqual(embed["$type"] as? String, "app.bsky.embed.video")
XCTAssertNil(embed["alt"])
let blob = try XCTUnwrap(embed["video"] as? [String: Any])
XCTAssertEqual(blob["mimeType"] as? String, "video/mp4")
let videoFile = FileManager.default.temporaryDirectory.appendingPathComponent("\(UUID().uuidString).mp4")
try Data([5, 6, 7, 8]).write(to: videoFile)
defer { try? FileManager.default.removeItem(at: videoFile) }
_ = try await service.publish(
text: "File video", replyTo: nil, quotePost: nil, images: [], video: VideoAttachment(fileURL: videoFile))
XCTAssertEqual(
StubURLProtocol.recordedRequests.filter { $0.url?.path == "/xrpc/app.bsky.video.uploadVideo" }.count, 2)
try await service.signOut()
}
func testFiveImagesUseGalleryEmbed() throws {
let image: [String: Any] = [
"image": ["mimeType": "image/jpeg"], "alt": "Example", "aspectRatio": ["width": 4, "height": 3]
]
let legacy = ATProtoBlueskyService.imageEmbed(Array(repeating: image, count: 4))
XCTAssertEqual(legacy["$type"] as? String, "app.bsky.embed.images")
let gallery = ATProtoBlueskyService.imageEmbed(Array(repeating: image, count: 10))
XCTAssertEqual(gallery["$type"] as? String, "app.bsky.embed.gallery")
let items = try XCTUnwrap(gallery["items"] as? [[String: Any]])
XCTAssertEqual(items.count, 10)
XCTAssertTrue(items.allSatisfy { $0["$type"] as? String == "app.bsky.embed.gallery#image" })
}
func testSavedCustomFeedsAndMissingFeedResponse() async throws {
let suite = "CustomFeeds.\(UUID().uuidString)"
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
let configuration = URLSessionConfiguration.ephemeral
configuration.protocolClasses = [StubURLProtocol.self]
let session = URLSession(configuration: configuration)
let expiry = Int(Date().addingTimeInterval(3600).timeIntervalSince1970)
let payload = Data("{\"exp\":\(expiry)}".utf8).base64EncodedString().replacingOccurrences(of: "=", with: "")
let token = "header.\(payload).signature"
let uri = "at://did:plc:reader/app.bsky.feed.generator/nature"
var legacy = false
var status = 200
StubURLProtocol.handler = { request in
try self.customFeedResponse(request, token: token, uri: uri, legacy: legacy, status: status)
}
defer {
StubURLProtocol.handler = nil
session.invalidateAndCancel()
defaults.removePersistentDomain(forName: suite)
}
let service = ATProtoBlueskyService(defaults: defaults, session: session)
_ = try await service.signIn(handle: "reader.example", appPassword: "test-password", authFactorToken: nil)
let expected = [CustomFeed(id: uri, name: "Nature", avatarURL: URL(string: "https://example.test/avatar.png"))]
let feeds = try await service.loadSubscribedFeeds()
XCTAssertEqual(feeds, expected)
legacy = true
let legacyFeeds = try await service.loadSubscribedFeeds()
XCTAssertEqual(legacyFeeds, expected)
let page = try await service.loadCustomFeed(uri: uri, cursor: "next")
XCTAssertEqual(page.cursor, "last")
_ = try await service.loadFollowingFeed(cursor: nil)
status = 404
do {
_ = try await service.loadCustomFeed(uri: uri, cursor: "next")
XCTFail("Expected a missing feed")
} catch { XCTAssertTrue(error is CustomFeedError, "Unexpected error: \(String(reflecting: error))") }
status = 503
do {
_ = try await service.loadCustomFeed(uri: uri, cursor: "next")
XCTFail("Expected a server error")
} catch { XCTAssertFalse(error is CustomFeedError) }
}
private func videoUploadResponse(_ request: URLRequest, token: String) throws -> (Int, Data) {
switch request.url?.path {
case "/xrpc/com.atproto.identity.resolveHandle": return (200, Data("{\"did\":\"did:plc:reader\"}".utf8))
case "/did:plc:reader":
return (
200,
Data(
("{\"id\":\"did:plc:reader\",\"service\":[{\"id\":\"#atproto_pds\","
+ "\"type\":\"AtprotoPersonalDataServer\","
+ "\"serviceEndpoint\":\"https://reader.example.test\"}]}")
.utf8)
)
case "/xrpc/com.atproto.server.createSession":
return (
200,
Data(
("{\"handle\":\"reader.example\",\"did\":\"did:plc:reader\","
+ "\"accessJwt\":\"\(token)\",\"refreshJwt\":\"refresh\"}")
.utf8)
)
case "/xrpc/app.bsky.actor.getProfile":
return (200, Data("{\"did\":\"did:plc:reader\",\"handle\":\"reader.example\"}".utf8))
case "/xrpc/com.atproto.server.getServiceAuth":
let query = URLComponents(url: request.url!, resolvingAgainstBaseURL: false)?.queryItems
XCTAssertEqual(query?.first { $0.name == "aud" }?.value, "did:web:reader.example.test")
XCTAssertEqual(query?.first { $0.name == "lxm" }?.value, "com.atproto.repo.uploadBlob")
return (200, Data("{\"token\":\"video-service-token\"}".utf8))
case "/xrpc/app.bsky.video.uploadVideo":
XCTAssertEqual(request.value(forHTTPHeaderField: "Authorization"), "Bearer video-service-token")
XCTAssertEqual(request.value(forHTTPHeaderField: "Content-Type"), "video/mp4")
return (200, Data("{\"jobId\":\"job-1\",\"state\":\"JOB_STATE_ENCODING\"}".utf8))
case "/xrpc/app.bsky.video.getJobStatus":
return (
200,
Data(
("{\"jobStatus\":{\"jobId\":\"job-1\",\"state\":\"JOB_STATE_COMPLETED\","
+ "\"blob\":{\"$type\":\"blob\",\"ref\":{\"$link\":\"bafk-video\"},"
+ "\"mimeType\":\"video/mp4\",\"size\":4}}}")
.utf8)
)
case "/xrpc/com.atproto.repo.createRecord":
return (200, Data("{\"uri\":\"at://did:plc:reader/app.bsky.feed.post/new\",\"cid\":\"cid\"}".utf8))
default:
XCTFail("Unexpected request: \(request.url?.absoluteString ?? "nil")")
return (404, Data())
}
}
private func customFeedResponse(_ request: URLRequest, token: String, uri: String, legacy: Bool, status: Int) throws
-> (Int, Data) {
if let response = try customFeedResponseIdentity(
request, token: token, uri: uri, legacy: legacy, status: status) {
return response
}
return try customFeedResponseAction(request, token: token, uri: uri, legacy: legacy, status: status)
}
private func customFeedResponseIdentity(
_ request: URLRequest, token: String, uri: String, legacy: Bool, status: Int
) throws -> (Int, Data)? {
switch request.url?.path {
case "/xrpc/com.atproto.identity.resolveHandle": return (200, Data("{\"did\":\"did:plc:reader\"}".utf8))
case "/did:plc:reader":
return (
200,
Data(
("{\"id\":\"did:plc:reader\",\"service\":[{\"id\":\"#atproto_pds\","
+ "\"type\":\"AtprotoPersonalDataServer\","
+ "\"serviceEndpoint\":\"https://reader.example.test\"}]}")
.utf8)
)
case "/xrpc/com.atproto.server.createSession":
return (
200,
Data(
("{\"handle\":\"reader.example\",\"did\":\"did:plc:reader\","
+ "\"accessJwt\":\"\(token)\",\"refreshJwt\":\"refresh\"}")
.utf8)
)
case "/xrpc/app.bsky.actor.getProfile":
return (200, Data("{\"did\":\"did:plc:reader\",\"handle\":\"reader.example\"}".utf8))
default: return nil
}
}
private func customFeedResponseAction(_ request: URLRequest, token: String, uri: String, legacy: Bool, status: Int)
throws -> (Int, Data) {
switch request.url?.path {
case "/xrpc/app.bsky.actor.getPreferences":
let pref: [String: Any] =
legacy
? ["$type": "app.bsky.actor.defs#savedFeedsPref", "saved": [uri, uri], "pinned": [uri]]
: [
"$type": "app.bsky.actor.defs#savedFeedsPrefV2",
"items": [
["id": "one", "type": "feed", "value": uri, "pinned": false],
[
"id": "two", "type": "feed",
"value": "at://did:plc:reader/app.bsky.feed.generator/deleted", "pinned": true
],
[
"id": "three", "type": "list",
"value": "at://did:plc:reader/app.bsky.graph.list/friends", "pinned": true
]
]
]
return (200, try JSONSerialization.data(withJSONObject: ["preferences": [pref]]))
case "/xrpc/app.bsky.feed.getFeedGenerators":
return (
200,
try JSONSerialization.data(withJSONObject: [
"feeds": [
[
"uri": uri, "cid": "cid", "did": "did:web:feed.example", "displayName": "Nature",
"avatar": "https://example.test/avatar.png",
"creator": ["did": "did:plc:reader", "handle": "reader.example"],
"indexedAt": "2024-05-06T12:34:56Z"
]
]
])
)
case "/xrpc/app.bsky.feed.getFeed":
let query = URLComponents(url: request.url!, resolvingAgainstBaseURL: false)?.queryItems
XCTAssertEqual(query?.first { $0.name == "feed" }?.value, uri)
XCTAssertEqual(query?.first { $0.name == "cursor" }?.value, "next")
XCTAssertEqual(query?.first { $0.name == "limit" }?.value, "70")
return status == 200
? (200, Data("{\"feed\":[],\"cursor\":\"last\"}".utf8))
: (status, Data("{\"error\":\"NotFound\",\"message\":\"Feed not found\"}".utf8))
case "/xrpc/app.bsky.feed.getTimeline":
let query = URLComponents(url: request.url!, resolvingAgainstBaseURL: false)?.queryItems
XCTAssertEqual(query?.first { $0.name == "limit" }?.value, "70")
return (200, Data("{\"feed\":[]}".utf8))
default:
XCTFail("Unexpected request: \(request.url?.absoluteString ?? "nil")")
return (404, Data("{}".utf8))
}
}
}