Files: 6c59c792588683040c22962f3e654c84ed584313 / router / async / normalise.js
2108 bytesRaw
1 | const nest = require('depnest') |
2 | const { isBlobLink, isFeed, isMsg, parseLink } = require('ssb-ref') |
3 | const ssbUri = require('ssb-uri') |
4 | |
5 | exports.gives = nest('router.async.normalise') |
6 | |
7 | exports.needs = nest({ |
8 | 'message.sync.unbox': 'first', |
9 | 'sbot.async.get': 'first' |
10 | }) |
11 | |
12 | exports.create = (api) => { |
13 | return nest('router.async.normalise', normalise) |
14 | |
15 | function normalise (location, cb) { |
16 | if (typeof location === 'object') { |
17 | cb(null, location) |
18 | return true |
19 | } |
20 | |
21 | // if someone has given you an annoying html encoded location |
22 | if (location.match(/^%25.*%3D.sha256$/)) { |
23 | location = decodeURIComponent(location) |
24 | } |
25 | |
26 | if (location.startsWith('ssb:')) { |
27 | try { |
28 | location = ssbUri.toSigilLink(location) |
29 | } catch (err) { |
30 | cb(err) |
31 | } |
32 | } |
33 | |
34 | var link = parseLink(location) |
35 | |
36 | if (link && isMsg(link.link)) { |
37 | var params = { id: link.link } |
38 | if (link.query && link.query.unbox) { |
39 | params.private = true |
40 | params.unbox = link.query.unbox |
41 | } |
42 | api.sbot.async.get(params, function (err, value) { |
43 | if (err) cb(err) |
44 | else { |
45 | if (typeof value.content === 'string') value = api.message.sync.unbox(value) |
46 | cb(null, { key: link.link, value }) |
47 | } |
48 | }) |
49 | } else if (isBlobLink(location)) { |
50 | // handles public & private blobs |
51 | // TODO - parse into link and query? |
52 | cb(null, { blob: location }) |
53 | } else if (isChannelMulti(location)) cb(null, { channels: location.split('+') }) |
54 | else if (isChannel(location)) cb(null, { channel: location }) |
55 | else if (isFeed(location)) cb(null, { feed: location }) |
56 | else if (isPage(location)) cb(null, { page: location.substring(1) }) |
57 | |
58 | return true |
59 | } |
60 | } |
61 | |
62 | function isChannelMulti (str) { |
63 | if (typeof str !== 'string') return false |
64 | |
65 | const channels = str.split('+') |
66 | return channels.length > 1 && channels.every(isChannel) |
67 | } |
68 | |
69 | function isChannel (str) { |
70 | return typeof str === 'string' && str[0] === '#' && str.length > 1 |
71 | } |
72 | |
73 | function isPage (str) { |
74 | return typeof str === 'string' && str[0] === '/' && str.length > 1 |
75 | } |
76 |
Built with git-ssb-web