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