Files: d52a7a5104122d27a4c209f65d8e9ab5e84c7e88 / index.js
11148 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 cat = require('pull-cat') |
7 | var pull = require('pull-stream') |
8 | var paramap = require('pull-paramap') |
9 | var marked = require('ssb-marked') |
10 | var sort = require('ssb-sort') |
11 | var toPull = require('stream-to-pull-stream') |
12 | var memo = require('asyncmemo') |
13 | var lru = require('lrucache') |
14 | var htime = require('human-time') |
15 | var emojis = require('emoji-named-characters') |
16 | var serveEmoji = require('emoji-server')() |
17 | |
18 | var emojiDir = path.join(require.resolve('emoji-named-characters'), '../pngs') |
19 | var appHash = hash([fs.readFileSync(__filename)]) |
20 | |
21 | var urlIdRegex = /^(?:\/(([%&]|%25)(?:[A-Za-z0-9\/+]|%2[Ff]|%2[Bb]){43}(?:=|%3D)\.sha256)(?:\.([^?]*))?|(\/.*?))(?:\?(.*))?$/ |
22 | |
23 | function MdRenderer(opts) { |
24 | marked.Renderer.call(this, {}) |
25 | this.opts = opts |
26 | } |
27 | MdRenderer.prototype = new marked.Renderer() |
28 | |
29 | MdRenderer.prototype.urltransform = function (href) { |
30 | if (!href) return false |
31 | switch (href[0]) { |
32 | case '%': return this.opts.msg_base + encodeURIComponent(href) |
33 | case '@': return this.opts.feed_base + encodeURIComponent(href) |
34 | case '&': return this.opts.blob_base + encodeURIComponent(href) |
35 | } |
36 | if (href.indexOf('javascript:') === 0) return false |
37 | return href |
38 | } |
39 | |
40 | MdRenderer.prototype.image = function (href, title, text) { |
41 | return '<img src="' + this.opts.img_base + escape(href) + '"' |
42 | + ' alt="' + text + '"' |
43 | + (title ? ' title="' + title + '"' : '') |
44 | + (this.options.xhtml ? '/>' : '>') |
45 | } |
46 | |
47 | function renderEmoji(emoji) { |
48 | var opts = this.renderer.opts |
49 | return emoji in emojis ? |
50 | '<img src="' + opts.emoji_base + escape(emoji) + '.png"' |
51 | + ' alt=":' + escape(emoji) + ':"' |
52 | + ' title=":' + escape(emoji) + ':"' |
53 | + ' class="ssb-emoji" height="16" width="16">' |
54 | : ':' + emoji + ':' |
55 | } |
56 | |
57 | exports.name = 'viewer' |
58 | exports.manifest = {} |
59 | exports.version = require('./package').version |
60 | |
61 | exports.init = function (sbot, config) { |
62 | var conf = config.viewer || {} |
63 | var port = conf.port || 8807 |
64 | var host = conf.host || config.host || '::' |
65 | |
66 | var base = conf.base || '/' |
67 | var defaultOpts = { |
68 | msg_base: conf.msg_base || base, |
69 | feed_base: conf.feed_base || '#', |
70 | blob_base: conf.blob_base || base, |
71 | img_base: conf.img_base || base, |
72 | emoji_base: conf.emoji_base || (base + 'emoji/'), |
73 | } |
74 | |
75 | var getMsg = memo({cache: lru(100)}, getMsgWithValue, sbot) |
76 | var getAbout = memo({cache: lru(100)}, require('./lib/about'), sbot) |
77 | |
78 | http.createServer(serve).listen(port, host, function () { |
79 | console.log('[viewer] Listening on http://' + host + ':' + port) |
80 | }) |
81 | |
82 | function serve(req, res) { |
83 | if (req.method !== 'GET' && req.method !== 'HEAD') { |
84 | return respond(res, 405, 'Method must be GET or HEAD') |
85 | } |
86 | var m = urlIdRegex.exec(req.url) |
87 | switch (m[2]) { |
88 | case '%25': m[2] = '%'; m[1] = decodeURIComponent(m[1]) |
89 | case '%': return serveId(req, res, m[1], m[3], m[5]) |
90 | case '&': return serveBlob(req, res, sbot, m[1]) |
91 | default: return servePath(req, res, m[4]) |
92 | } |
93 | } |
94 | |
95 | function serveId(req, res, id, ext, query) { |
96 | var q = query ? qs.parse(query) : {} |
97 | var includeRoot = !('noroot' in q) |
98 | var base = q.base || conf.base |
99 | var baseToken |
100 | if (!base) { |
101 | if (ext === 'js') base = baseToken = '__BASE_' + Math.random() + '_' |
102 | else base = '/' |
103 | } |
104 | var opts = { |
105 | base: base, |
106 | base_token: baseToken, |
107 | msg_base: q.msg_base || conf.msg_base || base, |
108 | feed_base: q.feed_base || conf.feed_base || '#', |
109 | blob_base: q.blob_base || conf.blob_base || base, |
110 | img_base: q.img_base || conf.img_base || base, |
111 | emoji_base: q.emoji_base || conf.emoji_base || (base + 'emoji/'), |
112 | } |
113 | opts.marked = { |
114 | gfm: true, |
115 | mentions: true, |
116 | tables: true, |
117 | breaks: true, |
118 | pedantic: false, |
119 | sanitize: true, |
120 | smartLists: true, |
121 | smartypants: false, |
122 | emoji: renderEmoji, |
123 | renderer: new MdRenderer(opts) |
124 | } |
125 | |
126 | var format = formatMsgs(id, ext, opts) |
127 | if (format === null) return respond(res, 415, 'Invalid format') |
128 | |
129 | pull( |
130 | sbot.links({dest: id, values: true, rel: 'root'}), |
131 | includeRoot && prepend(getMsg, id), |
132 | pull.unique('key'), |
133 | pull.collect(function (err, links) { |
134 | if (err) return respond(res, 500, err.stack || err) |
135 | var etag = hash(sort.heads(links).concat(appHash, ext, qs)) |
136 | if (req.headers['if-none-match'] === etag) return respond(res, 304) |
137 | res.writeHead(200, { |
138 | 'Content-Type': ctype(ext), |
139 | 'etag': etag |
140 | }) |
141 | pull( |
142 | pull.values(sort(links)), |
143 | paramap(addAuthorAbout, 8), |
144 | format, |
145 | toPull(res, function (err) { |
146 | if (err) console.error('[viewer]', err) |
147 | }) |
148 | ) |
149 | }) |
150 | ) |
151 | } |
152 | |
153 | function addAuthorAbout(msg, cb) { |
154 | getAbout(msg.value.author, function (err, about) { |
155 | if (err) return cb(err) |
156 | msg.author = about |
157 | cb(null, msg) |
158 | }) |
159 | } |
160 | } |
161 | |
162 | function serveBlob(req, res, sbot, id) { |
163 | if (req.headers['if-none-match'] === id) return respond(res, 304) |
164 | sbot.blobs.has(id, function (err, has) { |
165 | if (err) { |
166 | if (/^invalid/.test(err.message)) return respond(res, 400, err.message) |
167 | else return respond(res, 500, err.message || err) |
168 | } |
169 | if (!has) return respond(res, 404, 'Not found') |
170 | res.writeHead(200, { |
171 | 'Cache-Control': 'public, max-age=315360000', |
172 | 'etag': id |
173 | }) |
174 | pull( |
175 | sbot.blobs.get(id), |
176 | toPull(res, function (err) { |
177 | if (err) console.error('[viewer]', err) |
178 | }) |
179 | ) |
180 | }) |
181 | } |
182 | |
183 | function getMsgWithValue(sbot, id, cb) { |
184 | sbot.get(id, function (err, value) { |
185 | if (err) return cb(err) |
186 | cb(null, {key: id, value: value}) |
187 | }) |
188 | } |
189 | |
190 | function escape(str) { |
191 | return String(str) |
192 | .replace(/&/g, '&') |
193 | .replace(/</g, '<') |
194 | .replace(/>/g, '>') |
195 | .replace(/"/g, '"') |
196 | } |
197 | |
198 | function respond(res, status, message) { |
199 | res.writeHead(status) |
200 | res.end(message) |
201 | } |
202 | |
203 | function ctype(name) { |
204 | switch (name && /[^.\/]*$/.exec(name)[0] || 'html') { |
205 | case 'html': return 'text/html' |
206 | case 'js': return 'text/javascript' |
207 | case 'css': return 'text/css' |
208 | case 'json': return 'application/json' |
209 | } |
210 | } |
211 | |
212 | function servePath(req, res, url) { |
213 | switch (url) { |
214 | case '/robots.txt': return res.end('User-agent: *') |
215 | } |
216 | var m = /^(\/?[^\/]*)(\/.*)?$/.exec(url) |
217 | switch (m[1]) { |
218 | case '/static': return serveStatic(req, res, m[2]) |
219 | case '/emoji': return serveEmoji(req, res, m[2]) |
220 | } |
221 | return respond(res, 404, 'Not found') |
222 | } |
223 | |
224 | function ifModified(req, lastMod) { |
225 | var ifModSince = req.headers['if-modified-since'] |
226 | if (!ifModSince) return false |
227 | var d = new Date(ifModSince) |
228 | return d && Math.floor(d/1000) >= Math.floor(lastMod/1000) |
229 | } |
230 | |
231 | function serveStatic(req, res, file) { |
232 | serveFile(req, res, path.join(__dirname, 'static', file)) |
233 | } |
234 | |
235 | function serveFile(req, res, file) { |
236 | fs.stat(file, function (err, stat) { |
237 | if (err && err.code === 'ENOENT') return respond(res, 404, 'Not found') |
238 | if (err) return respond(res, 500, err.stack || err) |
239 | if (!stat.isFile()) return respond(res, 403, 'May only load files') |
240 | if (ifModified(req, stat.mtime)) return respond(res, 304, 'Not modified') |
241 | res.writeHead(200, { |
242 | 'Content-Type': ctype(file), |
243 | 'Content-Length': stat.size, |
244 | 'Last-Modified': stat.mtime.toGMTString() |
245 | }) |
246 | fs.createReadStream(file).pipe(res) |
247 | }) |
248 | } |
249 | |
250 | function prepend(fn, arg) { |
251 | return function (read) { |
252 | return function (abort, cb) { |
253 | if (fn && !abort) { |
254 | var _fn = fn |
255 | fn = null |
256 | return _fn(arg, function (err, value) { |
257 | if (err) return read(err, function (err) { |
258 | cb(err || true) |
259 | }) |
260 | cb(null, value) |
261 | }) |
262 | } |
263 | read(abort, cb) |
264 | } |
265 | } |
266 | } |
267 | |
268 | function formatMsgs(id, ext, opts) { |
269 | switch (ext || 'html') { |
270 | case 'html': return pull(renderThread(opts), wrapPage(id)) |
271 | case 'js': return pull(renderThread(opts), wrapJSEmbed(opts)) |
272 | case 'json': return wrapJSON() |
273 | default: return null |
274 | } |
275 | } |
276 | |
277 | function wrap(before, after) { |
278 | return function (read) { |
279 | return cat([pull.once(before), read, pull.once(after)]) |
280 | } |
281 | } |
282 | |
283 | function renderThread(opts) { |
284 | return pull( |
285 | pull.map(renderMsg.bind(this, opts)), |
286 | wrap('<div class="ssb-thread">', '</div>') |
287 | ) |
288 | } |
289 | |
290 | function wrapPage(id) { |
291 | return wrap('<!doctype html><html><head>' |
292 | + '<meta charset=utf-8>' |
293 | + '<title>' + id + '</title>' |
294 | + '<meta name=viewport content="width=device-width,initial-scale=1">' |
295 | + '<link rel=stylesheet href="/static/base.css">' |
296 | + '<link rel=stylesheet href="/static/nicer.css">' |
297 | + '</head><body>', |
298 | '</body></html>' |
299 | ) |
300 | } |
301 | |
302 | function wrapJSON() { |
303 | var first = true |
304 | return pull( |
305 | pull.map(JSON.stringify), |
306 | join(','), |
307 | wrap('[', ']') |
308 | ) |
309 | } |
310 | |
311 | function wrapJSEmbed(opts) { |
312 | return pull( |
313 | wrap('<link rel=stylesheet href="' + opts.base + 'static/base.css">', ''), |
314 | pull.map(docWrite), |
315 | opts.base_token && rewriteBase(new RegExp(opts.base_token, 'g')) |
316 | ) |
317 | } |
318 | |
319 | |
320 | function rewriteBase(token) { |
321 | // detect the origin of the script and rewrite the js/html to use it |
322 | return pull( |
323 | replace(token, '" + SSB_VIEWER_ORIGIN + "/'), |
324 | wrap('var SSB_VIEWER_ORIGIN = (function () {' |
325 | + 'var scripts = document.getElementsByTagName("script")\n' |
326 | + 'var script = scripts[scripts.length-1]\n' |
327 | + 'if (!script) return location.origin\n' |
328 | + 'return script.src.replace(/\\/%.*$/, "")\n' |
329 | + '}())\n', '') |
330 | ) |
331 | } |
332 | |
333 | function join(delim) { |
334 | var first = true |
335 | return pull.map(function (val) { |
336 | if (!first) return delim + String(val) |
337 | first = false |
338 | return val |
339 | }) |
340 | } |
341 | |
342 | function replace(re, rep) { |
343 | return pull.map(function (val) { |
344 | return String(val).replace(re, rep) |
345 | }) |
346 | } |
347 | |
348 | function docWrite(str) { |
349 | return 'document.write(' + JSON.stringify(str) + ')\n' |
350 | } |
351 | |
352 | function hash(arr) { |
353 | return arr.reduce(function (hash, item) { |
354 | return hash.update(String(item)) |
355 | }, crypto.createHash('sha256')).digest('base64') |
356 | } |
357 | |
358 | function renderMsg(opts, msg) { |
359 | var c = msg.value.content || {} |
360 | var name = encodeURIComponent(msg.key) |
361 | return '<div class="ssb-message" id="' + name + '">' |
362 | + '<img class="ssb-avatar-image" alt=""' |
363 | + ' src="' + opts.img_base + escape(msg.author.image) + '"' |
364 | + ' height="32" width="32">' |
365 | + '<a class="ssb-avatar-name"' |
366 | + ' href="' + opts.feed_base + escape(msg.value.author) + '"' |
367 | + '>' + msg.author.name + '</a>' |
368 | + msgTimestamp(msg, name) |
369 | + (c.type === 'post' ? renderPost(opts, c) : renderDefault(c)) |
370 | + '</div>' |
371 | } |
372 | |
373 | function msgTimestamp(msg, name) { |
374 | var date = new Date(msg.value.timestamp) |
375 | return '<time class="ssb-timestamp" datetime="' + date.toISOString() + '">' |
376 | + '<a href="#' + name + '">' |
377 | + formatDate(date) + '</a></time>' |
378 | } |
379 | |
380 | function formatDate(date) { |
381 | // return date.toISOString().replace('T', ' ') |
382 | return htime(date) |
383 | } |
384 | |
385 | function renderPost(opts, c) { |
386 | return '<div class="ssb-post">' + marked(c.text, opts.marked) + '</div>' |
387 | } |
388 | |
389 | function renderDefault(c) { |
390 | return '<pre>' + JSON.stringify(c, 0, 2) + '</pre>' |
391 | } |
392 |
Built with git-ssb-web