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