-
Notifications
You must be signed in to change notification settings - Fork 33
/
filters.ts
98 lines (88 loc) · 3.08 KB
/
filters.ts
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
91
92
93
94
95
96
97
98
import * as yaml from 'js-yaml';
import * as fs from 'fs';
class _TokenFilterRule {
name: string;
type: string;
info: string;
constructor({ name, type, info }: { name: string, type: string, info: string }) {
this.name = name;
this.type = type;
this.info = info;
}
include(tokenId: string) {
if(this.type === 'include-single') {
if(tokenId === this.info) {
return true;
} else {
return false;
}
} else if(this.type === 'exclude-single') {
if(tokenId === this.info) {
return false;
} else {
return true;
}
}
}
exclude(tokenId: string) {
return !this.include(tokenId);
}
}
class _TokenFilter {
public static Instance() {
return this._instance || (this._instance = new _TokenFilter());
}
private static _instance: _TokenFilter;
_rules = new Map<string, _TokenFilterRule>();
_hasIncludeSingle = false;
_hasExcludeSingle = false;
constructor() {
try {
let o = yaml.safeLoad(fs.readFileSync('filters.yml', 'utf-8')) as { tokens: _TokenFilterRule[] };
o!.tokens.forEach((f: _TokenFilterRule) => {
this.addRule(new _TokenFilterRule({ info: f.info, name: f.name, type: f.type }));
console.log("[INFO] Loaded token filter:", f.name);
});
} catch(e) {
console.log("[INFO] No token filters loaded.");
}
}
addRule(rule: _TokenFilterRule) {
if(this._rules.has(rule.info))
return;
if(rule.type === 'include-single') {
if(this._hasExcludeSingle)
throw Error('Invalid combination of filter rules. Filter already has exclude single rules added.');
this._hasIncludeSingle = true;
} else if(rule.type === 'exclude-single') {
if(this._hasIncludeSingle)
throw Error('Invalid combination of filter rules. Filter already has include single rules added.');
this._hasIncludeSingle = true;
}
this._rules.set(rule.info, rule);
}
passesAllFilterRules(tokenId: string) {
if(this._hasIncludeSingle) {
let r = Array.from(this._rules).filter((v, i) => v[1].type === 'include-single');
for(let i = 0; i < r.length; i++) {
if(r[i][1].type === 'include-single' && r[i][1].include(tokenId)) {
return true;
}
}
return false;
} else if(this._hasExcludeSingle) {
let r = Array.from(this._rules).filter((v, i) => v[1].type === 'exclude-single');
for(let i = 0; i < r.length; i++) {
if(r[i][1].type === 'exclude-single' && r[i][1].exclude(tokenId)) {
return false;
}
}
return true;
} else {
return true;
}
}
}
// accessor to a singleton stack for filters
export const TokenFilters = _TokenFilter.Instance;
TokenFilters();