-
Notifications
You must be signed in to change notification settings - Fork 6
/
app.js
409 lines (355 loc) · 12.3 KB
/
app.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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
"use strict";
const express = require("express");
require('express-async-errors');
const { LRUCache } = require("lru-cache");
const nunjucks = require('nunjucks');
const dateFilter = require('nunjucks-date-filter');
const config = require("./config.js");
const domain = config.DOMAIN ?? "bsky.link";
const fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args));
const PORT = process.env.PORT || 3008;
const VALID_URLS = ["bsky.app", "staging.bsky.app"];
const debug_log = true;
function log(s) {
if(debug_log){
console.log(s)
}
}
const app = express();
app.use(express.static("public"));
app.use((err, req, res, next) => {
res.status(500).render("error.njk", {
error: "There was an error loading this page."
});
});
const nun_env = nunjucks.configure('views', {
autoescape: true,
'express': app
});
nun_env.addGlobal('domain', domain);
nun_env.addFilter('date', dateFilter);
nun_env.addFilter('last_path', function(str) {
return str.split('/').pop();
});
nun_env.addFilter('linkify_text', function(r) {
const encoder = new TextEncoder();
let decoder = new TextDecoder();
const text_bytes = encoder.encode(r.text);
const textchunks = [];
let last_offset=0;
if (r.facets){
for (const facet of r.facets){
textchunks.push(decoder.decode(text_bytes.slice(last_offset,facet.index.byteStart)));
let closeLink=false;
for (const f of facet.features){
if (f.uri){
textchunks.push(`<a href='${f.uri}'>`);
closeLink = true;
break;
}
}
textchunks.push(decoder.decode(text_bytes.slice(facet.index.byteStart,facet.index.byteEnd)));
last_offset=facet.index.byteEnd;
if (closeLink){
textchunks.push("</a>");
}
}
}
textchunks.push(decoder.decode(text_bytes.slice(last_offset)));
return textchunks.join('');
});
let token = "";
let auth_token_expires = new Date().getTime();
let refresh = "";
function getAuthToken () {
log("getAuthToken called ");
return fetch("https://bsky.social/xrpc/com.atproto.server.createSession", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
"identifier": config.HANDLE,
"password": config.PASSWORD
})
})
.then (response => {
log(`getAuthToken status:'${response.status}' statusText:'${response.statusText}';`)
return response.json().then((data) => {
//log(data);
if (response.status==200) {
token = data.accessJwt;
refresh = data.refreshJwt;
log(`getAuthToken response: token='${token}'; refresh='${refresh}';`)
auth_token_expires = new Date().getTime() + 1000 *5 * 60 * 30;
} else {
auth_token_expires = new Date().getTime();
}
})
})
.catch(err =>{
//catch err
console.log(err);
});
}
function refreshAuthToken () {
if (refresh==="") {
log("refreshAuthToken called without refresh token;");
return getAuthToken();
}
log("refreshAuthToken called with: token='"+token+"'; refresh='"+refresh+"';");
return fetch("https://bsky.social/xrpc/com.atproto.server.refreshSession", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${refresh}`
}
})
.then (response => {
log(`refreshAuthToken status:'${response.status}' statusText:'${response.statusText}';`)
return response.json().then((data) => {
//log(data);
if (response.status==200) {
token = data.accessJwt;
refresh = data.refreshJwt;
auth_token_expires = new Date().getTime() + 1000 *5 * 60 * 30;
log(`refreshAuthToken response: token='${token}'; refresh='${refresh}';`)
} else {
return getAuthToken();
}
})
})
.catch(err =>{
//catch err
console.log(err);
});
}
function flattenReplies (replies, author_handle, iteration = 0) {
// replies are nested objects of .replies, so we need to flatten them
let all_replies = [];
if (iteration > 20) {
return all_replies;
}
if (!replies || replies.length == 0) {
return all_replies;
}
for (const reply of replies) {
if (reply?.post?.author?.handle != author_handle) {
continue;
}
all_replies.push(reply);
if (reply.replies && reply.replies.length > 0) {
all_replies = all_replies.concat(flattenReplies(reply.replies, author_handle, iteration + 1));
}
}
return all_replies;
}
const options = {
max: 500,
// for use with tracking overall storage size
maxSize: 5000,
sizeCalculation: (value, key) => {
return 1
},
// how long to live in ms
ttl: 1000 * 60 * 5,
// return stale items before removing from cache?
allowStale: false,
updateAgeOnGet: false,
updateAgeOnHas: false,
}
const cache = new LRUCache(options);
app.route("/").get(async (req, res) => {
if (new Date().getTime() > auth_token_expires) {
await refreshAuthToken();
}
const url = req.query.url;
let parsed_url;
if (!url) {
// show home
res.render("home.njk");
return;
}
try {
parsed_url = new URL(url);
} catch (e) {
res.render("error.njk", {
error: `Invalid URL: '${url}'`
});
return;
}
const domain = parsed_url.hostname;
if (!VALID_URLS.includes(domain)) {
res.render("error.njk", {
error: `Not a known Bluesky host '${domain}'`
});
return;
}
const show_thread = (req.query.show_thread == "on") || (req.query.show_thread == "t"); //support legacy value of 't' for existing URLs
const hide_parent = req.query.hide_parent == "on";
const handle = parsed_url.pathname.split("/")[2];
const post_id = parsed_url.pathname.split("/")[4];
if (!handle || !post_id) {
res.render("error.njk", {
error: `Empty handle '${handle}' or post '${post_id}'`
});
return;
}
let query_parts = [];
if (show_thread){
query_parts.push("show_thread=on");
}
if (hide_parent){
query_parts.push("hide_parent=on");
}
query_parts.push(`url=${url}`);
const query_string = "?" + query_parts.join("&");
if (cache.has(query_string)) {
const data = cache.get(query_string);
res.render("post.njk", data);
return;
}
// log("resolveHandle fetch: token='"+token+"'; refresh='"+refresh+"';");
return fetch("https://bsky.social/xrpc/com.atproto.identity.resolveHandle?handle=" + handle, {
method: "GET",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + token
}
}).then((response) => {
log("resolveHandle fetch: status='"+response.status+"'; statusText='"+response.statusText+"';");
response.json().then((did) => {
// log("getPostThread fetch: token='"+token+"'; refresh='"+refresh+"';");
fetch(`https://bsky.social/xrpc/app.bsky.feed.getPostThread?uri=at://${did.did}/app.bsky.feed.post/${post_id}`, {
method: "GET",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + token
},
}).then((response) => {
log("getPostThread fetch: status='"+response.status+"'; statusText='"+response.statusText+"';");
if (response.status !=200){
auth_token_expires = new Date().getTime();
res.render("error.njk", {
error: "Connection problem, try reloading"
});
return;
}
response.json().then((data) => {
if (data && data.thread && data.thread.post) {
// eschew preprocessing
} else {
res.render("error.njk", {
error: "No thread or post"
});
return;
}
const author_handle = data.thread.post?.author?.handle;
const flat_replies = flattenReplies(data.thread.replies, author_handle);
const response_data = {
thread: data.thread,
url: "https://"+domain+"/" + query_string,
post_url: url,
show_thread: show_thread,
hide_parent: hide_parent,
flat_replies: flat_replies,
};
cache.set(query_string, response_data);
res.render("post.njk", response_data);
});
});
});
}).catch(err =>{
console.log(err);
res.send("Err<pre>"+JSON.stringify(err,null,'')+"</pre>")
});
});
// app.route("/feed").get(async (req, res) => {
// if (new Date().getTime() > auth_token_expires) {
// await refreshAuthToken();
// }
// const user = req.query.user?req.query.user.toLowerCase():'';
// if (!user) {
// res.redirect('/#emcode');
// return;
// }
// // log("getAuthorFeed fetch: token='"+token+"'; refresh='"+refresh+"';");
// return fetch("https://bsky.social/xrpc/app.bsky.feed.getAuthorFeed?actor=" + user, {
// method: "GET",
// headers: {
// "Content-Type": "application/json",
// "Authorization": "Bearer " + token
// }
// }).then((response) => {
// log("getAuthorFeed fetch: status='"+response.status+"'; statusText='"+response.statusText+"';");
// if (response.status !=200){
// auth_token_expires = new Date().getTime();
// res.render("error.njk", {
// error: "Connection problem, try reloading"
// });
// return;
// }
// response.json().then((data) => {
// res.render("feed.njk", {
// author: user,
// posts: data.feed,
// });
// });
// }).catch(err =>{
// console.log(err);
// res.send("Err<pre>"+JSON.stringify(err,null,'')+"</pre>")
// });
// });
app.route("/getfeed").get(async (req, res) => {
if (new Date().getTime() > auth_token_expires) {
await refreshAuthToken();
}
var handle = req.query.handle;
if (!handle) {
res.status(400).send("No handle provided");
return;
}
if (handle.startsWith("https://staging.bsky.app/profile/")) {
handle = handle.replace("https://staging.bsky.app/profile/", "");
} else if (handle.startsWith("https://bsky.app/profile/")) {
handle = handle.replace("https://bsky.app/profile/", "");
}
handle = handle.replace("/", "");
if (handle.startsWith("did:")) {
return fetch("https://bsky.social/xrpc/app.bsky.actor.getProfile?actor=" + handle, {
method: "GET",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + token
}
}).then((response) => {
response.json().then((did) => {
res.json({
"handle": did.handle
});
});
}).catch(err =>{
console.log(err);
res.send("Err<pre>"+JSON.stringify(err,null,'')+"</pre>")
});
} else {
res.json({
"handle": handle
});
}
});
// app.route("/profile/:userHandle/").get(async (req, res) => {
// log(req.params);
// res.redirect(`/feed?user=${req.params.userHandle}`)
// });
app.route("/profile/:userHandle/post/:postId").get(async (req, res) => {
log(req.params);
res.redirect(`/?url=https://bsky.app/profile/${req.params.userHandle}/post/${req.params.postId}`)
});
// run in production mode
app.listen(PORT, () => {
console.log("Server started on port " + PORT);
});
process.on('uncaughtException', async (err) => {
console.log(err);
});