git ssb

3+

ev / decent



Tree: 26964367b4576851356b5e7a87124ef6c8562dd2

Files: 26964367b4576851356b5e7a87124ef6c8562dd2 / ssb-ws / json-api.js

2438 bytesRaw
1'use strict'
2var ref = require('ssb-ref')
3var Stack = require('stack')
4var BlobsHttp = require('multiblob-http')
5var pull = require('pull-stream')
6var URL = require('url')
7var Emoji = require('emoji-server')
8
9function send(res, obj) {
10 res.writeHead(200, {'Content-Type': 'application/json'})
11 res.end(JSON.stringify(obj, null, 2))
12}
13
14var BoxStream = require('pull-box-stream')
15var zeros = new Buffer(24); zeros.fill(0)
16
17module.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