git ssb

9+

cel / ssb-viewer



Tree: 2ee923fecc38c7bee0a0f0520fae62c565d18e63

Files: 2ee923fecc38c7bee0a0f0520fae62c565d18e63 / index.js

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

Built with git-ssb-web