git ssb

0+

Daan Patchwork / ssb-viewer



forked from cel / ssb-viewer

Tree: e042fb79339f605bb9bea4d8d2e0c4db84d8ec89

Files: e042fb79339f605bb9bea4d8d2e0c4db84d8ec89 / index.js

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

Built with git-ssb-web