Files: ca9ab26ec6f4f060a9ef89bec77537aa46a99707 / index.js
18581 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 webresolve = require('ssb-web-resolver') |
13 | var serveEmoji = require('emoji-server')() |
14 | var refs = require('ssb-ref') |
15 | var BoxStream = require('pull-box-stream') |
16 | var h = require('hyperscript') |
17 | var { |
18 | MdRenderer, |
19 | renderEmoji, |
20 | formatMsgs, |
21 | wrapPage, |
22 | renderThread, |
23 | renderAbout, |
24 | renderShowAll, |
25 | renderRssItem, |
26 | wrapRss, |
27 | } = require('./render') |
28 | |
29 | var appHash = hash([fs.readFileSync(__filename)]) |
30 | |
31 | var urlIdRegex = /^(?:\/(([%&@]|%25|%26|%40)(?:[A-Za-z0-9\/+]|%2[Ff]|%2[Bb]){43}(?:=|%3[Dd])\.(?:sha256|ed25519))(?:\.([^?]*))?|(\/.*?))(?:\?(.*))?$/ |
32 | |
33 | var zeros = new Buffer(24); zeros.fill(0) |
34 | |
35 | function hash(arr) { |
36 | return arr.reduce(function (hash, item) { |
37 | return hash.update(String(item)) |
38 | }, crypto.createHash('sha256')).digest('base64') |
39 | } |
40 | |
41 | exports.name = 'viewer' |
42 | exports.manifest = {} |
43 | exports.version = require('./package').version |
44 | |
45 | exports.init = function (sbot, config) { |
46 | var conf = config.viewer || {} |
47 | var port = conf.port || 8807 |
48 | var host = conf.host || config.host || '::' |
49 | |
50 | var base = conf.base || '/' |
51 | var defaultOpts = { |
52 | base: base, |
53 | msg_base: conf.msg_base || base, |
54 | feed_base: conf.feed_base || base, |
55 | blob_base: conf.blob_base || base, |
56 | img_base: conf.img_base || base, |
57 | emoji_base: conf.emoji_base || (base + 'emoji/'), |
58 | requireOptIn: conf.require_opt_in == null ? true : conf.require_opt_in, |
59 | } |
60 | |
61 | defaultOpts.marked = { |
62 | gfm: true, |
63 | mentions: true, |
64 | tables: true, |
65 | breaks: true, |
66 | pedantic: false, |
67 | sanitize: true, |
68 | smartLists: true, |
69 | smartypants: false, |
70 | emoji: renderEmoji, |
71 | renderer: new MdRenderer(defaultOpts) |
72 | } |
73 | |
74 | var getMsg = memo({cache: lru(100)}, getMsgWithValue, sbot) |
75 | var getAbout = memo({cache: lru(100)}, require('./lib/about'), sbot) |
76 | var serveAcmeChallenge = require('ssb-acme-validator')(sbot) |
77 | |
78 | http.createServer(serve).listen(port, host, function () { |
79 | if (/:/.test(host)) host = '[' + host + ']' |
80 | console.log('[viewer] Listening on http://' + host + ':' + port) |
81 | }) |
82 | |
83 | function serve(req, res) { |
84 | if (req.method !== 'GET' && req.method !== 'HEAD') { |
85 | return respond(res, 405, 'Method must be GET or HEAD') |
86 | } |
87 | |
88 | var m = urlIdRegex.exec(req.url) |
89 | |
90 | if (m[4] === '/robots.txt') return serveRobots(req, res, conf) |
91 | if (req.url.startsWith('/static/')) return serveStatic(req, res, m[4]) |
92 | if (req.url.startsWith('/emoji/')) return serveEmoji(req, res, m[4]) |
93 | if (req.url.startsWith('/user-feed/')) return serveUserFeed(req, res, m[4]) |
94 | else if (req.url.startsWith('/channel/')) return serveChannel(req, res, m[4]) |
95 | else if (req.url.startsWith('/.well-known/acme-challenge')) return serveAcmeChallenge(req, res) |
96 | else if (req.url.startsWith('/web/')) return serveWeb(req, res, m[4]) |
97 | |
98 | if (m[2] && m[2].length === 3) { |
99 | m[1] = decodeURIComponent(m[1]) |
100 | m[2] = m[1][0] |
101 | } |
102 | switch (m[2]) { |
103 | case '%': return serveId(req, res, m[1], m[3], m[5]) |
104 | case '@': return serveFeed(req, res, m[1], m[3], m[5]) |
105 | case '&': return serveBlob(req, res, sbot, m[1], m[5]) |
106 | } |
107 | |
108 | if (m[4] === '/') return serveHome(req, res, m[5]) |
109 | return respond(res, 404, 'Not found') |
110 | } |
111 | |
112 | function serveFeed(req, res, feedId, ext) { |
113 | console.log('serving feed: ' + feedId) |
114 | |
115 | var showAll = req.url.endsWith('?showAll') |
116 | |
117 | getAbout(feedId, function (err, about) { |
118 | if (err) return respond(res, 500, err.stack || err) |
119 | |
120 | function render() { |
121 | switch (ext) { |
122 | case 'rss': |
123 | return pull( |
124 | // formatMsgs(feedId, ext, defaultOpts) |
125 | renderRssItem(defaultOpts), wrapRss(about.name, defaultOpts) |
126 | ) |
127 | default: |
128 | var publicWebHosting = about.publicWebHosting == null |
129 | ? !defaultOpts.requireOptIn : about.publicWebHosting |
130 | var name = publicWebHosting ? about.name : feedId.substr(0, 10) + '…' |
131 | return pull( |
132 | renderAbout(defaultOpts, about, |
133 | renderShowAll(showAll, req.url)), wrapPage(name) |
134 | ) |
135 | } |
136 | } |
137 | |
138 | pull( |
139 | sbot.createUserStream({ id: feedId, reverse: true, limit: showAll ? -1 : (ext == 'rss' ? 25 : 10) }), |
140 | pull.filter(function (data) { |
141 | return 'object' === typeof data.value.content |
142 | }), |
143 | pull.collect(function (err, logs) { |
144 | if (err) return respond(res, 500, err.stack || err) |
145 | res.writeHead(200, { |
146 | 'Content-Type': ctype(ext) |
147 | }) |
148 | pull( |
149 | pull.values(logs), |
150 | paramap(addAuthorAbout, 8), |
151 | paramap(addBlog, 8), |
152 | paramap(addFollowAbout, 8), |
153 | paramap(addVoteMessage, 8), |
154 | paramap(addGitLinks, 8), |
155 | paramap(addGatheringAbout, 8), |
156 | render(), |
157 | toPull(res, function (err) { |
158 | if (err) console.error('[viewer]', err) |
159 | }) |
160 | ) |
161 | }) |
162 | ) |
163 | }) |
164 | } |
165 | |
166 | function serveWeb (req, res, url) { |
167 | var self = this |
168 | var id = decodeURIComponent(url.substr(1)) |
169 | |
170 | var components = url.split('/') |
171 | if (components[0] === '') components.shift() |
172 | if (components[0] === 'web') components.shift() |
173 | components[0] = decodeURIComponent(components[0]) |
174 | |
175 | webresolve(sbot, components, function (err, data) { |
176 | if (err) { |
177 | return respond(res, 404, 'ERROR: ' + err) |
178 | } |
179 | return pull( |
180 | pull.once(data), |
181 | toPull(res, function (err) { |
182 | if (err) console.error('[viewer]', err) |
183 | }) |
184 | ) |
185 | }) |
186 | } |
187 | |
188 | function serveUserFeed(req, res, url) { |
189 | var feedId = url.substring(url.lastIndexOf('user-feed/')+10, 100) |
190 | console.log('serving user feed: ' + feedId) |
191 | |
192 | var following = [] |
193 | var channelSubscriptions = [] |
194 | |
195 | getAbout(feedId, function (err, about) { |
196 | pull( |
197 | sbot.createUserStream({ id: feedId }), |
198 | pull.filter((msg) => { |
199 | return !msg.value || |
200 | msg.value.content.type == 'contact' || |
201 | (msg.value.content.type == 'channel' && |
202 | typeof msg.value.content.subscribed != 'undefined') |
203 | }), |
204 | pull.collect(function (err, msgs) { |
205 | msgs.forEach((msg) => { |
206 | if (msg.value.content.type == 'contact') |
207 | { |
208 | if (msg.value.content.following) |
209 | following[msg.value.content.contact] = 1 |
210 | else |
211 | delete following[msg.value.content.contact] |
212 | } |
213 | else // channel subscription |
214 | { |
215 | if (msg.value.content.subscribed) |
216 | channelSubscriptions[msg.value.content.channel] = 1 |
217 | else |
218 | delete channelSubscriptions[msg.value.content.channel] |
219 | } |
220 | }) |
221 | |
222 | serveFeeds(req, res, following, channelSubscriptions, feedId, |
223 | 'user feed ' + (about ? about.name : '')) |
224 | }) |
225 | ) |
226 | }) |
227 | } |
228 | |
229 | function serveFeeds(req, res, following, channelSubscriptions, feedId, name) { |
230 | var feedOpts = Object.assign({}, defaultOpts, { |
231 | renderPrivate: false, |
232 | renderSubscribe: false, |
233 | renderVote: false, |
234 | renderTalenet: false, |
235 | renderChess: false, |
236 | renderFollow: false, |
237 | renderPub: false, |
238 | renderAbout: false |
239 | }) |
240 | |
241 | pull( |
242 | sbot.createLogStream({ reverse: true, limit: 5000 }), |
243 | pull.filter((msg) => { |
244 | return !msg.value || |
245 | (msg.value.author in following || |
246 | msg.value.content.channel in channelSubscriptions) |
247 | }), |
248 | pull.take(150), |
249 | pull.collect(function (err, logs) { |
250 | if (err) return respond(res, 500, err.stack || err) |
251 | res.writeHead(200, { |
252 | 'Content-Type': ctype('html') |
253 | }) |
254 | pull( |
255 | pull.values(logs), |
256 | paramap(addAuthorAbout, 8), |
257 | paramap(addBlog, 8), |
258 | paramap(addFollowAbout, 8), |
259 | paramap(addVoteMessage, 8), |
260 | paramap(addGitLinks, 8), |
261 | paramap(addGatheringAbout, 8), |
262 | pull(renderThread(feedOpts), wrapPage(name)), |
263 | toPull(res, function (err) { |
264 | if (err) console.error('[viewer]', err) |
265 | }) |
266 | ) |
267 | }) |
268 | ) |
269 | } |
270 | |
271 | function serveChannel(req, res, url) { |
272 | var channelId = url.substring(url.lastIndexOf('channel/')+8, 100) |
273 | console.log('serving channel: ' + channelId) |
274 | |
275 | var showAll = req.url.endsWith('?showAll') |
276 | |
277 | pull( |
278 | sbot.query.read({ limit: showAll ? 300 : 10, reverse: true, query: [{$filter: { value: { content: { channel: channelId }}}}]}), |
279 | pull.collect(function (err, logs) { |
280 | if (err) return respond(res, 500, err.stack || err) |
281 | res.writeHead(200, { |
282 | 'Content-Type': ctype('html') |
283 | }) |
284 | pull( |
285 | pull.values(logs), |
286 | paramap(addAuthorAbout, 8), |
287 | paramap(addBlog, 8), |
288 | paramap(addVoteMessage, 8), |
289 | paramap(addGatheringAbout, 8), |
290 | pull(renderThread(defaultOpts, '', renderShowAll(showAll, req.url)), |
291 | wrapPage('#' + channelId)), |
292 | toPull(res, function (err) { |
293 | if (err) console.error('[viewer]', err) |
294 | }) |
295 | ) |
296 | }) |
297 | ) |
298 | } |
299 | |
300 | function serveId(req, res, id, ext, query) { |
301 | var q = query ? qs.parse(query) : {} |
302 | var includeRoot = !('noroot' in q) |
303 | var base = q.base || conf.base |
304 | var baseToken |
305 | if (!base) { |
306 | if (ext === 'js') base = baseToken = '__BASE_' + Math.random() + '_' |
307 | else base = '/' |
308 | } |
309 | var opts = { |
310 | base: base, |
311 | base_token: baseToken, |
312 | msg_base: q.msg_base || conf.msg_base || base, |
313 | feed_base: q.feed_base || conf.feed_base || base, |
314 | blob_base: q.blob_base || conf.blob_base || base, |
315 | img_base: q.img_base || conf.img_base || base, |
316 | emoji_base: q.emoji_base || conf.emoji_base || (base + 'emoji/'), |
317 | requireOptIn: defaultOpts.requireOptIn, |
318 | } |
319 | opts.marked = { |
320 | gfm: true, |
321 | mentions: true, |
322 | tables: true, |
323 | breaks: true, |
324 | pedantic: false, |
325 | sanitize: true, |
326 | smartLists: true, |
327 | smartypants: false, |
328 | emoji: renderEmoji, |
329 | renderer: new MdRenderer(opts) |
330 | } |
331 | |
332 | var format = formatMsgs(id, ext, opts) |
333 | if (format === null) return respond(res, 415, 'Invalid format') |
334 | |
335 | function render (links) { |
336 | var etag = hash(sort.heads(links).concat(appHash, ext, qs)) |
337 | if (req.headers['if-none-match'] === etag) return respond(res, 304) |
338 | res.writeHead(200, { |
339 | 'Content-Type': ctype(ext), |
340 | 'etag': etag |
341 | }) |
342 | pull( |
343 | pull.values(sort(links)), |
344 | paramap(addAuthorAbout, 8), |
345 | paramap(addVoteMessage, 8), |
346 | paramap(addBlog, 8), |
347 | paramap(addGatheringAbout, 8), |
348 | format, |
349 | toPull(res, function (err) { |
350 | if (err) console.error('[viewer]', err) |
351 | }) |
352 | ) |
353 | } |
354 | |
355 | getMsgWithValue(sbot, id, function (err, root) { |
356 | if (err) return respond(res, 500, err.stack || err) |
357 | if('string' === typeof root.value.content) |
358 | return render([root]) |
359 | |
360 | pull( |
361 | sbot.links({dest: id, values: true, rel: 'root' }), |
362 | pull.unique('key'), |
363 | pull.collect(function (err, links) { |
364 | if (err) return respond(res, 500, err.stack || err) |
365 | if(includeRoot) |
366 | links.unshift(root) |
367 | render(links) |
368 | }) |
369 | ) |
370 | }) |
371 | } |
372 | |
373 | function addFollowAbout(msg, cb) { |
374 | if (msg.value.content.contact) |
375 | getAbout(msg.value.content.contact, function (err, about) { |
376 | if (err) return cb(err) |
377 | msg.value.content.contactAbout = about |
378 | cb(null, msg) |
379 | }) |
380 | else |
381 | cb(null, msg) |
382 | } |
383 | |
384 | function addVoteMessage(msg, cb) { |
385 | if (msg.value.content.type == 'vote' && msg.value.content.vote && msg.value.content.vote.link[0] == '%') |
386 | getMsg(msg.value.content.vote.link, function (err, linkedMsg) { |
387 | var linkedC = linkedMsg && linkedMsg.value.content |
388 | if (linkedMsg) |
389 | msg.value.content.vote.linkedText = |
390 | (typeof linkedC.contentWarning === 'string' ? '[CW: ' + linkedC.contentWarning + '] ' : '') + |
391 | linkedC.text |
392 | cb(null, msg) |
393 | }) |
394 | else |
395 | cb(null, msg) |
396 | } |
397 | |
398 | function addBlog(msg, cb) { |
399 | if (msg.value && msg.value.content.type == 'blog') { |
400 | pull( |
401 | sbot.blobs.get(msg.value.content.blog), |
402 | pull.collect(function(err, blob) { |
403 | msg.value.content.blogContent = blob |
404 | cb(null, msg) |
405 | }) |
406 | ) |
407 | } else |
408 | cb(null, msg) |
409 | } |
410 | |
411 | function addAuthorAbout(msg, cb) { |
412 | getAbout(msg.value.author, function (err, about) { |
413 | if (err) return cb(err) |
414 | msg.author = about |
415 | cb(null, msg) |
416 | }) |
417 | } |
418 | |
419 | function addGatheringAbout(msg, cb) { |
420 | if (msg.value && msg.value.content.type === 'gathering') { |
421 | getAbout(msg.key, (err, about) => { |
422 | if (err) { cb(err) } |
423 | |
424 | msg.value.content.about = about |
425 | |
426 | pull( |
427 | sbot.backlinks.read({ |
428 | query: [{ $filter: { |
429 | dest: msg.key, |
430 | value: { content: { type: 'about' }}, |
431 | }}], |
432 | index: 'DTA' |
433 | }), |
434 | // Only grab messages about attendance |
435 | pull.filter(o => o.value.content.attendee !== undefined), |
436 | // Filter "can't attend"-messages |
437 | pull.filter(o => !o.value.content.attendee.remove), |
438 | pull.unique(o => o.value.content.attendee.link), |
439 | pull.collect((err, arr) => { |
440 | if (err) { cb(err) } |
441 | |
442 | msg.value.content.numberAttending = arr.length |
443 | |
444 | cb(null, msg) |
445 | }) |
446 | ) |
447 | }) |
448 | } else { |
449 | cb(null, msg) |
450 | } |
451 | } |
452 | |
453 | function addGitLinks(msg, cb) { |
454 | if (msg.value.content.type == 'git-update') |
455 | getMsg(msg.value.content.repo, function (err, gitRepo) { |
456 | if (gitRepo) |
457 | msg.value.content.repoName = gitRepo.value.content.name |
458 | cb(null, msg) |
459 | }) |
460 | else if (msg.value.content.type == 'issue') |
461 | getMsg(msg.value.content.project, function (err, gitRepo) { |
462 | if (gitRepo) |
463 | msg.value.content.repoName = gitRepo.value.content.name |
464 | cb(null, msg) |
465 | }) |
466 | else |
467 | cb(null, msg) |
468 | } |
469 | } |
470 | |
471 | function serveBlob(req, res, sbot, id, query) { |
472 | var q = query && qs.parse(query) |
473 | var unbox = q && typeof q.unbox === 'string' && q.unbox.replace(/\s/g, '+') |
474 | var etag = id + (unbox || '') |
475 | |
476 | if (req.headers['if-none-match'] === etag) return respond(res, 304) |
477 | sbot.blobs.has(id, function (err, has) { |
478 | if (err) { |
479 | if (/^invalid/.test(err.message)) return respond(res, 400, err.message) |
480 | else return respond(res, 500, err.message || err) |
481 | } |
482 | if (!has) return respond(res, 404, 'Not found') |
483 | |
484 | var unboxKey |
485 | if (unbox) { |
486 | try { unboxKey = new Buffer(unbox, 'base64') } |
487 | catch(e) { return respond(res, 400, err.message) } |
488 | if (unboxKey.length !== 32) return respond(res, 400, 'Bad blob key') |
489 | } |
490 | |
491 | res.writeHead(200, { |
492 | 'Cache-Control': 'public, max-age=315360000', |
493 | 'etag': etag |
494 | }) |
495 | |
496 | pull( |
497 | sbot.blobs.get(id), |
498 | unboxKey ? BoxStream.createUnboxStream(unboxKey, zeros) : null, |
499 | toPull(res, function (err) { |
500 | if (err) console.error('[viewer]', err) |
501 | }) |
502 | ) |
503 | }) |
504 | } |
505 | |
506 | function getMsgWithValue(sbot, id, cb) { |
507 | sbot.get(id, function (err, value) { |
508 | if (err) return cb(err) |
509 | cb(null, {key: id, value: value}) |
510 | }) |
511 | } |
512 | |
513 | function respond(res, status, message) { |
514 | res.writeHead(status) |
515 | res.end(message) |
516 | } |
517 | |
518 | function ctype(name) { |
519 | switch (name && /[^.\/]*$/.exec(name)[0] || 'html') { |
520 | case 'html': return 'text/html' |
521 | case 'js': return 'text/javascript' |
522 | case 'css': return 'text/css' |
523 | case 'json': return 'application/json' |
524 | case 'rss': return 'text/xml' |
525 | } |
526 | } |
527 | |
528 | function ifModified(req, lastMod) { |
529 | var ifModSince = req.headers['if-modified-since'] |
530 | if (!ifModSince) return false |
531 | var d = new Date(ifModSince) |
532 | return d && Math.floor(d/1000) >= Math.floor(lastMod/1000) |
533 | } |
534 | |
535 | function serveStatic(req, res, file) { |
536 | serveFile(req, res, path.join(__dirname, 'static', file)) |
537 | } |
538 | |
539 | function serveFile(req, res, file) { |
540 | fs.stat(file, function (err, stat) { |
541 | if (err && err.code === 'ENOENT') return respond(res, 404, 'Not found') |
542 | if (err) return respond(res, 500, err.stack || err) |
543 | if (!stat.isFile()) return respond(res, 403, 'May only load files') |
544 | if (ifModified(req, stat.mtime)) return respond(res, 304, 'Not modified') |
545 | res.writeHead(200, { |
546 | 'Content-Type': ctype(file), |
547 | 'Content-Length': stat.size, |
548 | 'Last-Modified': stat.mtime.toGMTString() |
549 | }) |
550 | fs.createReadStream(file).pipe(res) |
551 | }) |
552 | } |
553 | |
554 | function asChannelLink(id) { |
555 | var channel = refs.normalizeChannel(id) |
556 | if (channel) return '#' + channel |
557 | } |
558 | |
559 | function asLink(id) { |
560 | if (!id || typeof id !== 'string') return null |
561 | id = id.trim() |
562 | if (id[0] === '#') return asChannelLink(id) |
563 | if (refs.isLink(id)) return id |
564 | try { |
565 | id = decodeURIComponent(id) |
566 | } catch(e) { |
567 | return null |
568 | } |
569 | if (id[0] === '#') return asChannelLink(id) |
570 | if (refs.isLink(id)) return id |
571 | } |
572 | |
573 | function serveHome(req, res, query, conf) { |
574 | var q = query ? qs.parse(query) : {} |
575 | var id = asLink(q.id) |
576 | if (id) { |
577 | res.writeHead(303, { |
578 | Location: '/' + ( |
579 | id[0] === '#' ? 'channel/' + id.substr(1) : |
580 | refs.isMsgId(id) ? encodeURIComponent(id) : id) |
581 | }) |
582 | return res.end() |
583 | } |
584 | res.writeHead(200, { |
585 | 'Content-Type': 'text/html' |
586 | }) |
587 | pull( |
588 | pull.once(h('form', {method: 'get', action: ''}, |
589 | h('input', {name: 'id', placeholder: 'id', size: 60, value: q.id || ''}), ' ', |
590 | h('input', {type: 'submit', value: 'Go'}) |
591 | ).outerHTML), |
592 | wrapPage('ssb-viewer'), |
593 | toPull(res, function (err) { |
594 | if (err) console.error('[viewer]', err) |
595 | }) |
596 | ) |
597 | } |
598 | |
599 | function serveRobots(req, res, conf) { |
600 | var disallow = conf.disallowRobots == null ? true : conf.disallowRobots |
601 | res.end('User-agent: *\n' |
602 | + (disallow ? 'Disallow: /\n' : '')) |
603 | } |
604 | |
605 | function prepend(fn, arg) { |
606 | return function (read) { |
607 | return function (abort, cb) { |
608 | if (fn && !abort) { |
609 | var _fn = fn |
610 | fn = null |
611 | return _fn(arg, function (err, value) { |
612 | if (err) return read(err, function (err) { |
613 | cb(err || true) |
614 | }) |
615 | cb(null, value) |
616 | }) |
617 | } |
618 | read(abort, cb) |
619 | } |
620 | } |
621 | } |
622 |
Built with git-ssb-web