Files: 2d3be0b71fb114fe7815f6d65ae8c25ba8337ae4 / lib / serve-blobs.js
1790 bytesRaw
1 | var pull = require('pull-stream') |
2 | var cat = require('pull-cat') |
3 | var toPull = require('stream-to-pull-stream') |
4 | var ident = require('pull-identify-filetype') |
5 | var mime = require('mime-types') |
6 | var URL = require('url') |
7 | var http = require('http') |
8 | |
9 | module.exports = function (context, cb) { |
10 | return http.createServer(ServeBlobs(context.sbot)).listen(context.config.blobsPort, cb) |
11 | } |
12 | |
13 | function 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 | |
42 | function 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 | |
64 | function respond (res, status, message) { |
65 | res.writeHead(status) |
66 | res.end(message) |
67 | } |
68 | |
69 | function BlobCSP () { |
70 | return 'default-src none; sandbox' |
71 | } |
72 |
Built with git-ssb-web