Files: eb408e8545d033be2ffe5456e27eb7972717e2d4 / index.js
12329 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 serveEmoji = require('emoji-server')() |
13 | var { |
14 | MdRenderer, |
15 | renderEmoji, |
16 | formatMsgs, |
17 | wrapPage, |
18 | renderThread, |
19 | renderAbout |
20 | } = require('./render'); |
21 | |
22 | var appHash = hash([fs.readFileSync(__filename)]) |
23 | |
24 | var urlIdRegex = /^(?:\/(([%&@]|%25|%26|%40)(?:[A-Za-z0-9\/+]|%2[Ff]|%2[Bb]){43}(?:=|%3[Dd])\.(?:sha256|ed25519))(?:\.([^?]*))?|(\/.*?))(?:\?(.*))?$/ |
25 | |
26 | function hash(arr) { |
27 | return arr.reduce(function (hash, item) { |
28 | return hash.update(String(item)) |
29 | }, crypto.createHash('sha256')).digest('base64') |
30 | } |
31 | |
32 | exports.name = 'viewer' |
33 | exports.manifest = {} |
34 | exports.version = require('./package').version |
35 | |
36 | exports.init = function (sbot, config) { |
37 | var conf = config.viewer || {} |
38 | var port = conf.port || 8807 |
39 | var host = conf.host || config.host || '::' |
40 | |
41 | var base = conf.base || '/' |
42 | var defaultOpts = { |
43 | base: base, |
44 | msg_base: conf.msg_base || base, |
45 | feed_base: conf.feed_base || base, |
46 | blob_base: conf.blob_base || base, |
47 | img_base: conf.img_base || base, |
48 | emoji_base: conf.emoji_base || (base + 'emoji/'), |
49 | } |
50 | |
51 | defaultOpts.marked = { |
52 | gfm: true, |
53 | mentions: true, |
54 | tables: true, |
55 | breaks: true, |
56 | pedantic: false, |
57 | sanitize: true, |
58 | smartLists: true, |
59 | smartypants: false, |
60 | emoji: renderEmoji, |
61 | renderer: new MdRenderer(defaultOpts) |
62 | } |
63 | |
64 | var getMsg = memo({cache: lru(100)}, getMsgWithValue, sbot) |
65 | var getAbout = memo({cache: lru(100)}, require('./lib/about'), sbot) |
66 | |
67 | http.createServer(serve).listen(port, host, function () { |
68 | console.log('[viewer] Listening on http://' + host + ':' + port) |
69 | }) |
70 | |
71 | function serve(req, res) { |
72 | if (req.method !== 'GET' && req.method !== 'HEAD') { |
73 | return respond(res, 405, 'Method must be GET or HEAD') |
74 | } |
75 | |
76 | var m = urlIdRegex.exec(req.url) |
77 | |
78 | if (req.url.startsWith('/user-feed/')) return serveUserFeed(req, res, m[4]) |
79 | else if (req.url.startsWith('/channel/')) return serveChannel(req, res, m[4]) |
80 | |
81 | if (m[2] && m[2].length === 3) { |
82 | m[1] = decodeURIComponent(m[1]) |
83 | m[2] = m[1][0] |
84 | } |
85 | switch (m[2]) { |
86 | case '%': return serveId(req, res, m[1], m[3], m[5]) |
87 | case '@': return serveFeed(req, res, m[1], m[3], m[5]) |
88 | case '&': return serveBlob(req, res, sbot, m[1]) |
89 | default: return servePath(req, res, m[4]) |
90 | } |
91 | } |
92 | |
93 | function serveFeed(req, res, feedId) { |
94 | console.log("serving feed: " + feedId) |
95 | |
96 | var showAll = req.url.endsWith("?showAll") |
97 | var showAllHTML = showAll ? '' : '<br/><a href="' + req.url + '?showAll">Show whole feed</a>' |
98 | |
99 | getAbout(feedId, function (err, about) { |
100 | if (err) return respond(res, 500, err.stack || err) |
101 | |
102 | pull( |
103 | sbot.createUserStream({ id: feedId, reverse: true, limit: showAll ? -1 : 10 }), |
104 | pull.collect(function (err, logs) { |
105 | if (err) return respond(res, 500, err.stack || err) |
106 | res.writeHead(200, { |
107 | 'Content-Type': ctype("html") |
108 | }) |
109 | pull( |
110 | pull.values(logs), |
111 | paramap(addAuthorAbout, 8), |
112 | paramap(addFollowAbout, 8), |
113 | paramap(addVoteMessage, 8), |
114 | paramap(addGitLinks, 8), |
115 | pull(renderAbout(defaultOpts, about, showAllHTML), wrapPage(about.name)), |
116 | toPull(res, function (err) { |
117 | if (err) console.error('[viewer]', err) |
118 | }) |
119 | ) |
120 | }) |
121 | ) |
122 | }) |
123 | } |
124 | |
125 | function serveUserFeed(req, res, url) { |
126 | var feedId = url.substring(url.lastIndexOf('user-feed/')+10, 100) |
127 | console.log("serving user feed: " + feedId) |
128 | |
129 | var following = [] |
130 | var channelSubscriptions = [] |
131 | |
132 | getAbout(feedId, function (err, about) { |
133 | pull( |
134 | sbot.createUserStream({ id: feedId }), |
135 | pull.filter((msg) => { |
136 | return !msg.value || |
137 | msg.value.content.type == 'contact' || |
138 | (msg.value.content.type == 'channel' && |
139 | typeof msg.value.content.subscribed != 'undefined') |
140 | }), |
141 | pull.collect(function (err, msgs) { |
142 | msgs.forEach((msg) => { |
143 | if (msg.value.content.type == 'contact') |
144 | { |
145 | if (msg.value.content.following) |
146 | following[msg.value.content.contact] = 1 |
147 | else |
148 | delete following[msg.value.content.contact] |
149 | } |
150 | else // channel subscription |
151 | { |
152 | if (msg.value.content.subscribed) |
153 | channelSubscriptions[msg.value.content.channel] = 1 |
154 | else |
155 | delete channelSubscriptions[msg.value.content.channel] |
156 | } |
157 | }) |
158 | |
159 | serveFeeds(req, res, following, channelSubscriptions, feedId, 'user feed ' + about.name) |
160 | }) |
161 | ) |
162 | }) |
163 | } |
164 | |
165 | function serveFeeds(req, res, following, channelSubscriptions, feedId, name) { |
166 | pull( |
167 | sbot.createLogStream({ reverse: true, limit: 5000 }), |
168 | pull.filter((msg) => { |
169 | return !msg.value || |
170 | (msg.value.author in following || |
171 | msg.value.content.channel in channelSubscriptions) |
172 | }), |
173 | pull.take(150), |
174 | pull.collect(function (err, logs) { |
175 | if (err) return respond(res, 500, err.stack || err) |
176 | res.writeHead(200, { |
177 | 'Content-Type': ctype("html") |
178 | }) |
179 | pull( |
180 | pull.values(logs), |
181 | paramap(addAuthorAbout, 8), |
182 | paramap(addFollowAbout, 8), |
183 | paramap(addVoteMessage, 8), |
184 | paramap(addGitLinks, 8), |
185 | pull(renderThread(defaultOpts), wrapPage(name)), |
186 | toPull(res, function (err) { |
187 | if (err) console.error('[viewer]', err) |
188 | }) |
189 | ) |
190 | }) |
191 | ) |
192 | } |
193 | |
194 | function serveChannel(req, res, url) { |
195 | var channelId = url.substring(url.lastIndexOf('channel/')+8, 100) |
196 | console.log("serving channel: " + channelId) |
197 | |
198 | var showAll = req.url.endsWith("?showAll") |
199 | var showAllHTML = showAll ? '' : '<br/><a href="' + req.url + '?showAll">Show whole feed</a>' |
200 | |
201 | pull( |
202 | sbot.query.read({ limit: showAll ? 300 : 10, reverse: true, query: [{$filter: { value: { content: { channel: channelId }}}}]}), |
203 | pull.collect(function (err, logs) { |
204 | if (err) return respond(res, 500, err.stack || err) |
205 | res.writeHead(200, { |
206 | 'Content-Type': ctype("html") |
207 | }) |
208 | pull( |
209 | pull.values(logs), |
210 | paramap(addAuthorAbout, 8), |
211 | paramap(addVoteMessage, 8), |
212 | pull(renderThread(defaultOpts, showAllHTML), wrapPage('#' + channelId)), |
213 | toPull(res, function (err) { |
214 | if (err) console.error('[viewer]', err) |
215 | }) |
216 | ) |
217 | }) |
218 | ) |
219 | } |
220 | |
221 | function serveId(req, res, id, ext, query) { |
222 | var q = query ? qs.parse(query) : {} |
223 | var includeRoot = !('noroot' in q) |
224 | var base = q.base || conf.base |
225 | var baseToken |
226 | if (!base) { |
227 | if (ext === 'js') base = baseToken = '__BASE_' + Math.random() + '_' |
228 | else base = '/' |
229 | } |
230 | var opts = { |
231 | base: base, |
232 | base_token: baseToken, |
233 | msg_base: q.msg_base || conf.msg_base || base, |
234 | feed_base: q.feed_base || conf.feed_base || base, |
235 | blob_base: q.blob_base || conf.blob_base || base, |
236 | img_base: q.img_base || conf.img_base || base, |
237 | emoji_base: q.emoji_base || conf.emoji_base || (base + 'emoji/'), |
238 | } |
239 | opts.marked = { |
240 | gfm: true, |
241 | mentions: true, |
242 | tables: true, |
243 | breaks: true, |
244 | pedantic: false, |
245 | sanitize: true, |
246 | smartLists: true, |
247 | smartypants: false, |
248 | emoji: renderEmoji, |
249 | renderer: new MdRenderer(opts) |
250 | } |
251 | |
252 | var format = formatMsgs(id, ext, opts) |
253 | if (format === null) return respond(res, 415, 'Invalid format') |
254 | |
255 | pull( |
256 | sbot.links({dest: id, values: true }), |
257 | includeRoot && prepend(getMsg, id), |
258 | pull.unique('key'), |
259 | pull.collect(function (err, links) { |
260 | if (err) return respond(res, 500, err.stack || err) |
261 | var etag = hash(sort.heads(links).concat(appHash, ext, qs)) |
262 | if (req.headers['if-none-match'] === etag) return respond(res, 304) |
263 | res.writeHead(200, { |
264 | 'Content-Type': ctype(ext), |
265 | 'etag': etag |
266 | }) |
267 | pull( |
268 | pull.values(sort(links)), |
269 | paramap(addAuthorAbout, 8), |
270 | format, |
271 | toPull(res, function (err) { |
272 | if (err) console.error('[viewer]', err) |
273 | }) |
274 | ) |
275 | }) |
276 | ) |
277 | } |
278 | |
279 | function addFollowAbout(msg, cb) { |
280 | if (msg.value.content.contact) |
281 | getAbout(msg.value.content.contact, function (err, about) { |
282 | if (err) return cb(err) |
283 | msg.value.content.contactAbout = about |
284 | cb(null, msg) |
285 | }) |
286 | else |
287 | cb(null, msg) |
288 | } |
289 | |
290 | function addVoteMessage(msg, cb) { |
291 | if (msg.value.content.type == 'vote' && msg.value.content.vote.link[0] == '%') |
292 | getMsg(msg.value.content.vote.link, function (err, linkedMsg) { |
293 | if (linkedMsg) |
294 | msg.value.content.vote.linkedText = linkedMsg.value.content.text |
295 | cb(null, msg) |
296 | }) |
297 | else |
298 | cb(null, msg) |
299 | } |
300 | |
301 | function addAuthorAbout(msg, cb) { |
302 | getAbout(msg.value.author, function (err, about) { |
303 | if (err) return cb(err) |
304 | msg.author = about |
305 | cb(null, msg) |
306 | }) |
307 | } |
308 | |
309 | function addGitLinks(msg, cb) { |
310 | if (msg.value.content.type == 'git-update') |
311 | getMsg(msg.value.content.repo, function (err, gitRepo) { |
312 | if (gitRepo) |
313 | msg.value.content.repoName = gitRepo.value.content.name |
314 | cb(null, msg) |
315 | }) |
316 | else if (msg.value.content.type == 'issue') |
317 | getMsg(msg.value.content.project, function (err, gitRepo) { |
318 | if (gitRepo) |
319 | msg.value.content.repoName = gitRepo.value.content.name |
320 | cb(null, msg) |
321 | }) |
322 | else |
323 | cb(null, msg) |
324 | } |
325 | } |
326 | |
327 | function serveBlob(req, res, sbot, id) { |
328 | if (req.headers['if-none-match'] === id) return respond(res, 304) |
329 | sbot.blobs.has(id, function (err, has) { |
330 | if (err) { |
331 | if (/^invalid/.test(err.message)) return respond(res, 400, err.message) |
332 | else return respond(res, 500, err.message || err) |
333 | } |
334 | if (!has) return respond(res, 404, 'Not found') |
335 | res.writeHead(200, { |
336 | 'Cache-Control': 'public, max-age=315360000', |
337 | 'etag': id |
338 | }) |
339 | pull( |
340 | sbot.blobs.get(id), |
341 | toPull(res, function (err) { |
342 | if (err) console.error('[viewer]', err) |
343 | }) |
344 | ) |
345 | }) |
346 | } |
347 | |
348 | function getMsgWithValue(sbot, id, cb) { |
349 | sbot.get(id, function (err, value) { |
350 | if (err) return cb(err) |
351 | cb(null, {key: id, value: value}) |
352 | }) |
353 | } |
354 | |
355 | function respond(res, status, message) { |
356 | res.writeHead(status) |
357 | res.end(message) |
358 | } |
359 | |
360 | function ctype(name) { |
361 | switch (name && /[^.\/]*$/.exec(name)[0] || 'html') { |
362 | case 'html': return 'text/html' |
363 | case 'js': return 'text/javascript' |
364 | case 'css': return 'text/css' |
365 | case 'json': return 'application/json' |
366 | } |
367 | } |
368 | |
369 | function servePath(req, res, url) { |
370 | switch (url) { |
371 | case '/robots.txt': return res.end('User-agent: *') |
372 | } |
373 | var m = /^(\/?[^\/]*)(\/.*)?$/.exec(url) |
374 | switch (m[1]) { |
375 | case '/static': return serveStatic(req, res, m[2]) |
376 | case '/emoji': return serveEmoji(req, res, m[2]) |
377 | } |
378 | return respond(res, 404, 'Not found') |
379 | } |
380 | |
381 | function ifModified(req, lastMod) { |
382 | var ifModSince = req.headers['if-modified-since'] |
383 | if (!ifModSince) return false |
384 | var d = new Date(ifModSince) |
385 | return d && Math.floor(d/1000) >= Math.floor(lastMod/1000) |
386 | } |
387 | |
388 | function serveStatic(req, res, file) { |
389 | serveFile(req, res, path.join(__dirname, 'static', file)) |
390 | } |
391 | |
392 | function serveFile(req, res, file) { |
393 | fs.stat(file, function (err, stat) { |
394 | if (err && err.code === 'ENOENT') return respond(res, 404, 'Not found') |
395 | if (err) return respond(res, 500, err.stack || err) |
396 | if (!stat.isFile()) return respond(res, 403, 'May only load files') |
397 | if (ifModified(req, stat.mtime)) return respond(res, 304, 'Not modified') |
398 | res.writeHead(200, { |
399 | 'Content-Type': ctype(file), |
400 | 'Content-Length': stat.size, |
401 | 'Last-Modified': stat.mtime.toGMTString() |
402 | }) |
403 | fs.createReadStream(file).pipe(res) |
404 | }) |
405 | } |
406 | |
407 | function prepend(fn, arg) { |
408 | return function (read) { |
409 | return function (abort, cb) { |
410 | if (fn && !abort) { |
411 | var _fn = fn |
412 | fn = null |
413 | return _fn(arg, function (err, value) { |
414 | if (err) return read(err, function (err) { |
415 | cb(err || true) |
416 | }) |
417 | cb(null, value) |
418 | }) |
419 | } |
420 | read(abort, cb) |
421 | } |
422 | } |
423 | } |
424 |
Built with git-ssb-web