Files: b4c65fe0668bf7f8c17503206a51cbb417ee9727 / mentions.js
2498 bytesRaw
1 | var mentions = require('ssb-mentions') |
2 | |
3 | /* |
4 | when javascript is turned off we can't use auto predict. |
5 | this method lets you just enter the names as raw mentions, |
6 | @{name} and then looks up the names you might use. |
7 | * if it's unambigious it uses that key. |
8 | * if there is more than one with that name, but only |
9 | one that you call that name (other peers can use the same name) |
10 | then it chooses the one you use. |
11 | * if there are more than one feed you call that name, |
12 | make a dropdown select which one you will mention. |
13 | |
14 | */ |
15 | |
16 | function simpleAt (text) { |
17 | var rx = /(?:^|\s)(@[\w\-_\d\!]+)/g |
18 | var a = [] |
19 | var match = rx.exec(text) |
20 | while(match) { |
21 | a.push({name:match[1].substring(1), link: false}) |
22 | match = rx.exec(text) |
23 | } |
24 | return a |
25 | |
26 | } |
27 | |
28 | function _mentions (text, cb) { |
29 | var m = mentions(text) |
30 | simpleAt(text).forEach(function (e) { |
31 | for(var i = 0; i < m.length; i++) |
32 | if(m[i].name == e.name) return |
33 | m.push(e) |
34 | }) |
35 | return m |
36 | } |
37 | |
38 | function lookup (sbot, name, cb) { |
39 | var mention = {name: name, link: null} |
40 | sbot.names.getSignifies(name, function (err, names) { |
41 | if(names && names.length) { |
42 | names = names.filter(function (e) { |
43 | return e.name == name |
44 | }) |
45 | var first = names[0] |
46 | names = names.filter(function (e, i) { |
47 | return !i || first.id !== e.id |
48 | }) |
49 | if(names.length) { |
50 | var _names = names.filter(function (e) { |
51 | return e.named === name |
52 | }) |
53 | if(_names.length === 1) |
54 | return cb(null, _names[0].id) |
55 | } |
56 | if(names.length === 1) |
57 | cb(null, first.id) |
58 | else |
59 | cb(null, null, names) |
60 | } |
61 | }) |
62 | } |
63 | |
64 | module.exports = function (sbot, text, cb) { |
65 | var m = _mentions(text), n = 1, ambigious = [] |
66 | m.forEach(function (mention, i) { |
67 | if(mention.name && mention.link === false) { |
68 | n++ |
69 | lookup(sbot, mention.name, function (err, link, names) { |
70 | if(err) return next(err) |
71 | |
72 | if(link) mention.link = link |
73 | else ambigious.push(names) |
74 | |
75 | next() |
76 | }) |
77 | } |
78 | }) |
79 | |
80 | next() |
81 | |
82 | function next (err) { |
83 | if(n>=0 && err) { |
84 | n = -1 |
85 | cb(err) |
86 | } |
87 | if(--n) return |
88 | cb(null, m, ambigious) |
89 | } |
90 | } |
91 | |
92 | if(!module.parent) |
93 | require('ssb-client')(function (err, sbot) { |
94 | if(err) throw err |
95 | module.exports(sbot, process.argv[2], function (err, data, ambigious) { |
96 | if(err) throw err |
97 | console.log(JSON.stringify(data, null, 2)) |
98 | console.log(JSON.stringify(ambigious, null, 2)) |
99 | sbot.close() |
100 | }) |
101 | }) |
102 | |
103 | |
104 |
Built with git-ssb-web