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