UNPKG

2.5 kBJavaScriptView Raw
1'use strict'
2var ref = require('ssb-ref')
3var Stack = require('stack')
4var BlobsHttp = require('multiblob-http')
5var sort = require('ssb-sort')
6var pull = require('pull-stream')
7var WebBoot = require('web-bootloader/handler')
8var URL = require('url')
9var Emoji = require('emoji-server')
10
11function msgHandler(path, handler) {
12 return function (req, res, next) {
13 console.log(req.method, req.url)
14 if(req.method !== 'GET') return next()
15 if(req.url.indexOf(path) === 0) {
16 var id = req.url.substring(path.length)
17 console.log("MSG?", id)
18 if(!ref.isMsg(id))
19 next(new Error('not a valid message id:'+id))
20 else {
21 req.id = id
22 handler(req, res, next)
23 }
24 }
25 else
26 next()
27 }
28}
29
30function send(res, obj) {
31 res.writeHead(200, {'Content-Type': 'application/json'})
32 res.end(JSON.stringify(obj, null, 2))
33}
34
35module.exports = function (sbot) {
36 var prefix = '/blobs'
37 return Stack(
38 WebBoot,
39 Emoji('/img/emoji'),
40 function (req, res, next) {
41 res.setHeader('Access-Control-Allow-Origin', '*')
42 res.setHeader("Access-Control-Allow-Headers",
43 "Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since");
44 res.setHeader("Access-Control-Allow-Methods", "GET", "HEAD");
45 next()
46 },
47 msgHandler('/msg/', function (req, res, next) {
48 sbot.get(req.id, function (err, msg) {
49 if(err) return next(err)
50 send(res, {key: req.id, value: msg})
51 })
52 }),
53 msgHandler('/thread/', function (req, res, next) {
54 sbot.get(req.id, function (err, value) {
55 if(err) return next(err)
56 var msg = {key: req.id, value: value}
57
58 pull(
59 sbot.links({rel: 'root', dest: req.id, values: true, keys: true}),
60 pull.collect(function (err, ary) {
61 if(err) return next(err)
62 ary.unshift(msg)
63 send(res, sort(ary))
64 })
65 )
66 })
67
68 }),
69 function (req, res, next) {
70 if(!(req.method === "GET" || req.method == 'HEAD')) return next()
71
72 var u = URL.parse('http://makeurlparseright.com'+req.url)
73 var hash = decodeURIComponent(u.pathname.substring((prefix+'/get/').length))
74 //check if we don't already have this, tell blobs we want it, if necessary.
75 sbot.blobs.has(hash, function (err, has) {
76 if(has) next()
77 else sbot.blobs.want(hash, function (err, has) { next() })
78 })
79 },
80 BlobsHttp(sbot.blobs, prefix)
81 )
82}
83
84
85
86
87
88
89