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