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