git ssb

9+

cel / ssb-viewer



Tree: efdeaa0a623ee9b7e7a4d700a02f61921260e575

Files: efdeaa0a623ee9b7e7a4d700a02f61921260e575 / index.js

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

Built with git-ssb-web