1 | 'use strict'
|
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 | module.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 |
|
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 |
|
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 |
|