Files: e0439586cabe63fc84e88ff400edb18470cdec52 / message / async / name.js
2166 bytesRaw
1 | const nest = require('depnest') |
2 | const ref = require('ssb-ref') |
3 | const {resolve, onceTrue} = require('mutant') |
4 | |
5 | exports.needs = nest({ |
6 | 'sbot.async.get': 'first', |
7 | 'sbot.pull.links': 'first', |
8 | 'message.sync.unbox': 'first', |
9 | 'about.obs.socialValue': 'first', |
10 | 'keys.sync.id': 'first' |
11 | }) |
12 | exports.gives = nest('message.async.name') |
13 | |
14 | // needs an async version |
15 | |
16 | exports.create = function (api) { |
17 | return nest('message.async.name', function (id, cb) { |
18 | if (!ref.isLink(id)) throw new Error('an id must be specified') |
19 | var fallbackName = id.substring(0, 10) + '...' |
20 | api.sbot.async.get(id, function (err, value) { |
21 | if (value && typeof value.content === 'string') { |
22 | value = api.message.sync.unbox(value) |
23 | } |
24 | |
25 | if (err && err.name === 'NotFoundError') { |
26 | return cb(null, fallbackName + '...(missing)') |
27 | } else if (value && typeof value.content.title === 'string') { |
28 | return cb(null, truncate(value.content.title, 40)) |
29 | } else if (value && value.content.type === 'post' && typeof value.content.text === 'string') { |
30 | if (value.content.text.trim()) { |
31 | return cb(null, titleFromMarkdown(value.content.text, 40) || fallbackName) |
32 | } |
33 | } else if (value && typeof value.content.text === 'string') { |
34 | return cb(null, value.content.type + ': ' + titleFromMarkdown(value.content.text, 30)) |
35 | } else { |
36 | return getAboutName(id, cb) |
37 | } |
38 | |
39 | return cb(null, fallbackName) |
40 | }) |
41 | }) |
42 | |
43 | function getAboutName (id, cb) { |
44 | var name = api.about.obs.socialValue(id, 'name') |
45 | var title = api.about.obs.socialValue(id, 'title') |
46 | |
47 | onceTrue(name.sync, () => { |
48 | cb(null, resolve(name) || resolve(title) || id.substring(0, 10) + '...') |
49 | }) |
50 | } |
51 | } |
52 | |
53 | function titleFromMarkdown (text, max) { |
54 | text = text.trim().split('\n', 3).join('\n') |
55 | text = text.replace(/_|`|\*|#|^\[@.*?]|\[|]|\(\S*?\)/g, '').trim() |
56 | text = text.replace(/:$/, '') |
57 | text = text.trim().split('\n', 1)[0].trim() |
58 | text = truncate(text, max) |
59 | return text |
60 | } |
61 | |
62 | function truncate (text, maxLength) { |
63 | if (text.length > maxLength) { |
64 | text = text.substring(0, maxLength - 2) + '...' |
65 | } |
66 | return text |
67 | } |
68 |
Built with git-ssb-web