Files: 773fd1b7228f74b7b9788e4426906a0eae566c9a / index.js
11119 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 && /^invalid/.test(err.message)) return respond(400, err.message) |
166 | if (err) return respond(500, err.message || err) |
167 | if (!has) return respond(404, 'Not found') |
168 | res.writeHead(200, { |
169 | 'Cache-Control': 'public, max-age=315360000', |
170 | 'etag': id |
171 | }) |
172 | pull( |
173 | sbot.blobs.get(id), |
174 | toPull(res, function (err) { |
175 | if (err) console.error('[viewer]', err) |
176 | }) |
177 | ) |
178 | }) |
179 | } |
180 | |
181 | function getMsgWithValue(sbot, id, cb) { |
182 | sbot.get(id, function (err, value) { |
183 | if (err) return cb(err) |
184 | cb(null, {key: id, value: value}) |
185 | }) |
186 | } |
187 | |
188 | function escape(str) { |
189 | return String(str) |
190 | .replace(/&/g, '&') |
191 | .replace(/</g, '<') |
192 | .replace(/>/g, '>') |
193 | .replace(/"/g, '"') |
194 | } |
195 | |
196 | function respond(res, status, message) { |
197 | res.writeHead(status) |
198 | res.end(message) |
199 | } |
200 | |
201 | function ctype(name) { |
202 | switch (name && /[^.\/]*$/.exec(name)[0] || 'html') { |
203 | case 'html': return 'text/html' |
204 | case 'js': return 'text/javascript' |
205 | case 'css': return 'text/css' |
206 | case 'json': return 'application/json' |
207 | } |
208 | } |
209 | |
210 | function servePath(req, res, url) { |
211 | switch (url) { |
212 | case '/robots.txt': return res.end('User-agent: *') |
213 | } |
214 | var m = /^(\/?[^\/]*)(\/.*)?$/.exec(url) |
215 | switch (m[1]) { |
216 | case '/static': return serveStatic(req, res, m[2]) |
217 | case '/emoji': return serveEmoji(req, res, m[2]) |
218 | } |
219 | return respond(res, 404, 'Not found') |
220 | } |
221 | |
222 | function ifModified(req, lastMod) { |
223 | var ifModSince = req.headers['if-modified-since'] |
224 | if (!ifModSince) return false |
225 | var d = new Date(ifModSince) |
226 | return d && Math.floor(d/1000) >= Math.floor(lastMod/1000) |
227 | } |
228 | |
229 | function serveStatic(req, res, file) { |
230 | serveFile(req, res, path.join(__dirname, 'static', file)) |
231 | } |
232 | |
233 | function serveFile(req, res, file) { |
234 | fs.stat(file, function (err, stat) { |
235 | if (err && err.code === 'ENOENT') return respond(res, 404, 'Not found') |
236 | if (err) return respond(res, 500, err.stack || err) |
237 | if (!stat.isFile()) return respond(res, 403, 'May only load files') |
238 | if (ifModified(req, stat.mtime)) return respond(res, 304, 'Not modified') |
239 | res.writeHead(200, { |
240 | 'Content-Type': ctype(file), |
241 | 'Content-Length': stat.size, |
242 | 'Last-Modified': stat.mtime.toGMTString() |
243 | }) |
244 | fs.createReadStream(file).pipe(res) |
245 | }) |
246 | } |
247 | |
248 | function prepend(fn, arg) { |
249 | return function (read) { |
250 | return function (abort, cb) { |
251 | if (fn && !abort) { |
252 | var _fn = fn |
253 | fn = null |
254 | return _fn(arg, function (err, value) { |
255 | if (err) return read(err, function (err) { |
256 | cb(err || true) |
257 | }) |
258 | cb(null, value) |
259 | }) |
260 | } |
261 | read(abort, cb) |
262 | } |
263 | } |
264 | } |
265 | |
266 | function formatMsgs(id, ext, opts) { |
267 | switch (ext || 'html') { |
268 | case 'html': return pull(renderThread(opts), wrapPage(id)) |
269 | case 'js': return pull(renderThread(opts), wrapJSEmbed(opts)) |
270 | case 'json': return wrapJSON() |
271 | default: return null |
272 | } |
273 | } |
274 | |
275 | function wrap(before, after) { |
276 | return function (read) { |
277 | return cat([pull.once(before), read, pull.once(after)]) |
278 | } |
279 | } |
280 | |
281 | function renderThread(opts) { |
282 | return pull( |
283 | pull.map(renderMsg.bind(this, opts)), |
284 | wrap('<div class="ssb-thread">', '</div>') |
285 | ) |
286 | } |
287 | |
288 | function wrapPage(id) { |
289 | return wrap('<!doctype html><html><head>' |
290 | + '<meta charset=utf-8>' |
291 | + '<title>' + id + '</title>' |
292 | + '<meta name=viewport content="width=device-width,initial-scale=1">' |
293 | + '<link rel=stylesheet href="/static/base.css">' |
294 | + '<link rel=stylesheet href="/static/nicer.css">' |
295 | + '</head><body>', |
296 | '</body></html>' |
297 | ) |
298 | } |
299 | |
300 | function wrapJSON() { |
301 | var first = true |
302 | return pull( |
303 | pull.map(JSON.stringify), |
304 | join(','), |
305 | wrap('[', ']') |
306 | ) |
307 | } |
308 | |
309 | function wrapJSEmbed(opts) { |
310 | return pull( |
311 | wrap('<link rel=stylesheet href="' + opts.base + 'static/base.css">', ''), |
312 | pull.map(docWrite), |
313 | opts.base_token && rewriteBase(new RegExp(opts.base_token, 'g')) |
314 | ) |
315 | } |
316 | |
317 | |
318 | function rewriteBase(token) { |
319 | // detect the origin of the script and rewrite the js/html to use it |
320 | return pull( |
321 | replace(token, '" + SSB_VIEWER_ORIGIN + "/'), |
322 | wrap('var SSB_VIEWER_ORIGIN = (function () {' |
323 | + 'var scripts = document.getElementsByTagName("script")\n' |
324 | + 'var script = scripts[scripts.length-1]\n' |
325 | + 'if (!script) return location.origin\n' |
326 | + 'return script.src.replace(/\\/%.*$/, "")\n' |
327 | + '}())\n', '') |
328 | ) |
329 | } |
330 | |
331 | function join(delim) { |
332 | var first = true |
333 | return pull.map(function (val) { |
334 | if (!first) return delim + String(val) |
335 | first = false |
336 | return val |
337 | }) |
338 | } |
339 | |
340 | function replace(re, rep) { |
341 | return pull.map(function (val) { |
342 | return String(val).replace(re, rep) |
343 | }) |
344 | } |
345 | |
346 | function docWrite(str) { |
347 | return 'document.write(' + JSON.stringify(str) + ')\n' |
348 | } |
349 | |
350 | function hash(arr) { |
351 | return arr.reduce(function (hash, item) { |
352 | return hash.update(String(item)) |
353 | }, crypto.createHash('sha256')).digest('base64') |
354 | } |
355 | |
356 | function renderMsg(opts, msg) { |
357 | var c = msg.value.content || {} |
358 | var name = encodeURIComponent(msg.key) |
359 | return '<div class="ssb-message" id="' + name + '">' |
360 | + '<img class="ssb-avatar-image" alt=""' |
361 | + ' src="' + opts.img_base + escape(msg.author.image) + '"' |
362 | + ' height="32" width="32">' |
363 | + '<a class="ssb-avatar-name"' |
364 | + ' href="' + opts.feed_base + escape(msg.value.author) + '"' |
365 | + '>' + msg.author.name + '</a>' |
366 | + msgTimestamp(msg, name) |
367 | + (c.type === 'post' ? renderPost(opts, c) : renderDefault(c)) |
368 | + '</div>' |
369 | } |
370 | |
371 | function msgTimestamp(msg, name) { |
372 | var date = new Date(msg.value.timestamp) |
373 | return '<time class="ssb-timestamp" datetime="' + date.toISOString() + '">' |
374 | + '<a href="#' + name + '">' |
375 | + formatDate(date) + '</a></time>' |
376 | } |
377 | |
378 | function formatDate(date) { |
379 | // return date.toISOString().replace('T', ' ') |
380 | return htime(date) |
381 | } |
382 | |
383 | function renderPost(opts, c) { |
384 | return '<div class="ssb-post">' + marked(c.text, opts.marked) + '</div>' |
385 | } |
386 | |
387 | function renderDefault(c) { |
388 | return '<pre>' + JSON.stringify(c, 0, 2) + '</pre>' |
389 | } |
390 |
Built with git-ssb-web