Files: 5544d14b7f0ac44755ee8975c5e544c94aab285f / index.js
17471 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 || '#', |
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.collect(function (err, logs) { |
205 | if (err) return respond(res, 500, err.stack || err) |
206 | res.writeHead(200, { |
207 | 'Content-Type': ctype("html") |
208 | }) |
209 | pull( |
210 | pull.values(logs), |
211 | paramap(addAuthorAbout, 8), |
212 | paramap(addFollowAbout, 8), |
213 | paramap(addVoteMessage, 8), |
214 | pull(renderThread(opts), wrapPage(feedId)), |
215 | toPull(res, function (err) { |
216 | if (err) console.error('[viewer]', err) |
217 | }) |
218 | ) |
219 | }) |
220 | ) |
221 | } |
222 | |
223 | function serveChannel(req, res, url) { |
224 | var channelId = url.substring(url.lastIndexOf('channel/')+8, 100) |
225 | console.log("serving channel: " + channelId) |
226 | |
227 | var opts = defaultOpts |
228 | |
229 | opts.marked = { |
230 | gfm: true, |
231 | mentions: true, |
232 | tables: true, |
233 | breaks: true, |
234 | pedantic: false, |
235 | sanitize: true, |
236 | smartLists: true, |
237 | smartypants: false, |
238 | emoji: renderEmoji, |
239 | renderer: new MdRenderer(opts) |
240 | } |
241 | |
242 | pull( |
243 | sbot.query.read({ limit: 500, reverse: true, query: [{$filter: { value: { content: { channel: channelId }}}}]}), |
244 | pull.collect(function (err, logs) { |
245 | if (err) return respond(res, 500, err.stack || err) |
246 | res.writeHead(200, { |
247 | 'Content-Type': ctype("html") |
248 | }) |
249 | pull( |
250 | pull.values(logs), |
251 | paramap(addAuthorAbout, 8), |
252 | paramap(addVoteMessage, 8), |
253 | pull(renderThread(opts), wrapPage(channelId)), |
254 | toPull(res, function (err) { |
255 | if (err) console.error('[viewer]', err) |
256 | }) |
257 | ) |
258 | }) |
259 | ) |
260 | } |
261 | |
262 | function addFollowAbout(msg, cb) { |
263 | if (msg.value.content.contact) |
264 | getAbout(msg.value.content.contact, function (err, about) { |
265 | if (err) return cb(err) |
266 | msg.value.content.contactAbout = about |
267 | cb(null, msg) |
268 | }) |
269 | else |
270 | cb(null, msg) |
271 | } |
272 | |
273 | function addVoteMessage(msg, cb) { |
274 | if (msg.value.content.type == 'vote') |
275 | getMsg(msg.value.content.vote.link, function (err, linkedMsg) { |
276 | if (err) return cb(err) |
277 | msg.value.content.vote.linkedText = linkedMsg.value.content.text |
278 | cb(null, msg) |
279 | }) |
280 | else |
281 | cb(null, msg) |
282 | } |
283 | |
284 | function serveId(req, res, id, ext, query) { |
285 | var q = query ? qs.parse(query) : {} |
286 | var includeRoot = !('noroot' in q) |
287 | var base = q.base || conf.base |
288 | var baseToken |
289 | if (!base) { |
290 | if (ext === 'js') base = baseToken = '__BASE_' + Math.random() + '_' |
291 | else base = '/' |
292 | } |
293 | var opts = { |
294 | base: base, |
295 | base_token: baseToken, |
296 | msg_base: q.msg_base || conf.msg_base || base, |
297 | feed_base: q.feed_base || conf.feed_base || '#', |
298 | blob_base: q.blob_base || conf.blob_base || base, |
299 | img_base: q.img_base || conf.img_base || base, |
300 | emoji_base: q.emoji_base || conf.emoji_base || (base + 'emoji/'), |
301 | } |
302 | opts.marked = { |
303 | gfm: true, |
304 | mentions: true, |
305 | tables: true, |
306 | breaks: true, |
307 | pedantic: false, |
308 | sanitize: true, |
309 | smartLists: true, |
310 | smartypants: false, |
311 | emoji: renderEmoji, |
312 | renderer: new MdRenderer(opts) |
313 | } |
314 | |
315 | var format = formatMsgs(id, ext, opts) |
316 | if (format === null) return respond(res, 415, 'Invalid format') |
317 | |
318 | pull( |
319 | sbot.links({dest: id, values: true, rel: 'root'}), |
320 | includeRoot && prepend(getMsg, id), |
321 | pull.unique('key'), |
322 | pull.collect(function (err, links) { |
323 | if (err) return respond(res, 500, err.stack || err) |
324 | var etag = hash(sort.heads(links).concat(appHash, ext, qs)) |
325 | if (req.headers['if-none-match'] === etag) return respond(res, 304) |
326 | res.writeHead(200, { |
327 | 'Content-Type': ctype(ext), |
328 | 'etag': etag |
329 | }) |
330 | pull( |
331 | pull.values(sort(links)), |
332 | paramap(addAuthorAbout, 8), |
333 | format, |
334 | toPull(res, function (err) { |
335 | if (err) console.error('[viewer]', err) |
336 | }) |
337 | ) |
338 | }) |
339 | ) |
340 | } |
341 | |
342 | function addAuthorAbout(msg, cb) { |
343 | getAbout(msg.value.author, function (err, about) { |
344 | if (err) return cb(err) |
345 | msg.author = about |
346 | cb(null, msg) |
347 | }) |
348 | } |
349 | } |
350 | |
351 | function serveBlob(req, res, sbot, id) { |
352 | if (req.headers['if-none-match'] === id) return respond(res, 304) |
353 | sbot.blobs.has(id, function (err, has) { |
354 | if (err) { |
355 | if (/^invalid/.test(err.message)) return respond(res, 400, err.message) |
356 | else return respond(res, 500, err.message || err) |
357 | } |
358 | if (!has) return respond(res, 404, 'Not found') |
359 | res.writeHead(200, { |
360 | 'Cache-Control': 'public, max-age=315360000', |
361 | 'etag': id |
362 | }) |
363 | pull( |
364 | sbot.blobs.get(id), |
365 | toPull(res, function (err) { |
366 | if (err) console.error('[viewer]', err) |
367 | }) |
368 | ) |
369 | }) |
370 | } |
371 | |
372 | function getMsgWithValue(sbot, id, cb) { |
373 | sbot.get(id, function (err, value) { |
374 | if (err) return cb(err) |
375 | cb(null, {key: id, value: value}) |
376 | }) |
377 | } |
378 | |
379 | function escape(str) { |
380 | return String(str) |
381 | .replace(/&/g, '&') |
382 | .replace(/</g, '<') |
383 | .replace(/>/g, '>') |
384 | .replace(/"/g, '"') |
385 | } |
386 | |
387 | function respond(res, status, message) { |
388 | res.writeHead(status) |
389 | res.end(message) |
390 | } |
391 | |
392 | function ctype(name) { |
393 | switch (name && /[^.\/]*$/.exec(name)[0] || 'html') { |
394 | case 'html': return 'text/html' |
395 | case 'js': return 'text/javascript' |
396 | case 'css': return 'text/css' |
397 | case 'json': return 'application/json' |
398 | } |
399 | } |
400 | |
401 | function servePath(req, res, url) { |
402 | switch (url) { |
403 | case '/robots.txt': return res.end('User-agent: *') |
404 | } |
405 | var m = /^(\/?[^\/]*)(\/.*)?$/.exec(url) |
406 | switch (m[1]) { |
407 | case '/static': return serveStatic(req, res, m[2]) |
408 | case '/emoji': return serveEmoji(req, res, m[2]) |
409 | } |
410 | return respond(res, 404, 'Not found') |
411 | } |
412 | |
413 | function ifModified(req, lastMod) { |
414 | var ifModSince = req.headers['if-modified-since'] |
415 | if (!ifModSince) return false |
416 | var d = new Date(ifModSince) |
417 | return d && Math.floor(d/1000) >= Math.floor(lastMod/1000) |
418 | } |
419 | |
420 | function serveStatic(req, res, file) { |
421 | serveFile(req, res, path.join(__dirname, 'static', file)) |
422 | } |
423 | |
424 | function serveFile(req, res, file) { |
425 | fs.stat(file, function (err, stat) { |
426 | if (err && err.code === 'ENOENT') return respond(res, 404, 'Not found') |
427 | if (err) return respond(res, 500, err.stack || err) |
428 | if (!stat.isFile()) return respond(res, 403, 'May only load files') |
429 | if (ifModified(req, stat.mtime)) return respond(res, 304, 'Not modified') |
430 | res.writeHead(200, { |
431 | 'Content-Type': ctype(file), |
432 | 'Content-Length': stat.size, |
433 | 'Last-Modified': stat.mtime.toGMTString() |
434 | }) |
435 | fs.createReadStream(file).pipe(res) |
436 | }) |
437 | } |
438 | |
439 | function prepend(fn, arg) { |
440 | return function (read) { |
441 | return function (abort, cb) { |
442 | if (fn && !abort) { |
443 | var _fn = fn |
444 | fn = null |
445 | return _fn(arg, function (err, value) { |
446 | if (err) return read(err, function (err) { |
447 | cb(err || true) |
448 | }) |
449 | cb(null, value) |
450 | }) |
451 | } |
452 | read(abort, cb) |
453 | } |
454 | } |
455 | } |
456 | |
457 | function formatMsgs(id, ext, opts) { |
458 | switch (ext || 'html') { |
459 | case 'html': return pull(renderThread(opts), wrapPage(id)) |
460 | case 'js': return pull(renderThread(opts), wrapJSEmbed(opts)) |
461 | case 'json': return wrapJSON() |
462 | default: return null |
463 | } |
464 | } |
465 | |
466 | function wrap(before, after) { |
467 | return function (read) { |
468 | return cat([pull.once(before), read, pull.once(after)]) |
469 | } |
470 | } |
471 | |
472 | function renderThread(opts) { |
473 | return pull( |
474 | pull.map(renderMsg.bind(this, opts)), |
475 | wrap('<div class="ssb-thread">', '</div>') |
476 | ) |
477 | } |
478 | |
479 | function wrapPage(id) { |
480 | return wrap('<!doctype html><html><head>' |
481 | + '<meta charset=utf-8>' |
482 | + '<title>' + id + '</title>' |
483 | + '<meta name=viewport content="width=device-width,initial-scale=1">' |
484 | + '<link rel=stylesheet href="/static/base.css">' |
485 | + '<link rel=stylesheet href="/static/nicer.css">' |
486 | + '</head><body>', |
487 | '</body></html>' |
488 | ) |
489 | } |
490 | |
491 | function wrapJSON() { |
492 | var first = true |
493 | return pull( |
494 | pull.map(JSON.stringify), |
495 | join(','), |
496 | wrap('[', ']') |
497 | ) |
498 | } |
499 | |
500 | function wrapJSEmbed(opts) { |
501 | return pull( |
502 | wrap('<link rel=stylesheet href="' + opts.base + 'static/base.css">', ''), |
503 | pull.map(docWrite), |
504 | opts.base_token && rewriteBase(new RegExp(opts.base_token, 'g')) |
505 | ) |
506 | } |
507 | |
508 | |
509 | function rewriteBase(token) { |
510 | // detect the origin of the script and rewrite the js/html to use it |
511 | return pull( |
512 | replace(token, '" + SSB_VIEWER_ORIGIN + "/'), |
513 | wrap('var SSB_VIEWER_ORIGIN = (function () {' |
514 | + 'var scripts = document.getElementsByTagName("script")\n' |
515 | + 'var script = scripts[scripts.length-1]\n' |
516 | + 'if (!script) return location.origin\n' |
517 | + 'return script.src.replace(/\\/%.*$/, "")\n' |
518 | + '}())\n', '') |
519 | ) |
520 | } |
521 | |
522 | function join(delim) { |
523 | var first = true |
524 | return pull.map(function (val) { |
525 | if (!first) return delim + String(val) |
526 | first = false |
527 | return val |
528 | }) |
529 | } |
530 | |
531 | function replace(re, rep) { |
532 | return pull.map(function (val) { |
533 | return String(val).replace(re, rep) |
534 | }) |
535 | } |
536 | |
537 | function docWrite(str) { |
538 | return 'document.write(' + JSON.stringify(str) + ')\n' |
539 | } |
540 | |
541 | function hash(arr) { |
542 | return arr.reduce(function (hash, item) { |
543 | return hash.update(String(item)) |
544 | }, crypto.createHash('sha256')).digest('base64') |
545 | } |
546 | |
547 | function renderMsg(opts, msg) { |
548 | var c = msg.value.content || {} |
549 | var name = encodeURIComponent(msg.key) |
550 | return '<div class="ssb-message" id="' + name + '">' |
551 | + '<img class="ssb-avatar-image" alt=""' |
552 | + ' src="' + opts.img_base + escape(msg.author.image) + '"' |
553 | + ' height="32" width="32">' |
554 | + '<a class="ssb-avatar-name"' |
555 | + ' href="/' + escape(msg.value.author) + '"' |
556 | + '>' + msg.author.name + '</a>' |
557 | + msgTimestamp(msg, name) |
558 | + render(opts, c) |
559 | + '</div>' |
560 | } |
561 | |
562 | function msgTimestamp(msg, name) { |
563 | var date = new Date(msg.value.timestamp) |
564 | return '<time class="ssb-timestamp" datetime="' + date.toISOString() + '">' |
565 | + '<a href="#' + name + '">' |
566 | + formatDate(date) + '</a></time>' |
567 | } |
568 | |
569 | function formatDate(date) { |
570 | // return date.toISOString().replace('T', ' ') |
571 | return htime(date) |
572 | } |
573 | |
574 | function render(opts, c) |
575 | { |
576 | if (c.type === 'post') { |
577 | var channel = c.channel ? ' in #' + c.channel : '' |
578 | return channel + renderPost(opts, c) |
579 | } else if (c.type == 'vote' && c.vote.expression == 'Dig') { |
580 | var channel = c.channel ? ' in #' + c.channel : '' |
581 | var linkedText = 'this' |
582 | if (typeof c.vote.linkedText != 'undefined') |
583 | linkedText = c.vote.linkedText.substring(0, 100) |
584 | return ' dug ' + '<a href="/' + c.vote.link + '">' + linkedText + '</a>' + channel |
585 | } |
586 | else if (c.type == 'vote') { |
587 | var linkedText = 'this' |
588 | if (typeof c.vote.linkedText != 'undefined') |
589 | linkedText = c.vote.linkedText.substring(0, 100) |
590 | return ' voted <a href="/' + c.vote.link + '">' + linkedText + '</a>' |
591 | } |
592 | else if (c.type == 'contact' && c.following) { |
593 | var name = c.contact |
594 | if (typeof c.contactAbout != 'undefined') |
595 | name = c.contactAbout.name |
596 | return ' followed <a href="/' + c.contact + '">' + name + "</a>" |
597 | } |
598 | else if (typeof c == 'string') |
599 | return ' wrote something private ' |
600 | else if (c.type == 'about') |
601 | return ' changed something in about' |
602 | else if (c.type == 'issue') |
603 | return ' created an issue' |
604 | else if (c.type == 'git-update') |
605 | return ' did a git update' |
606 | else if (c.type == 'ssb-dns') |
607 | return ' updated dns' |
608 | else if (c.type == 'pub') |
609 | return ' connected to a pub' |
610 | else if (c.type == 'channel' && c.subscribed) |
611 | return ' subscribed to channel <a href="/channel/' + c.channel + '">#' + c.channel + "</a>" |
612 | else |
613 | return renderDefault(c) |
614 | } |
615 | |
616 | function renderPost(opts, c) { |
617 | return '<div class="ssb-post">' + marked(c.text, opts.marked) + '</div>' |
618 | } |
619 | |
620 | function renderDefault(c) { |
621 | return '<pre>' + JSON.stringify(c, 0, 2) + '</pre>' |
622 | } |
623 |
Built with git-ssb-web