git ssb

0+

Daan Patchwork / ssb-viewer



forked from cel / ssb-viewer

Tree: f09e7259ef382ed0b8862e0631cc1f157bbc101a

Files: f09e7259ef382ed0b8862e0631cc1f157bbc101a / index.js

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

Built with git-ssb-web