git ssb

9+

cel / ssb-viewer



Tree: b422fc1e8e938b340e5961d30a2d16edb54dd647

Files: b422fc1e8e938b340e5961d30a2d16edb54dd647 / index.js

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

Built with git-ssb-web