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