-
Notifications
You must be signed in to change notification settings - Fork 4
/
helpers.mjs
90 lines (76 loc) · 2.76 KB
/
helpers.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import TurndownService from 'turndown';
const turndownService = new TurndownService();
export const functional = {
/**
* The identity function
* @see handleMessages()
* @param a Anything
* @return @p a
*/
id(a) { return a; },
/**
* Maybe monad composition for unary functions
* If @p f or @p g or f(x) return a falsy value, it will propagate through
* @param f Outer (later, 2nd) function
* @param g Inner (earlier, 1st) function
* @return New function that composes @p f and @p g, unless @p f, @p g, or the intermediary result is falsy (it returns undefined, i.e. Nothing)
*/
maybeCompose( f, g ) {
return x => {
if( !f || !g ) return undefined;
const y = g( x );
if( !y ) return undefined;
else return f( x );
};
},
};
export const helpers = {
/**
* A transformer that converts received HTML into markdown.
* @param m Message object
* @return Message object with markdown body
*/
reduceHtml(m) {
const mp = m;
const unescapeHtml = unsafe => {
return unsafe
.replace( /&/g, `&` )
.replace( /</g, `<` )
.replace( />/g, `>` )
.replace( /"/g, `"` )
.replace( /'/g, `'` );
};
// <p></p>
mp.message = mp.message.replace( /<\/?p[\w =#"':\/\\.\-?]*>/gi, "" );
// <a>gets left</a>
// Custom links are text in <a>, and then the link in <kbd>
mp.message = mp.message.replace( /<\/?a[\w -=#"':\/\\.\-?]*>/gi, "" );
mp.message = mp.message.replace( "<kbd>", "" );
mp.message = mp.message.replace( "</kbd>", "" );
// <img> to :emotes:
mp.message = mp.message.replace( /<img[\w -=#"':\/\\.\-?]*>/gi, m => {
// (((, ))), :), :( are rendered differently
// (They dont even show up in the emote list)
//
// It wouldn't be so bad if the two echos were 'echol' and 'echor', but
// one echo is flipped with CSS.
if( m.includes('alt="echo"') ) {
return m.includes('scaleX(-1)') ? "(((" : ")))";
}
return m.match( /alt="([\w:()]+)"/ )[1];
});
mp.message = turndownService.turndown( mp.message );
mp.message = mp.message.replace( /\\\\\\/gi, "" );
return mp;
},
/**
* Filter that checks message visibility.
* Uses global config room and global.
* @see config
* @param m Message object
* @return The message object if it is visible, undefined otherwise
*/
roomCheck( m, config ) {
return ( m.channel !== config.room && !config.global ) ? undefined : m;
},
};