git ssb

0+

Daan Patchwork / ssb-viewer



forked from cel / ssb-viewer

Tree: ad80496c9aaec127be8cd80533c253901b618812

Files: ad80496c9aaec127be8cd80533c253901b618812 / index.js

17838 bytesRaw
1var fs = require('fs')
2var http = require('http')
3var qs = require('querystring')
4var path = require('path')
5var crypto = require('crypto')
6var pull = require('pull-stream')
7var paramap = require('pull-paramap')
8var sort = require('ssb-sort')
9var toPull = require('stream-to-pull-stream')
10var memo = require('asyncmemo')
11var lru = require('lrucache')
12var webresolve = require('ssb-web-resolver')
13var serveEmoji = require('emoji-server')()
14var refs = require('ssb-ref')
15var BoxStream = require('pull-box-stream')
16var h = require('hyperscript')
17var {
18 MdRenderer,
19 renderEmoji,
20 formatMsgs,
21 wrapPage,
22 renderThread,
23 renderAbout,
24 renderShowAll,
25 renderRssItem,
26 wrapRss,
27} = require('./render');
28
29var appHash = hash([fs.readFileSync(__filename)])
30
31var urlIdRegex = /^(?:\/(([%&@]|%25|%26|%40)(?:[A-Za-z0-9\/+]|%2[Ff]|%2[Bb]){43}(?:=|%3[Dd])\.(?:sha256|ed25519))(?:\.([^?]*))?|(\/.*?))(?:\?(.*))?$/
32
33var zeros = new Buffer(24); zeros.fill(0)
34
35function hash(arr) {
36 return arr.reduce(function (hash, item) {
37 return hash.update(String(item))
38 }, crypto.createHash('sha256')).digest('base64')
39}
40
41exports.name = 'viewer'
42exports.manifest = {}
43exports.version = require('./package').version
44
45exports.init = function (sbot, config) {
46 var conf = config.viewer || {}
47 var port = conf.port || 8807
48 var host = conf.host || config.host || '::'
49
50 var base = conf.base || '/'
51 var defaultOpts = {
52 base: base,
53 msg_base: conf.msg_base || base,
54 feed_base: conf.feed_base || base,
55 blob_base: conf.blob_base || base,
56 img_base: conf.img_base || base,
57 emoji_base: conf.emoji_base || (base + 'emoji/'),
58 requireOptIn: conf.require_opt_in == null ? true : conf.require_opt_in,
59 }
60
61 defaultOpts.marked = {
62 gfm: true,
63 mentions: true,
64 tables: true,
65 breaks: true,
66 pedantic: false,
67 sanitize: true,
68 smartLists: true,
69 smartypants: false,
70 emoji: renderEmoji,
71 renderer: new MdRenderer(defaultOpts)
72 }
73
74 var getMsg = memo({cache: lru(100)}, getMsgWithValue, sbot)
75 var getAbout = memo({cache: lru(100)}, require('./lib/about'), sbot)
76 var serveAcmeChallenge = require('ssb-acme-validator')(sbot)
77
78 http.createServer(serve).listen(port, host, function () {
79 if (/:/.test(host)) host = '[' + host + ']'
80 console.log('[viewer] Listening on http://' + host + ':' + port)
81 })
82
83 function serve(req, res) {
84 if (req.method !== 'GET' && req.method !== 'HEAD') {
85 return respond(res, 405, 'Method must be GET or HEAD')
86 }
87
88 var m = urlIdRegex.exec(req.url)
89
90 if (m[4] === '/robots.txt') return serveRobots(req, res, conf)
91 if (req.url.startsWith('/static/')) return serveStatic(req, res, m[4])
92 if (req.url.startsWith('/emoji/')) return serveEmoji(req, res, m[4])
93 if (req.url.startsWith('/user-feed/')) return serveUserFeed(req, res, m[4])
94 else if (req.url.startsWith('/channel/')) return serveChannel(req, res, m[4])
95 else if (req.url.startsWith('/.well-known/acme-challenge')) return serveAcmeChallenge(req, res)
96 else if (req.url.startsWith('/web/')) return serveWeb(req, res, m[4])
97
98 if (m[2] && m[2].length === 3) {
99 m[1] = decodeURIComponent(m[1])
100 m[2] = m[1][0]
101 }
102 switch (m[2]) {
103 case '%': return serveId(req, res, m[1], m[3], m[5])
104 case '@': return serveFeed(req, res, m[1], m[3], m[5])
105 case '&': return serveBlob(req, res, sbot, m[1], m[5])
106 }
107
108 if (m[4] === '/') return serveHome(req, res, m[5])
109 return respond(res, 404, 'Not found')
110 }
111
112 function serveFeed(req, res, feedId, ext) {
113 console.log("serving feed: " + feedId)
114
115 var showAll = req.url.endsWith("?showAll");
116
117 getAbout(feedId, function (err, about) {
118 if (err) return respond(res, 500, err.stack || err)
119
120 function render() {
121 switch (ext) {
122 case 'rss':
123 return pull(
124 // formatMsgs(feedId, ext, defaultOpts)
125 renderRssItem(defaultOpts), wrapRss(about.name, defaultOpts)
126 );
127 default:
128 var publicWebHosting = about.publicWebHosting == null
129 ? !defaultOpts.requireOptIn : about.publicWebHosting
130 var name = publicWebHosting ? about.name : feedId.substr(0, 10) + '…'
131 return pull(
132 renderAbout(defaultOpts, about,
133 renderShowAll(showAll, req.url)), wrapPage(name)
134 );
135 }
136 }
137
138 pull(
139 sbot.createUserStream({ id: feedId, reverse: true, limit: showAll ? -1 : (ext == 'rss' ? 25 : 10) }),
140 pull.filter(function (data) {
141 return 'object' === typeof data.value.content
142 }),
143 pull.collect(function (err, logs) {
144 if (err) return respond(res, 500, err.stack || err)
145 res.writeHead(200, {
146 'Content-Type': ctype(ext)
147 })
148 pull(
149 pull.values(logs),
150 paramap(addAuthorAbout, 8),
151 paramap(addBlog, 8),
152 paramap(addFollowAbout, 8),
153 paramap(addVoteMessage, 8),
154 paramap(addGitLinks, 8),
155 paramap(addGatheringAbout, 8),
156 render(),
157 toPull(res, function (err) {
158 if (err) console.error('[viewer]', err)
159 })
160 )
161 })
162 )
163 })
164 }
165
166 function serveWeb (req, res, url) {
167 var self = this
168 var id = decodeURIComponent(url.substr(1))
169
170 var components = url.split('/')
171 if (components[0] === '') components.shift()
172 if (components[0] === 'web') components.shift()
173 components[0] = decodeURIComponent(components[0])
174
175 webresolve(sbot, components, function (err, data) {
176 if (err) {
177 return respond(res, 404, 'ERROR: ' + err)
178 }
179 return pull(
180 pull.once(data),
181 toPull(res, function (err) {
182 if (err) console.error('[viewer]', err)
183 })
184 )
185 })
186 }
187
188 function serveUserFeed(req, res, url) {
189 var feedId = url.substring(url.lastIndexOf('user-feed/')+10, 100)
190 console.log("serving user feed: " + feedId)
191
192 var following = []
193 var channelSubscriptions = []
194
195 getAbout(feedId, function (err, about) {
196 pull(
197 sbot.createUserStream({ id: feedId }),
198 pull.filter((msg) => {
199 return !msg.value ||
200 msg.value.content.type == 'contact' ||
201 (msg.value.content.type == 'channel' &&
202 typeof msg.value.content.subscribed != 'undefined')
203 }),
204 pull.collect(function (err, msgs) {
205 msgs.forEach((msg) => {
206 if (msg.value.content.type == 'contact')
207 {
208 if (msg.value.content.following)
209 following[msg.value.content.contact] = 1
210 else
211 delete following[msg.value.content.contact]
212 }
213 else // channel subscription
214 {
215 if (msg.value.content.subscribed)
216 channelSubscriptions[msg.value.content.channel] = 1
217 else
218 delete channelSubscriptions[msg.value.content.channel]
219 }
220 })
221
222 serveFeeds(req, res, following, channelSubscriptions, feedId,
223 'user feed ' + (about ? about.name : ""))
224 })
225 )
226 })
227 }
228
229 function serveFeeds(req, res, following, channelSubscriptions, feedId, name) {
230 var feedOpts = Object.assign({}, defaultOpts, {
231 renderPrivate: false,
232 renderSubscribe: false,
233 renderVote: false,
234 renderTalenet: false,
235 renderChess: false,
236 renderFollow: false,
237 renderPub: false,
238 renderAbout: false
239 })
240
241 pull(
242 sbot.createLogStream({ reverse: true, limit: 5000 }),
243 pull.filter((msg) => {
244 return !msg.value ||
245 (msg.value.author in following ||
246 msg.value.content.channel in channelSubscriptions)
247 }),
248 pull.take(150),
249 pull.collect(function (err, logs) {
250 if (err) return respond(res, 500, err.stack || err)
251 res.writeHead(200, {
252 'Content-Type': ctype("html")
253 })
254 pull(
255 pull.values(logs),
256 paramap(addAuthorAbout, 8),
257 paramap(addBlog, 8),
258 paramap(addFollowAbout, 8),
259 paramap(addVoteMessage, 8),
260 paramap(addGitLinks, 8),
261 paramap(addGatheringAbout, 8),
262 pull(renderThread(feedOpts), wrapPage(name)),
263 toPull(res, function (err) {
264 if (err) console.error('[viewer]', err)
265 })
266 )
267 })
268 )
269 }
270
271 function serveChannel(req, res, url) {
272 var channelId = url.substring(url.lastIndexOf('channel/')+8, 100)
273 console.log("serving channel: " + channelId)
274
275 var showAll = req.url.endsWith("?showAll")
276
277 pull(
278 sbot.query.read({ limit: showAll ? 300 : 10, reverse: true, query: [{$filter: { value: { content: { channel: channelId }}}}]}),
279 pull.collect(function (err, logs) {
280 if (err) return respond(res, 500, err.stack || err)
281 res.writeHead(200, {
282 'Content-Type': ctype("html")
283 })
284 pull(
285 pull.values(logs),
286 paramap(addAuthorAbout, 8),
287 paramap(addBlog, 8),
288 paramap(addVoteMessage, 8),
289 paramap(addGatheringAbout, 8),
290 pull(renderThread(defaultOpts, '', renderShowAll(showAll, req.url)),
291 wrapPage('#' + channelId)),
292 toPull(res, function (err) {
293 if (err) console.error('[viewer]', err)
294 })
295 )
296 })
297 )
298 }
299
300 function serveId(req, res, id, ext, query) {
301 var q = query ? qs.parse(query) : {}
302 var includeRoot = !('noroot' in q)
303 var base = q.base || conf.base
304 var baseToken
305 if (!base) {
306 if (ext === 'js') base = baseToken = '__BASE_' + Math.random() + '_'
307 else base = '/'
308 }
309 var opts = {
310 base: base,
311 base_token: baseToken,
312 msg_base: q.msg_base || conf.msg_base || base,
313 feed_base: q.feed_base || conf.feed_base || base,
314 blob_base: q.blob_base || conf.blob_base || base,
315 img_base: q.img_base || conf.img_base || base,
316 emoji_base: q.emoji_base || conf.emoji_base || (base + 'emoji/'),
317 requireOptIn: defaultOpts.requireOptIn,
318 }
319 opts.marked = {
320 gfm: true,
321 mentions: true,
322 tables: true,
323 breaks: true,
324 pedantic: false,
325 sanitize: true,
326 smartLists: true,
327 smartypants: false,
328 emoji: renderEmoji,
329 renderer: new MdRenderer(opts)
330 }
331
332 var format = formatMsgs(id, ext, opts)
333 if (format === null) return respond(res, 415, 'Invalid format')
334
335 function render (links) {
336 var etag = hash(sort.heads(links).concat(appHash, ext, qs))
337 if (req.headers['if-none-match'] === etag) return respond(res, 304)
338 res.writeHead(200, {
339 'Content-Type': ctype(ext),
340 'etag': etag
341 })
342 pull(
343 pull.values(sort(links)),
344 paramap(addAuthorAbout, 8),
345 paramap(addBlog, 8),
346 paramap(addGatheringAbout, 8),
347 format,
348 toPull(res, function (err) {
349 if (err) console.error('[viewer]', err)
350 })
351 )
352 }
353
354 getMsgWithValue(sbot, id, function (err, root) {
355 if (err) return respond(res, 500, err.stack || err)
356 if('string' === typeof root.value.content)
357 return render([root])
358
359 pull(
360 sbot.links({dest: id, values: true, rel: 'root' }),
361 pull.unique('key'),
362 pull.collect(function (err, links) {
363 if (err) return respond(res, 500, err.stack || err)
364 if(includeRoot)
365 links.unshift(root)
366 render(links)
367 })
368 )
369 })
370 }
371
372 function addFollowAbout(msg, cb) {
373 if (msg.value.content.contact)
374 getAbout(msg.value.content.contact, function (err, about) {
375 if (err) return cb(err)
376 msg.value.content.contactAbout = about
377 cb(null, msg)
378 })
379 else
380 cb(null, msg)
381 }
382
383 function addVoteMessage(msg, cb) {
384 if (msg.value.content.type == 'vote' && msg.value.content.vote && msg.value.content.vote.link[0] == '%')
385 getMsg(msg.value.content.vote.link, function (err, linkedMsg) {
386 if (linkedMsg)
387 msg.value.content.vote.linkedText = linkedMsg.value.content.text
388 cb(null, msg)
389 })
390 else
391 cb(null, msg)
392 }
393
394 function addBlog(msg, cb) {
395 if (msg.value && msg.value.content.type == "blog") {
396 pull(
397 sbot.blobs.get(msg.value.content.blog),
398 pull.collect(function(err, blob) {
399 msg.value.content.blogContent = blob
400 cb(null, msg)
401 })
402 )
403 } else
404 cb(null, msg)
405 }
406
407 function addAuthorAbout(msg, cb) {
408 getAbout(msg.value.author, function (err, about) {
409 if (err) return cb(err)
410 msg.author = about
411 cb(null, msg)
412 })
413 }
414
415 function addGatheringAbout(msg, cb) {
416 if (msg.value && msg.value.content.type === 'gathering') {
417 getAbout(msg.key, (err, about) => {
418 if (err) { cb(err) }
419
420 msg.value.content.about = about
421
422 pull(
423 sbot.backlinks.read({
424 query: [{ $filter: {
425 dest: msg.key,
426 value: { content: { type: 'about' }},
427 }}],
428 index: 'DTA'
429 }),
430 // Only grab messages about attendance
431 pull.filter(o => o.value.content.attendee !== undefined),
432 // Filter "can't attend"-messages
433 pull.filter(o => !o.value.content.attendee.remove),
434 pull.unique(o => o.value.content.attendee.link),
435 pull.collect((err, arr) => {
436 if (err) { cb(err) }
437
438 msg.value.content.numberAttending = arr.length
439
440 cb(null, msg)
441 })
442 )
443 })
444 } else {
445 cb(null, msg)
446 }
447 }
448
449 function addGitLinks(msg, cb) {
450 if (msg.value.content.type == 'git-update')
451 getMsg(msg.value.content.repo, function (err, gitRepo) {
452 if (gitRepo)
453 msg.value.content.repoName = gitRepo.value.content.name
454 cb(null, msg)
455 })
456 else if (msg.value.content.type == 'issue')
457 getMsg(msg.value.content.project, function (err, gitRepo) {
458 if (gitRepo)
459 msg.value.content.repoName = gitRepo.value.content.name
460 cb(null, msg)
461 })
462 else
463 cb(null, msg)
464 }
465}
466
467function serveBlob(req, res, sbot, id, query) {
468 var q = query && qs.parse(query)
469 var unbox = q && typeof q.unbox === 'string' && q.unbox.replace(/\s/g, '+')
470 var etag = id + (unbox || '')
471
472 if (req.headers['if-none-match'] === etag) return respond(res, 304)
473 sbot.blobs.has(id, function (err, has) {
474 if (err) {
475 if (/^invalid/.test(err.message)) return respond(res, 400, err.message)
476 else return respond(res, 500, err.message || err)
477 }
478 if (!has) return respond(res, 404, 'Not found')
479
480 var unboxKey
481 if (unbox) {
482 try { unboxKey = new Buffer(unbox, 'base64') }
483 catch(e) { return respond(res, 400, err.message) }
484 if (unboxKey.length !== 32) return respond(res, 400, 'Bad blob key')
485 }
486
487 res.writeHead(200, {
488 'Cache-Control': 'public, max-age=315360000',
489 'etag': etag
490 })
491
492 pull(
493 sbot.blobs.get(id),
494 unboxKey ? BoxStream.createUnboxStream(unboxKey, zeros) : null,
495 toPull(res, function (err) {
496 if (err) console.error('[viewer]', err)
497 })
498 )
499 })
500}
501
502function getMsgWithValue(sbot, id, cb) {
503 sbot.get(id, function (err, value) {
504 if (err) return cb(err)
505 cb(null, {key: id, value: value})
506 })
507}
508
509function respond(res, status, message) {
510 res.writeHead(status)
511 res.end(message)
512}
513
514function ctype(name) {
515 switch (name && /[^.\/]*$/.exec(name)[0] || 'html') {
516 case 'html': return 'text/html'
517 case 'js': return 'text/javascript'
518 case 'css': return 'text/css'
519 case 'json': return 'application/json'
520 case 'rss': return 'text/xml'
521 }
522}
523
524function ifModified(req, lastMod) {
525 var ifModSince = req.headers['if-modified-since']
526 if (!ifModSince) return false
527 var d = new Date(ifModSince)
528 return d && Math.floor(d/1000) >= Math.floor(lastMod/1000)
529}
530
531function serveStatic(req, res, file) {
532 serveFile(req, res, path.join(__dirname, 'static', file))
533}
534
535function serveFile(req, res, file) {
536 fs.stat(file, function (err, stat) {
537 if (err && err.code === 'ENOENT') return respond(res, 404, 'Not found')
538 if (err) return respond(res, 500, err.stack || err)
539 if (!stat.isFile()) return respond(res, 403, 'May only load files')
540 if (ifModified(req, stat.mtime)) return respond(res, 304, 'Not modified')
541 res.writeHead(200, {
542 'Content-Type': ctype(file),
543 'Content-Length': stat.size,
544 'Last-Modified': stat.mtime.toGMTString()
545 })
546 fs.createReadStream(file).pipe(res)
547 })
548}
549
550function asChannelLink(id) {
551 var channel = refs.normalizeChannel(id)
552 if (channel) return '#' + channel
553}
554
555function asLink(id) {
556 if (!id || typeof id !== 'string') return null
557 id = id.trim()
558 if (id[0] === '#') return asChannelLink(id)
559 if (refs.isLink(id)) return id
560 try {
561 id = decodeURIComponent(id)
562 } catch(e) {
563 return null
564 }
565 if (id[0] === '#') return asChannelLink(id)
566 if (refs.isLink(id)) return id
567}
568
569function serveHome(req, res, query, conf) {
570 var q = query ? qs.parse(query) : {}
571 var id = asLink(q.id)
572 if (id) {
573 res.writeHead(303, {
574 Location: '/' + (
575 id[0] === '#' ? 'channel/' + id.substr(1) :
576 refs.isMsgId(id) ? encodeURIComponent(id) : id)
577 })
578 return res.end()
579 }
580 res.writeHead(200, {
581 'Content-Type': 'text/html'
582 })
583 pull(
584 pull.once(h('form', {method: 'get', action: ''},
585 h('input', {name: 'id', placeholder: 'id', size: 60, value: q.id || ''}), ' ',
586 h('input', {type: 'submit', value: 'Go'})
587 ).outerHTML),
588 wrapPage('ssb-viewer'),
589 toPull(res, function (err) {
590 if (err) console.error('[viewer]', err)
591 })
592 )
593}
594
595function serveRobots(req, res, conf) {
596 var disallow = conf.disallowRobots == null ? true : conf.disallowRobots
597 res.end('User-agent: *\n'
598 + (disallow ? 'Disallow: /\n' : ''))
599}
600
601function prepend(fn, arg) {
602 return function (read) {
603 return function (abort, cb) {
604 if (fn && !abort) {
605 var _fn = fn
606 fn = null
607 return _fn(arg, function (err, value) {
608 if (err) return read(err, function (err) {
609 cb(err || true)
610 })
611 cb(null, value)
612 })
613 }
614 read(abort, cb)
615 }
616 }
617}
618

Built with git-ssb-web