git ssb

9+

cel / ssb-viewer



Tree: 08321fdd28495d2cb08d4f7256ed2f6aab925315

Files: 08321fdd28495d2cb08d4f7256ed2f6aab925315 / index.js

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

Built with git-ssb-web