git ssb

0+

Matt McKegg / ssb-backlinks



Tree: 4a84a761c29ecd2e1b840ea5d875a5958fe47c24

Files: 4a84a761c29ecd2e1b840ea5d875a5958fe47c24 / emit-links.js

1315 bytesRaw
1var ref = require('ssb-ref')
2var deepEqual = require('deep-equal')
3var extend = require('xtend')
4var matchChannel = /^#[^\s#]+$/
5
6module.exports = emitLinks
7
8function 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
34function isChannel (value) {
35 return typeof value === 'string' && value.length < 30 && matchChannel.test(value)
36}
37
38function 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
47function 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