git ssb

10+

Matt McKegg / patchwork



Tree: 7381a35f2932b9f7bc20367318557ecf1a3530d0

Files: 7381a35f2932b9f7bc20367318557ecf1a3530d0 / lib / serve-blobs.js

1790 bytesRaw
1var pull = require('pull-stream')
2var cat = require('pull-cat')
3var toPull = require('stream-to-pull-stream')
4var ident = require('pull-identify-filetype')
5var mime = require('mime-types')
6var URL = require('url')
7var http = require('http')
8
9module.exports = function (context, cb) {
10 return http.createServer(ServeBlobs(context.sbot)).listen(context.config.blobsPort, cb)
11}
12
13function ServeBlobs (sbot) {
14 return function (req, res, next) {
15 var parsed = URL.parse(req.url, true)
16 var hash = decodeURIComponent(parsed.pathname.slice(1))
17 waitFor(hash, function (_, has) {
18 if (!has) return respond(res, 404, 'File not found')
19 // optional name override
20 if (parsed.query.name) {
21 res.setHeader('Content-Disposition', 'inline; filename=' + encodeURIComponent(parsed.query.name))
22 }
23
24 // serve
25 res.setHeader('Content-Security-Policy', BlobCSP())
26 respondSource(res, sbot.blobs.get(hash), false)
27 })
28 }
29
30 function waitFor (hash, cb) {
31 sbot.blobs.has(hash, function (err, has) {
32 if (err) return cb(err)
33 if (has) {
34 cb(null, has)
35 } else {
36 sbot.blobs.want(hash, cb)
37 }
38 })
39 }
40}
41
42function respondSource (res, source, wrap) {
43 if (wrap) {
44 res.writeHead(200, {'Content-Type': 'text/html'})
45 pull(
46 cat([
47 pull.once('<html><body><script>'),
48 source,
49 pull.once('</script></body></html>')
50 ]),
51 toPull.sink(res)
52 )
53 } else {
54 pull(
55 source,
56 ident(function (type) {
57 if (type) res.writeHead(200, {'Content-Type': mime.lookup(type)})
58 }),
59 toPull.sink(res)
60 )
61 }
62}
63
64function respond (res, status, message) {
65 res.writeHead(status)
66 res.end(message)
67}
68
69function BlobCSP () {
70 return 'default-src none; sandbox'
71}
72

Built with git-ssb-web