Files: cd6daeeaa3add9754505f6f331965f4de2e98a72 / ssb-ws / json-api.js
2438 bytesRaw
1 | |
2 | var ref = require('ssb-ref') |
3 | var Stack = require('stack') |
4 | var BlobsHttp = require('multiblob-http') |
5 | var pull = require('pull-stream') |
6 | var URL = require('url') |
7 | var Emoji = require('emoji-server') |
8 | |
9 | function send(res, obj) { |
10 | res.writeHead(200, {'Content-Type': 'application/json'}) |
11 | res.end(JSON.stringify(obj, null, 2)) |
12 | } |
13 | |
14 | var BoxStream = require('pull-box-stream') |
15 | var zeros = new Buffer(24); zeros.fill(0) |
16 | |
17 | module.exports = function (sbot, layers) { |
18 | var prefix = '/blobs' |
19 | return Stack( |
20 | function (req, res, next) { |
21 | Stack.compose.apply(null, layers)(req, res, next) |
22 | }, |
23 | Emoji('/img/emoji'), |
24 | //blobs are served over CORS, so you can get blobs from any pub. |
25 | /*function (req, res, next) { |
26 | res.setHeader('Access-Control-Allow-Origin', '*') |
27 | res.setHeader("Access-Control-Allow-Headers", |
28 | "Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since"); |
29 | res.setHeader("Access-Control-Allow-Methods", "GET", "HEAD"); |
30 | next() |
31 | },*/ |
32 | function (req, res, next) { |
33 | var id |
34 | try { id = decodeURIComponent(req.url.substring(5)) } |
35 | catch (_) { id = req.url.substring(5) } |
36 | if(req.url.substring(0, 5) !== '/msg/' || !ref.isMsg(id)) return next() |
37 | |
38 | sbot.get(id, function (err, msg) { |
39 | if(err) return next(err) |
40 | send(res, {key: id, value: msg}) |
41 | }) |
42 | }, |
43 | function (req, res, next) { |
44 | if(!(req.method === "GET" || req.method == 'HEAD')) return next() |
45 | |
46 | var u = URL.parse('http://makeurlparseright.com'+req.url) |
47 | var hash = decodeURIComponent(u.pathname.substring((prefix+'/get/').length)) |
48 | //check if we don't already have this, tell blobs we want it, if necessary. |
49 | sbot.blobs.has(hash, function (err, has) { |
50 | if(has) next() |
51 | else sbot.blobs.want(hash, function (err, has) { next() }) |
52 | }) |
53 | }, |
54 | BlobsHttp(sbot.blobs, prefix, {size: false, transform: function (q) { |
55 | if(q.unbox && /\.boxs$/.test(q.unbox)) { |
56 | var key = new Buffer(q.unbox.replace(/\s/g, '+'), 'base64') |
57 | if(key.length !== 32) |
58 | return function (read) { |
59 | return function (abort, cb) { |
60 | read(new Error('key must be 32 bytes long'), cb) |
61 | } |
62 | } |
63 | return BoxStream.createUnboxStream( |
64 | new Buffer(key, 'base64'), |
65 | zeros |
66 | ) |
67 | } |
68 | return pull.through() |
69 | }}) |
70 | ) |
71 | } |
72 | |
73 | |
74 | |
75 | |
76 | |
77 | |
78 |
Built with git-ssb-web