git ssb

9+

cel / ssb-viewer



Tree: 7b1296a17c686246a78705ff9f4d90b54c294c86

Files: 7b1296a17c686246a78705ff9f4d90b54c294c86 / index.js

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

Built with git-ssb-web