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
import Foundation
import XCTest
@testable import OldFella
extension ATProtoServiceTests {
func testPublishEmbedsQuoteAndBuildsUTF8Facets() async throws {
let suiteName = "OldFellaFacetPublishTests.\(UUID().uuidString)"
let defaults = try XCTUnwrap(UserDefaults(suiteName: suiteName))
let configuration = URLSessionConfiguration.ephemeral
configuration.protocolClasses = [StubURLProtocol.self]
let session = URLSession(configuration: configuration)
let futureExpiry = Int(Date().addingTimeInterval(3600).timeIntervalSince1970)
let payload = Data("{\"exp\":\(futureExpiry)}".utf8).base64EncodedString()
.replacingOccurrences(of: "+", with: "-")
.replacingOccurrences(of: "/", with: "_")
.replacingOccurrences(of: "=", with: "")
let token = "header.\(payload).signature"
let quote = Post(
id: "at://did:plc:quoted/app.bsky.feed.post/one", cid: "quote-cid",
author: Post.Author(id: "did:plc:quoted", name: "Quoted", handle: "quoted.example"), text: "Quoted",
likeCount: 0, repostCount: 0, isLiked: false, isReposted: false, imageURLs: [], replyIDs: [])
StubURLProtocol.clearRequests()
StubURLProtocol.handler = { request in
try self.facetPublishResponse(request, token: token, quote: quote)
}
defer {
StubURLProtocol.handler = nil
session.invalidateAndCancel()
defaults.removePersistentDomain(forName: suiteName)
}
let service = ATProtoBlueskyService(defaults: defaults, session: session)
_ = try await service.signIn(
handle: "reader.example", appPassword: "dedicated-app-password", authFactorToken: nil)
let text = "🌤️ visit https://example.com/path#section @friend.example #sky @missing.example"
let post = try await service.publish(text: text, replyTo: nil, quotePost: quote, images: [])
try assertPublishedFacets(post, text: text, quote: quote)
try await assertPostTextLimits(service, quote: quote)
try await assertIncompleteQuote(service, quote: quote)
try await service.signOut()
}
private func facetPublishResponse(_ request: URLRequest, token: String, quote: Post) throws -> (Int, Data) {
switch request.url?.path {
case "/xrpc/com.atproto.identity.resolveHandle":
let handle = URLComponents(url: request.url!, resolvingAgainstBaseURL: false)?.queryItems?.first(
where: { $0.name == "handle" })?.value
if handle == "friend.example" {
return (200, Data("{\"did\":\"did:plc:friend\"}".utf8))
}
if handle == "reader.example" {
return (200, Data("{\"did\":\"did:plc:reader\"}".utf8))
}
return (500, Data("{\"error\":\"NotFound\"}".utf8))
case "/did:plc:reader":
return (
200,
Data(
("{\"id\":\"did:plc:reader\",\"service\":[{\"id\":\"#atproto_pds\","
+ "\"type\":\"AtprotoPersonalDataServer\","
+ "\"serviceEndpoint\":\"https://facet-pds.example.test\"}]}")
.utf8)
)
case "/xrpc/com.atproto.server.createSession":
return (
200,
Data(
("{\"handle\":\"reader.example\",\"did\":\"did:plc:reader\","
+ "\"accessJwt\":\"\(token)\",\"refreshJwt\":\"refresh-token\"}")
.utf8)
)
case "/xrpc/app.bsky.actor.getProfile":
return (200, Data("{\"did\":\"did:plc:reader\",\"handle\":\"reader.example\"}".utf8))
case "/xrpc/com.atproto.repo.createRecord":
return (
200,
Data(
"{\"uri\":\"at://did:plc:reader/app.bsky.feed.post/published\",\"cid\":\"published-cid\"}".utf8)
)
default:
return (404, Data("{\"error\":\"NotFound\"}".utf8))
}
}
private func decodePublishedFacet(_ facet: [String: Any]) -> PostFacet? {
guard let index = facet["index"] as? [String: Int],
let start = index["byteStart"], let end = index["byteEnd"],
let features = facet["features"] as? [[String: String]],
let feature = features.first,
let type = feature["$type"]
else { return nil }
switch type {
case "app.bsky.richtext.facet#link":
return PostFacet(byteStart: start, byteEnd: end, feature: .link(URL(string: feature["uri"]!)!))
case "app.bsky.richtext.facet#mention":
return PostFacet(byteStart: start, byteEnd: end, feature: .mention(feature["did"]!))
case "app.bsky.richtext.facet#tag":
return PostFacet(byteStart: start, byteEnd: end, feature: .tag(feature["tag"]!))
default: return nil
}
}
private func assertPublishedFacets(_ post: Post, text: String, quote: Post) throws {
let createRequest = try XCTUnwrap(
StubURLProtocol.recordedRequests.first { $0.url?.path == "/xrpc/com.atproto.repo.createRecord" })
let requestBody = try XCTUnwrap(StubURLProtocol.recordedBody(for: createRequest.url!))
let payloadObject = try XCTUnwrap(JSONSerialization.jsonObject(with: requestBody) as? [String: Any])
let record = try XCTUnwrap(payloadObject["record"] as? [String: Any])
let finalText = try XCTUnwrap(record["text"] as? String)
let facets = try XCTUnwrap(record["facets"] as? [[String: Any]])
XCTAssertEqual(post.text, finalText)
XCTAssertEqual(finalText, text)
XCTAssertEqual(facets.count, 3)
let embed = try XCTUnwrap(record["embed"] as? [String: Any])
XCTAssertEqual(embed["$type"] as? String, "app.bsky.embed.record")
XCTAssertEqual(
embed["record"] as? [String: String],
["$type": "com.atproto.repo.strongRef", "uri": quote.id, "cid": quote.cid])
let decoded = facets.compactMap(decodePublishedFacet)
let expectedFacets: [PostFacet] = [
PostFacet(
byteStart: byteRange(of: "https://example.com/path#section", in: finalText).0,
byteEnd: byteRange(of: "https://example.com/path#section", in: finalText).1,
feature: .link(URL(string: "https://example.com/path#section")!)),
PostFacet(
byteStart: byteRange(of: "@friend.example", in: finalText).0,
byteEnd: byteRange(of: "@friend.example", in: finalText).1, feature: .mention("did:plc:friend")),
PostFacet(
byteStart: byteRange(of: "#sky", in: finalText).0, byteEnd: byteRange(of: "#sky", in: finalText).1,
feature: .tag("sky"))
]
XCTAssertEqual(decoded, expectedFacets)
}
private func assertIncompleteQuote(_ service: ATProtoBlueskyService, quote: Post) async throws {
var incompleteQuote = quote
incompleteQuote.cid = ""
StubURLProtocol.clearRequests()
do {
_ = try await service.publish(
text: "A quote", replyTo: nil, quotePost: incompleteQuote, images: [ImageAttachment(data: Data())])
XCTFail("Expected a missing post reference error")
} catch ServiceError.postReferenceUnavailable {
XCTAssertTrue(StubURLProtocol.recordedRequests.isEmpty)
}
}
private func assertPostTextLimits(_ service: ATProtoBlueskyService, quote: Post) async throws {
let combinedCharacter = "👨👩👧👦"
let plainText = String(repeating: combinedCharacter, count: 300)
StubURLProtocol.clearRequests()
let plainPost = try await service.publish(text: plainText, replyTo: nil, quotePost: nil, images: [])
let plainRequest = try XCTUnwrap(
StubURLProtocol.recordedRequests.first { $0.url?.path == "/xrpc/com.atproto.repo.createRecord" })
let plainBody = try XCTUnwrap(StubURLProtocol.recordedBody(for: plainRequest.url!))
let plainPayload = try XCTUnwrap(JSONSerialization.jsonObject(with: plainBody) as? [String: Any])
let plainRecord = try XCTUnwrap(plainPayload["record"] as? [String: Any])
XCTAssertEqual(plainRecord["text"] as? String, plainText)
XCTAssertEqual(plainPost.text, plainText)
let quoteText = String(repeating: combinedCharacter, count: 300)
StubURLProtocol.clearRequests()
let boundaryPost = try await service.publish(text: quoteText, replyTo: nil, quotePost: quote, images: [])
let boundaryRequest = try XCTUnwrap(
StubURLProtocol.recordedRequests.first { $0.url?.path == "/xrpc/com.atproto.repo.createRecord" })
let boundaryBody = try XCTUnwrap(StubURLProtocol.recordedBody(for: boundaryRequest.url!))
let boundaryPayload = try XCTUnwrap(JSONSerialization.jsonObject(with: boundaryBody) as? [String: Any])
let boundaryRecord = try XCTUnwrap(boundaryPayload["record"] as? [String: Any])
XCTAssertEqual(boundaryRecord["text"] as? String, quoteText)
XCTAssertEqual(boundaryPost.text.count, 300)
for (overLimitText, quotedPost) in [
(plainText + combinedCharacter, nil), (quoteText + combinedCharacter, quote)
] {
StubURLProtocol.clearRequests()
do {
_ = try await service.publish(
text: overLimitText, replyTo: nil, quotePost: quotedPost, images: [ImageAttachment(data: Data())])
XCTFail("Expected the post text limit error")
} catch ServiceError.postTextTooLong {
XCTAssertEqual(
ServiceError.postTextTooLong.localizedDescription,
"The post is over 300 characters. Shorten the text and try again.")
}
XCTAssertTrue(StubURLProtocol.recordedRequests.isEmpty)
}
}
}