-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathapi.js
365 lines (274 loc) · 8.98 KB
/
api.js
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
/**
* Thrown when the response is technically a "success" one, but the returned data is not what it should be.
*/
class ResponseDataError extends Error {}
/**
* Thrown when the passed URL is not a supported post URL on bsky.app.
*/
class URLError extends Error {
/** @param {string} message */
constructor(message) {
super(message);
}
}
/**
* Caches the mapping of handles to DIDs to avoid unnecessary API calls to resolveHandle or getProfile.
*/
class HandleCache {
prepareCache() {
if (!this.cache) {
this.cache = JSON.parse(localStorage.getItem('handleCache') ?? '{}');
}
}
saveCache() {
localStorage.setItem('handleCache', JSON.stringify(this.cache));
}
/** @param {string} handle, @returns {string | undefined} */
getHandleDid(handle) {
this.prepareCache();
return this.cache[handle];
}
/** @param {string} handle, @param {string} did */
setHandleDid(handle, did) {
this.prepareCache();
this.cache[handle] = did;
this.saveCache();
}
/** @param {string} did, @returns {string | undefined} */
findHandleByDid(did) {
this.prepareCache();
let found = Object.entries(this.cache).find((e) => e[1] == did);
return found ? found[0] : undefined;
}
}
/**
* Stores user's access tokens and data in local storage after they log in.
*/
class LocalStorageConfig {
constructor() {
let data = localStorage.getItem('userData');
this.user = data ? JSON.parse(data) : {};
}
save() {
if (this.user) {
localStorage.setItem('userData', JSON.stringify(this.user));
} else {
localStorage.removeItem('userData');
}
}
}
/**
* API client for connecting to the Bluesky XRPC API (authenticated or not).
*/
class BlueskyAPI extends Minisky {
/** @param {string | undefined} host, @param {boolean} useAuthentication */
constructor(host, useAuthentication) {
super(host, useAuthentication ? new LocalStorageConfig() : undefined);
this.handleCache = new HandleCache();
this.profiles = {};
}
/** @param {json} author */
cacheProfile(author) {
this.profiles[author.did] = author;
this.profiles[author.handle] = author;
this.handleCache.setHandleDid(author.handle, author.did);
}
/** @param {string} did, @returns {string | undefined} */
findHandleByDid(did) {
return this.handleCache.findHandleByDid(did);
}
/** @param {string} did, @returns {Promise<string>} */
async fetchHandleForDid(did) {
let cachedHandle = this.handleCache.findHandleByDid(did);
if (cachedHandle) {
return cachedHandle;
} else {
let author = await this.loadUserProfile(did);
return author.handle;
}
}
/** @param {string} string, @returns {[string, string]} */
static parsePostURL(string) {
let url;
try {
url = new URL(string);
} catch (error) {
throw new URLError(`${error}`);
}
if (url.protocol != 'https:') {
throw new URLError('URL must start with https://');
}
if (!(url.host == 'staging.bsky.app' || url.host == 'bsky.app' || url.host == 'main.bsky.dev')) {
throw new URLError('Only bsky.app URLs are supported');
}
let parts = url.pathname.split('/');
if (parts.length < 5 || parts[1] != 'profile' || parts[3] != 'post') {
throw new URLError('This is not a valid thread URL');
}
let handle = parts[2];
let postId = parts[4];
return [handle, postId];
}
/** @param {string} handle, @returns {Promise<string>} */
async resolveHandle(handle) {
let cachedDid = this.handleCache.getHandleDid(handle);
if (cachedDid) {
return cachedDid;
} else {
let json = await this.getRequest('com.atproto.identity.resolveHandle', { handle }, { auth: false });
let did = json['did'];
if (did) {
this.handleCache.setHandleDid(handle, did);
return did;
} else {
throw new ResponseDataError('Missing DID in response: ' + JSON.stringify(json));
}
}
}
/** @param {string} url, @returns {Promise<json>} */
async loadThreadByURL(url) {
let [handle, postId] = BlueskyAPI.parsePostURL(url);
return await this.loadThreadById(handle, postId);
}
/** @param {string} author, @param {string} postId, @returns {Promise<json>} */
async loadThreadById(author, postId) {
let did = author.startsWith('did:') ? author : await this.resolveHandle(author);
let postURI = `at://${did}/app.bsky.feed.post/${postId}`;
return await this.loadThreadByAtURI(postURI);
}
/** @param {string} uri, @returns {Promise<json>} */
async loadThreadByAtURI(uri) {
return await this.getRequest('app.bsky.feed.getPostThread', { uri: uri, depth: 10 });
}
/** @param {string} handle, @returns {Promise<json>} */
async loadUserProfile(handle) {
if (this.profiles[handle]) {
return this.profiles[handle];
} else {
let profile = await this.getRequest('app.bsky.actor.getProfile', { actor: handle });
this.cacheProfile(profile);
return profile;
}
}
/** @returns {Promise<json | undefined>} */
async getCurrentUserAvatar() {
let json = await this.getRequest('com.atproto.repo.getRecord', {
repo: this.user.did,
collection: 'app.bsky.actor.profile',
rkey: 'self'
});
return json.value.avatar;
}
/** @returns {Promise<string?>} */
async loadCurrentUserAvatar() {
if (!this.config || !this.config.user) {
throw new AuthError("User isn't logged in");
}
let avatar = await this.getCurrentUserAvatar();
if (avatar) {
let url = `https://cdn.bsky.app/img/avatar/plain/${this.user.did}/${avatar.ref.$link}@jpeg`;
this.config.user.avatar = url;
this.config.save();
return url;
} else {
return null;
}
}
/** @param {string} uri, @returns {Promise<json[]>} */
async getReplies(uri) {
let json = await this.getRequest('blue.feeds.post.getReplies', { uri });
return json.replies;
}
/** @param {string} uri, @returns {Promise<number>} */
async getQuoteCount(uri) {
let json = await this.getRequest('blue.feeds.post.getQuoteCount', { uri });
return json.quoteCount;
}
/** @param {string} url, @param {string | undefined} cursor, @returns {Promise<json>} */
async getQuotes(url, cursor = undefined) {
let [handle, postId] = BlueskyAPI.parsePostURL(url);
let did = handle.startsWith('did:') ? handle : await appView.resolveHandle(handle);
let postURI = `at://${did}/app.bsky.feed.post/${postId}`;
let params = { uri: postURI };
if (cursor) {
params['cursor'] = cursor;
}
return await this.getRequest('blue.feeds.post.getQuotes', params);
}
/** @param {string} hashtag, @param {string | undefined} cursor, @returns {Promise<json>} */
async getHashtagFeed(hashtag, cursor = undefined) {
let params = { q: '#' + hashtag, limit: 50, sort: 'latest' };
if (cursor) {
params['cursor'] = cursor;
}
return await this.getRequest('app.bsky.feed.searchPosts', params);
}
async loadNotifications(cursor) {
let params = { limit: 100 };
if (cursor) {
params.cursor = cursor;
}
return await this.getRequest('app.bsky.notification.listNotifications', params);
}
async loadMentions(cursor) {
let response = await this.loadNotifications(cursor);
let mentions = response.notifications.filter(x => ['reply', 'mention'].includes(x.reason));
let uris = mentions.map(x => x['uri']);
let posts = [];
for (let i = 0; i < uris.length; i += 25) {
let batch = await this.loadPosts(uris.slice(i, i + 25));
posts = posts.concat(batch);
}
return { cursor: response.cursor, posts };
}
/** @param {string} postURI, @returns {Promise<json>} */
async loadPost(postURI) {
let posts = await this.loadPosts([postURI]);
if (posts.length == 1) {
return posts[0];
} else {
throw new ResponseDataError('Post not found');
}
}
/** @param {string} postURI, @returns {Promise<json | undefined>} */
async loadPostIfExists(postURI) {
let posts = await this.loadPosts([postURI]);
return posts[0];
}
/** @param {string[]} uris, @returns {Promise<object[]>} */
async loadPosts(uris) {
if (uris.length > 0) {
let response = await this.getRequest('app.bsky.feed.getPosts', { uris });
return response.posts;
} else {
return [];
}
}
/** @param {Post} post, @returns {Promise<json>} */
async likePost(post) {
return await this.postRequest('com.atproto.repo.createRecord', {
repo: this.user.did,
collection: 'app.bsky.feed.like',
record: {
subject: {
uri: post.uri,
cid: post.cid
},
createdAt: new Date().toISOString()
}
});
}
/** @param {string} uri, @returns {Promise<void>} */
async removeLike(uri) {
let { rkey } = atURI(uri);
await this.postRequest('com.atproto.repo.deleteRecord', {
repo: this.user.did,
collection: 'app.bsky.feed.like',
rkey: rkey
});
}
resetTokens() {
delete this.user.avatar;
super.resetTokens();
}
}