git ssb

0+

Daan Patchwork / ssb-viewer



forked from cel / ssb-viewer

Tree: 36c63bc1828456bf3417ff9eb5187cfcb776b3b2

Files: 36c63bc1828456bf3417ff9eb5187cfcb776b3b2 / index.js

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

Built with git-ssb-web