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