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