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