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