git ssb

9+

cel / ssb-viewer



Tree: cecdc93fd30b7c181e4e9720a98ef8f788355906

Files: cecdc93fd30b7c181e4e9720a98ef8f788355906 / index.js

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

Built with git-ssb-web