Files: 4a84a761c29ecd2e1b840ea5d875a5958fe47c24 / emit-links.js
1315 bytesRaw
1 | var ref = require('ssb-ref') |
2 | var deepEqual = require('deep-equal') |
3 | var extend = require('xtend') |
4 | var matchChannel = /^#[^\s#]+$/ |
5 | |
6 | module.exports = emitLinks |
7 | |
8 | function emitLinks (msg, emit) { |
9 | var links = new Set() |
10 | walk(msg.value.content, function (path, value) { |
11 | // HACK: handle legacy channel mentions |
12 | if (deepEqual(path, ['channel'])) { |
13 | var channel = ref.normalizeChannel(value) |
14 | if (channel) { |
15 | value = `#${channel}` |
16 | } |
17 | } |
18 | |
19 | // TODO: should add channel matching to ref.type |
20 | if (ref.type(value)) { |
21 | links.add(value) |
22 | } else if (isChannel(value)) { |
23 | links.add(`#${ref.normalizeChannel(value.slice(1))}`) |
24 | } |
25 | }) |
26 | links.forEach(link => { |
27 | emit(extend(msg, { |
28 | rts: resolveTimestamp(msg), |
29 | dest: link |
30 | })) |
31 | }) |
32 | } |
33 | |
34 | function isChannel (value) { |
35 | return typeof value === 'string' && value.length < 30 && matchChannel.test(value) |
36 | } |
37 | |
38 | function resolveTimestamp (msg) { |
39 | if (!msg || !msg.value || !msg.value.timestamp) return |
40 | if (msg.timestamp) { |
41 | return Math.min(msg.timestamp, msg.value.timestamp) |
42 | } else { |
43 | return msg.value.timestamp |
44 | } |
45 | } |
46 | |
47 | function walk (obj, fn, prefix) { |
48 | if (obj && typeof obj === 'object') { |
49 | for (var k in obj) { |
50 | walk(obj[k], fn, (prefix || []).concat(k)) |
51 | } |
52 | } else { |
53 | fn(prefix, obj) |
54 | } |
55 | } |
56 |
Built with git-ssb-web