Files: 0ed559744790dca3e81c14bc14db092ea1fc626c / index.js
2093 bytesRaw
1 | const FlumeView = require('flumeview-search') |
2 | const pull = require('pull-stream') |
3 | const Validator = require('is-my-json-valid') |
4 | |
5 | const isBlobMention = Validator(require('./schema/mention')) |
6 | |
7 | const INDEX_VERSION = 2 |
8 | const SEARCH_TERM_MIN = 3 |
9 | |
10 | const imgExtRegEx = /\.(jpg|jpeg|png|gif|bmp|svg)$/i |
11 | const spaceCharRegex = /(-|\.|_|\/|~|\s)/g |
12 | |
13 | module.exports = { |
14 | name: 'meme', |
15 | version: require('./package.json').version, |
16 | manifest: { |
17 | query: 'source', |
18 | search: 'async' |
19 | }, |
20 | init: (sbot) => { |
21 | const view = sbot._flumeUse('meme', FlumeView(INDEX_VERSION, SEARCH_TERM_MIN, map)) |
22 | |
23 | return { |
24 | query: view.query, |
25 | search |
26 | } |
27 | |
28 | function search (opts, cb) { |
29 | if (typeof opts === 'string') opts = { query: opts } |
30 | opts.query = opts.query.toLowerCase() |
31 | |
32 | const validTerms = opts.query |
33 | .split(spaceCharRegex) |
34 | .filter(s => s.length >= SEARCH_TERM_MIN) |
35 | |
36 | pull( |
37 | view.query(opts), |
38 | pull.collect((err, data) => { |
39 | if (err) return cb(err) |
40 | |
41 | const result = data.reduce((soFar, msg) => { |
42 | getMentions(msg) |
43 | .filter(isBlobMention) |
44 | .filter(containsSearchTerms) |
45 | .forEach(({ link, name }) => { |
46 | if (!soFar[link]) soFar[link] = [] |
47 | |
48 | soFar[link].push({ name, author: getAuthor(msg), msg: msg.key }) |
49 | }) |
50 | |
51 | return soFar |
52 | }, {}) |
53 | |
54 | cb(null, result) |
55 | }) |
56 | ) |
57 | |
58 | function containsSearchTerms (mention) { |
59 | const name = mention.name.toLowerCase() |
60 | return validTerms.every(term => name.indexOf(term) > -1) |
61 | } |
62 | } |
63 | } |
64 | } |
65 | |
66 | function map (msg) { |
67 | return getMentions(msg) |
68 | .filter(isBlobMention) |
69 | .map(m => m.name) |
70 | .map(n => n.replace(imgExtRegEx, '').replace(spaceCharRegex, ' ')) |
71 | .join(' ') |
72 | } |
73 | |
74 | function getMentions (msg) { |
75 | if (!msg.value.content.mentions) return [] |
76 | else if (!Array.isArray(msg.value.content.mentions)) return [msg.value.content.mentions] |
77 | else return msg.value.content.mentions |
78 | } |
79 | |
80 | function getAuthor (msg) { |
81 | return msg.value.author |
82 | } |
83 |
Built with git-ssb-web