git ssb

3+

ev / decent



Tree: b5f3c11f9e0e43e79da1e0146bd5f9357360d53c

Files: b5f3c11f9e0e43e79da1e0146bd5f9357360d53c / plugins / ws / json-api.js

1862 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
14module.exports = function (sbot, layers) {
15 var prefix = '/blobs'
16 return Stack(
17 function (req, res, next) {
18 Stack.compose.apply(null, layers)(req, res, next)
19 },
20 Emoji('/img/emoji'),
21 //blobs are served over CORS, so you can get blobs from any pub.
22 function (req, res, next) {
23 res.setHeader('Access-Control-Allow-Origin', '*')
24 res.setHeader("Access-Control-Allow-Headers",
25 "Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since");
26 res.setHeader("Access-Control-Allow-Methods", "GET", "HEAD");
27 next()
28 },
29 function (req, res, next) {
30 var id
31 try { id = decodeURIComponent(req.url.substring(5)) }
32 catch (_) { id = req.url.substring(5) }
33 console.log(req.url, id)
34 if(req.url.substring(0, 5) !== '/msg/' || !ref.isMsg(id)) return next()
35
36 sbot.get(id, function (err, msg) {
37 if(err) return next(err)
38 send(res, {key: id, value: msg})
39 })
40 },
41 function (req, res, next) {
42 if(!(req.method === "GET" || req.method == 'HEAD')) return next()
43
44 var u = URL.parse('http://makeurlparseright.com'+req.url)
45 var hash = decodeURIComponent(u.pathname.substring((prefix+'/get/').length))
46 //check if we don't already have this, tell blobs we want it, if necessary.
47 sbot.blobs.has(hash, function (err, has) {
48 if(has) next()
49 else sbot.blobs.want(hash, function (err, has) { next() })
50 })
51 },
52 BlobsHttp(sbot.blobs, prefix)
53 )
54}
55
56

Built with git-ssb-web