Files: 77471357a47c8057251ef438e025a95428a78eb8 / index.js
14342 bytesRaw
1 | var fs = require('fs') |
2 | var http = require('http') |
3 | var qs = require('querystring') |
4 | var path = require('path') |
5 | var crypto = require('crypto') |
6 | var pull = require('pull-stream') |
7 | var paramap = require('pull-paramap') |
8 | var sort = require('ssb-sort') |
9 | var toPull = require('stream-to-pull-stream') |
10 | var memo = require('asyncmemo') |
11 | var lru = require('lrucache') |
12 | var serveEmoji = require('emoji-server')() |
13 | var { |
14 | MdRenderer, |
15 | renderEmoji, |
16 | formatMsgs, |
17 | wrapPage, |
18 | renderThread, |
19 | renderAbout, |
20 | renderShowAll, |
21 | renderRssItem, |
22 | wrapRss, |
23 | } = require('./render'); |
24 | |
25 | var appHash = hash([fs.readFileSync(__filename)]) |
26 | |
27 | var urlIdRegex = /^(?:\/(([%&@]|%25|%26|%40)(?:[A-Za-z0-9\/+]|%2[Ff]|%2[Bb]){43}(?:=|%3[Dd])\.(?:sha256|ed25519))(?:\.([^?]*))?|(\/.*?))(?:\?(.*))?$/ |
28 | |
29 | function hash(arr) { |
30 | return arr.reduce(function (hash, item) { |
31 | return hash.update(String(item)) |
32 | }, crypto.createHash('sha256')).digest('base64') |
33 | } |
34 | |
35 | exports.name = 'viewer' |
36 | exports.manifest = {} |
37 | exports.version = require('./package').version |
38 | |
39 | exports.init = function (sbot, config) { |
40 | var conf = config.viewer || {} |
41 | |
42 | var about = require('./lib/about') |
43 | |
44 | var getAbout = memo({cache: lru(100)}, about, sbot) |
45 | |
46 | var lastRefresh = Date.now() |
47 | |
48 | function ensureFreshAboutCache(cb) { |
49 | if (about.allAbouts && (lastRefresh - Date.now()) / 1000 < 30 * 60) { |
50 | cb() |
51 | } else { |
52 | sbot.about.get((err, allAbouts) => { |
53 | about.allAbouts = allAbouts |
54 | cb() |
55 | }) |
56 | } |
57 | } |
58 | |
59 | var getMsg = memo({cache: lru(100)}, getMsgWithValue, sbot) |
60 | |
61 | var base = conf.base || '/' |
62 | var defaultOpts = { |
63 | base: base, |
64 | msg_base: conf.msg_base || base, |
65 | feed_base: conf.feed_base || base, |
66 | blob_base: conf.blob_base || base, |
67 | img_base: conf.img_base || base, |
68 | emoji_base: conf.emoji_base || (base + 'emoji/'), |
69 | } |
70 | |
71 | defaultOpts.marked = { |
72 | gfm: true, |
73 | mentions: true, |
74 | tables: true, |
75 | breaks: true, |
76 | pedantic: false, |
77 | sanitize: true, |
78 | smartLists: true, |
79 | smartypants: false, |
80 | emoji: renderEmoji, |
81 | renderer: new MdRenderer(defaultOpts) |
82 | } |
83 | |
84 | exports.serveFeed = function(req, res, feedId, ext) { |
85 | ensureFreshAboutCache(() => { |
86 | console.log("serving feed: " + feedId) |
87 | |
88 | var showAll = req.url.endsWith("?showAll"); |
89 | |
90 | getAbout(feedId, function (err, about) { |
91 | if (err) return respond(res, 500, err.stack || err) |
92 | |
93 | function render() { |
94 | switch (ext) { |
95 | case 'rss': |
96 | return pull( |
97 | // formatMsgs(feedId, ext, defaultOpts) |
98 | renderRssItem(defaultOpts), wrapRss(about.name, defaultOpts) |
99 | ); |
100 | default: |
101 | return pull( |
102 | renderAbout(defaultOpts, about, |
103 | renderShowAll(req.url)), wrapPage(about.name) |
104 | ); |
105 | } |
106 | } |
107 | |
108 | pull( |
109 | sbot.createUserStream({ id: feedId, reverse: true, |
110 | limit: showAll ? -1 : (ext == 'rss' ? 25 : 10) }), |
111 | pull.collect(function (err, logs) { |
112 | if (err) return respond(res, 500, err.stack || err) |
113 | res.writeHead(200, { |
114 | 'Content-Type': ctype(ext) |
115 | }) |
116 | pull( |
117 | pull.values(logs), |
118 | paramap(addAuthorAbout, 8), |
119 | paramap(addBlog, 8), |
120 | paramap(addFollowAbout, 8), |
121 | paramap(addVoteMessage, 8), |
122 | paramap(addGitLinks, 8), |
123 | render(), |
124 | toPull(res, function (err) { |
125 | if (err) console.error('[viewer]', err) |
126 | }) |
127 | ) |
128 | }) |
129 | ) |
130 | }) |
131 | }) |
132 | } |
133 | |
134 | exports.serveUserFeed = function(req, res, feedId) { |
135 | ensureFreshAboutCache(() => { |
136 | |
137 | console.log("serving user feed: " + feedId) |
138 | |
139 | var following = [] |
140 | var channelSubscriptions = [] |
141 | |
142 | getAbout(feedId, function (err, about) { |
143 | pull( |
144 | sbot.createUserStream({ id: feedId }), |
145 | pull.filter((msg) => { |
146 | return !msg.value || |
147 | msg.value.content.type == 'contact' || |
148 | (msg.value.content.type == 'channel' && |
149 | typeof msg.value.content.subscribed != 'undefined') |
150 | }), |
151 | pull.collect(function (err, msgs) { |
152 | msgs.forEach((msg) => { |
153 | if (msg.value.content.type == 'contact') |
154 | { |
155 | if (msg.value.content.following) |
156 | following[msg.value.content.contact] = 1 |
157 | else |
158 | delete following[msg.value.content.contact] |
159 | } |
160 | else // channel subscription |
161 | { |
162 | if (msg.value.content.subscribed) |
163 | channelSubscriptions[msg.value.content.channel] = 1 |
164 | else |
165 | delete channelSubscriptions[msg.value.content.channel] |
166 | } |
167 | }) |
168 | |
169 | serveFeeds(req, res, following, channelSubscriptions, feedId, |
170 | 'user feed ' + (about ? about.name : "")) |
171 | }) |
172 | ) |
173 | }) |
174 | }) |
175 | } |
176 | |
177 | function serveFeeds(req, res, following, channelSubscriptions, feedId, name) { |
178 | var feedOpts = Object.assign({}, defaultOpts, { |
179 | renderPrivate: false, |
180 | renderSubscribe: false, |
181 | renderVote: false, |
182 | renderTalenet: false, |
183 | renderChess: false, |
184 | renderFollow: false, |
185 | renderPub: false, |
186 | renderAbout: false |
187 | }) |
188 | |
189 | pull( |
190 | sbot.createLogStream({ reverse: true, limit: 5000 }), |
191 | pull.filter((msg) => { |
192 | return !msg.value || |
193 | (msg.value.author in following || |
194 | msg.value.content.channel in channelSubscriptions) |
195 | }), |
196 | pull.take(150), |
197 | pull.collect(function (err, logs) { |
198 | if (err) return respond(res, 500, err.stack || err) |
199 | res.writeHead(200, { |
200 | 'Content-Type': ctype("html") |
201 | }) |
202 | pull( |
203 | pull.values(logs), |
204 | paramap(addAuthorAbout, 8), |
205 | paramap(addBlog, 8), |
206 | paramap(addFollowAbout, 8), |
207 | paramap(addVoteMessage, 8), |
208 | paramap(addGitLinks, 8), |
209 | pull(renderThread(feedOpts), wrapPage(name)), |
210 | toPull(res, function (err) { |
211 | if (err) console.error('[viewer]', err) |
212 | }) |
213 | ) |
214 | }) |
215 | ) |
216 | } |
217 | |
218 | exports.serveChannel = function(req, res, channelId) { |
219 | ensureFreshAboutCache(() => { |
220 | |
221 | console.log("serving channel: " + channelId) |
222 | |
223 | var showAll = req.url.endsWith("?showAll") |
224 | |
225 | pull( |
226 | sbot.query.read({ limit: showAll ? 300 : 10, reverse: true, |
227 | query: [{$filter: { value: { content: { channel: channelId }}}}]}), |
228 | pull.collect(function (err, logs) { |
229 | if (err) return respond(res, 500, err.stack || err) |
230 | res.writeHead(200, { |
231 | 'Content-Type': ctype("html") |
232 | }) |
233 | pull( |
234 | pull.values(logs), |
235 | paramap(addAuthorAbout, 8), |
236 | paramap(addBlog, 8), |
237 | paramap(addVoteMessage, 8), |
238 | pull(renderThread(defaultOpts, '', renderShowAll(req.url)), |
239 | wrapPage('#' + channelId)), |
240 | toPull(res, function (err) { |
241 | if (err) console.error('[viewer]', err) |
242 | }) |
243 | ) |
244 | }) |
245 | ) |
246 | }) |
247 | } |
248 | |
249 | exports.serveId = function(req, res, id, ext, query) { |
250 | ensureFreshAboutCache(() => { |
251 | |
252 | var q = query ? qs.parse(query) : {} |
253 | var includeRoot = !('noroot' in q) |
254 | var base = q.base || conf.base |
255 | var baseToken |
256 | if (!base) { |
257 | if (ext === 'js') base = baseToken = '__BASE_' + Math.random() + '_' |
258 | else base = '/' |
259 | } |
260 | var opts = { |
261 | base: base, |
262 | base_token: baseToken, |
263 | msg_base: q.msg_base || conf.msg_base || base, |
264 | feed_base: q.feed_base || conf.feed_base || base, |
265 | blob_base: q.blob_base || conf.blob_base || base, |
266 | img_base: q.img_base || conf.img_base || base, |
267 | emoji_base: q.emoji_base || conf.emoji_base || (base + 'emoji/'), |
268 | } |
269 | opts.marked = { |
270 | gfm: true, |
271 | mentions: true, |
272 | tables: true, |
273 | breaks: true, |
274 | pedantic: false, |
275 | sanitize: true, |
276 | smartLists: true, |
277 | smartypants: false, |
278 | emoji: renderEmoji, |
279 | renderer: new MdRenderer(opts) |
280 | } |
281 | |
282 | var format = formatMsgs(id, ext, opts) |
283 | if (format === null) return respond(res, 415, 'Invalid format') |
284 | |
285 | pull( |
286 | sbot.links({dest: id, values: true }), |
287 | includeRoot && prepend(getMsg, id), |
288 | pull.unique('key'), |
289 | pull.collect(function (err, links) { |
290 | if (err) return respond(res, 500, err.stack || err) |
291 | var etag = hash(sort.heads(links).concat(appHash, ext, qs)) |
292 | if (req.headers['if-none-match'] === etag) return respond(res, 304) |
293 | res.writeHead(200, { |
294 | 'Content-Type': ctype(ext), |
295 | 'etag': etag |
296 | }) |
297 | pull( |
298 | pull.values(sort(links)), |
299 | paramap(addAuthorAbout, 8), |
300 | paramap(addBlog, 8), |
301 | format, |
302 | toPull(res, function (err) { |
303 | if (err) console.error('[viewer]', err) |
304 | }) |
305 | ) |
306 | }) |
307 | ) |
308 | }) |
309 | } |
310 | |
311 | function addFollowAbout(msg, cb) { |
312 | if (msg.value.content.contact) |
313 | getAbout(msg.value.content.contact, function (err, about) { |
314 | if (err) return cb(err) |
315 | msg.value.content.contactAbout = about |
316 | cb(null, msg) |
317 | }) |
318 | else |
319 | cb(null, msg) |
320 | } |
321 | |
322 | function addVoteMessage(msg, cb) { |
323 | if (msg.value.content.type == 'vote' && msg.value.content.vote && msg.value.content.vote.link[0] == '%') |
324 | getMsg(msg.value.content.vote.link, function (err, linkedMsg) { |
325 | if (linkedMsg) |
326 | msg.value.content.vote.linkedText = linkedMsg.value.content.text |
327 | cb(null, msg) |
328 | }) |
329 | else |
330 | cb(null, msg) |
331 | } |
332 | |
333 | function addBlog(msg, cb) { |
334 | if (msg.value && msg.value.content.type == "blog") { |
335 | pull( |
336 | sbot.blobs.get(msg.value.content.blog), |
337 | pull.collect(function(err, blob) { |
338 | msg.value.content.blogContent = blob |
339 | cb(null, msg) |
340 | }) |
341 | ) |
342 | } else |
343 | cb(null, msg) |
344 | } |
345 | |
346 | function addAuthorAbout(msg, cb) { |
347 | getAbout(msg.value.author, function (err, about) { |
348 | if (err) return cb(err) |
349 | msg.author = about |
350 | cb(null, msg) |
351 | }) |
352 | } |
353 | |
354 | function addGitLinks(msg, cb) { |
355 | if (msg.value.content.type == 'git-update') |
356 | getMsg(msg.value.content.repo, function (err, gitRepo) { |
357 | if (gitRepo) |
358 | msg.value.content.repoName = gitRepo.value.content.name |
359 | cb(null, msg) |
360 | }) |
361 | else if (msg.value.content.type == 'issue') |
362 | getMsg(msg.value.content.project, function (err, gitRepo) { |
363 | if (gitRepo) |
364 | msg.value.content.repoName = gitRepo.value.content.name |
365 | cb(null, msg) |
366 | }) |
367 | else |
368 | cb(null, msg) |
369 | } |
370 | } |
371 | |
372 | exports.serveHttp = function (sbot, config) { |
373 | var conf = config.viewer || {} |
374 | var port = conf.port || 8807 |
375 | var host = conf.host || config.host || '::' |
376 | |
377 | var serveAcmeChallenge = require('ssb-acme-validator')(sbot) |
378 | |
379 | http.createServer(serve).listen(port, host, function () { |
380 | console.log('[viewer] Listening on http://' + host + ':' + port) |
381 | }) |
382 | |
383 | function serve(req, res) { |
384 | if (req.method !== 'GET' && req.method !== 'HEAD') { |
385 | return respond(res, 405, 'Method must be GET or HEAD') |
386 | } |
387 | |
388 | var m = urlIdRegex.exec(req.url) |
389 | |
390 | if (req.url.startsWith('/user-feed/')) |
391 | return exports.serveUserFeed(req, res, m[4].substring(m[4].lastIndexOf('user-feed/')+10, 100)) |
392 | else if (req.url.startsWith('/channel/')) |
393 | return exports.serveChannel(req, res, m[4].substring(m[4].lastIndexOf('channel/')+8, 100)) |
394 | else if (req.url.startsWith('/.well-known/acme-challenge')) return serveAcmeChallenge(req, res) |
395 | |
396 | if (m[2] && m[2].length === 3) { |
397 | m[1] = decodeURIComponent(m[1]) |
398 | m[2] = m[1][0] |
399 | } |
400 | switch (m[2]) { |
401 | case '%': return exports.serveId(req, res, m[1], m[3], m[5]) |
402 | case '@': return exports.serveFeed(req, res, m[1], m[3], m[5]) |
403 | case '&': return serveBlob(req, res, sbot, m[1]) |
404 | default: return servePath(req, res, m[4]) |
405 | } |
406 | } |
407 | } |
408 | |
409 | function serveBlob(req, res, sbot, id) { |
410 | if (req.headers['if-none-match'] === id) return respond(res, 304) |
411 | sbot.blobs.has(id, function (err, has) { |
412 | if (err) { |
413 | if (/^invalid/.test(err.message)) return respond(res, 400, err.message) |
414 | else return respond(res, 500, err.message || err) |
415 | } |
416 | if (!has) return respond(res, 404, 'Not found') |
417 | res.writeHead(200, { |
418 | 'Cache-Control': 'public, max-age=315360000', |
419 | 'etag': id |
420 | }) |
421 | pull( |
422 | sbot.blobs.get(id), |
423 | toPull(res, function (err) { |
424 | if (err) console.error('[viewer]', err) |
425 | }) |
426 | ) |
427 | }) |
428 | } |
429 | |
430 | function getMsgWithValue(sbot, id, cb) { |
431 | sbot.get(id, function (err, value) { |
432 | if (err) return cb(err) |
433 | cb(null, {key: id, value: value}) |
434 | }) |
435 | } |
436 | |
437 | function respond(res, status, message) { |
438 | res.writeHead(status) |
439 | res.end(message) |
440 | } |
441 | |
442 | function ctype(name) { |
443 | switch (name && /[^.\/]*$/.exec(name)[0] || 'html') { |
444 | case 'html': return 'text/html' |
445 | case 'js': return 'text/javascript' |
446 | case 'css': return 'text/css' |
447 | case 'json': return 'application/json' |
448 | case 'rss': return 'text/xml' |
449 | } |
450 | } |
451 | |
452 | function servePath(req, res, url) { |
453 | switch (url) { |
454 | case '/robots.txt': return res.end('User-agent: *') |
455 | } |
456 | var m = /^(\/?[^\/]*)(\/.*)?$/.exec(url) |
457 | switch (m[1]) { |
458 | case '/static': return serveStatic(req, res, m[2]) |
459 | case '/emoji': return serveEmoji(req, res, m[2]) |
460 | } |
461 | return respond(res, 404, 'Not found') |
462 | } |
463 | |
464 | function ifModified(req, lastMod) { |
465 | var ifModSince = req.headers['if-modified-since'] |
466 | if (!ifModSince) return false |
467 | var d = new Date(ifModSince) |
468 | return d && Math.floor(d/1000) >= Math.floor(lastMod/1000) |
469 | } |
470 | |
471 | function serveStatic(req, res, file) { |
472 | serveFile(req, res, path.join(__dirname, 'static', file)) |
473 | } |
474 | |
475 | function serveFile(req, res, file) { |
476 | fs.stat(file, function (err, stat) { |
477 | if (err && err.code === 'ENOENT') return respond(res, 404, 'Not found') |
478 | if (err) return respond(res, 500, err.stack || err) |
479 | if (!stat.isFile()) return respond(res, 403, 'May only load files') |
480 | if (ifModified(req, stat.mtime)) return respond(res, 304, 'Not modified') |
481 | res.writeHead(200, { |
482 | 'Content-Type': ctype(file), |
483 | 'Content-Length': stat.size, |
484 | 'Last-Modified': stat.mtime.toGMTString() |
485 | }) |
486 | fs.createReadStream(file).pipe(res) |
487 | }) |
488 | } |
489 | |
490 | function prepend(fn, arg) { |
491 | return function (read) { |
492 | return function (abort, cb) { |
493 | if (fn && !abort) { |
494 | var _fn = fn |
495 | fn = null |
496 | return _fn(arg, function (err, value) { |
497 | if (err) return read(err, function (err) { |
498 | cb(err || true) |
499 | }) |
500 | cb(null, value) |
501 | }) |
502 | } |
503 | read(abort, cb) |
504 | } |
505 | } |
506 | } |
507 |
Built with git-ssb-web