git ssb

9+

cel / ssb-viewer



Tree: b99fb41a81ed0e6a2d0e1f32c5fae9ce6cf5d9de

Files: b99fb41a81ed0e6a2d0e1f32c5fae9ce6cf5d9de / index.js

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

Built with git-ssb-web