-
Notifications
You must be signed in to change notification settings - Fork 18
/
Condition.ts
328 lines (304 loc) · 14.5 KB
/
Condition.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
/**
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {MessageData} from './ThreadData';
import Utils from './utils';
const RE_FLAG_PATTERN = /^\/(.*)\/([gimuys]*)$/;
enum ConditionType {
AND, OR, NOT, SUBJECT, FROM, TO, CC, BCC, LIST, SENDER, RECEIVER, BODY,
}
/**
* S expression represents condition in rule.
*
* Syntax:
* CONDITION_EXP := (OPERATOR CONDITION_LIST) | (MATCHER STRING)
* OPERATOR := and | or | not
* MATCHER := subject | from | to | cc | bcc | list | sender | receiver | content
* CONDITION_LIST := CONDITION_EXP | CONDITION_EXP CONDITION_LIST
*/
export default class Condition {
private static parseSubConditions(rest_str: string, condition_str: string): Condition[] {
const result = [];
let start = 0, level = 0, length = rest_str.length;
for (let end = 0; end < length; end++) {
switch (rest_str[end]) {
case '(':
level++;
break;
case ')':
level--;
Utils.assert(level >= 0, `Condition ${condition_str} has non-balanced parentheses`);
if (level === 0) {
if (start < end) {
const sub_str = rest_str.substring(start, end + 1).trim();
if (sub_str.length > 0) {
result.push(new Condition(sub_str));
}
}
start = end + 1;
}
break;
}
}
Utils.assert(level === 0, `Condition ${condition_str} has non-balanced parentheses overall.`);
return result;
}
private static escapeRegExp(pattern: string): string {
return pattern.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
private static parseRegExp(pattern: string, condition_str: string, matching_address: boolean): RegExp {
Utils.assert(pattern.length > 0, `Condition ${condition_str} should have value but not found`);
const match = pattern.match(RE_FLAG_PATTERN);
if (match !== null) {
// normal regexp
const [/* ignored */, p, flags] = match;
return new RegExp(p, flags);
} else if (pattern.startsWith('"') && pattern.endsWith('"')) {
// exact matching
return new RegExp(`(^|<)${Condition.escapeRegExp(pattern.substring(1, pattern.length - 1))}($|>)`, 'i');
} else if (matching_address) {
// ignoring label in address
return new RegExp(`(^|<)${Condition.escapeRegExp(pattern).replace('@', '(\\+[^@]+)?@')}($|>)`, 'i');
} else {
// containing matching
return new RegExp(Condition.escapeRegExp(pattern));
}
}
private readonly type: ConditionType;
private readonly regexp: RegExp;
private readonly sub_conditions: Condition[];
constructor(condition_str: string) {
condition_str = condition_str.trim();
Utils.assert(condition_str.startsWith('(') && condition_str.endsWith(')'),
`Condition ${condition_str} should be surrounded by ().`);
const first_space = condition_str.indexOf(" ");
const type_str = condition_str.substring(1, first_space).trim().toUpperCase();
const rest_str = condition_str.substring(first_space + 1, condition_str.length - 1).trim();
this.type = ConditionType[type_str as keyof typeof ConditionType];
switch (this.type) {
case ConditionType.AND:
case ConditionType.OR: {
this.sub_conditions = Condition.parseSubConditions(rest_str, condition_str);
break;
}
case ConditionType.NOT: {
this.sub_conditions = Condition.parseSubConditions(rest_str, condition_str);
if (this.sub_conditions.length !== 1) {
throw `Conditions of type ${type_str} must have exactly one sub-condition, but found ${this.sub_conditions.length}: ${rest_str}`;
}
break;
}
case ConditionType.FROM:
case ConditionType.TO:
case ConditionType.CC:
case ConditionType.BCC:
case ConditionType.LIST:
case ConditionType.SENDER:
case ConditionType.RECEIVER: {
this.regexp = Condition.parseRegExp(rest_str, condition_str, true);
break;
}
case ConditionType.SUBJECT:
case ConditionType.BODY: {
this.regexp = Condition.parseRegExp(rest_str, condition_str, false);
break;
}
default:
throw `Unexpected condition type ${type_str} from ${condition_str}.`;
}
}
match(message_data: MessageData): boolean {
switch (this.type) {
case ConditionType.AND: {
for (const sub_condition of this.sub_conditions) {
if (!sub_condition.match(message_data)) {
return false;
}
}
return true;
}
case ConditionType.OR: {
for (const sub_condition of this.sub_conditions) {
if (sub_condition.match(message_data)) {
return true;
}
}
return false;
}
case ConditionType.NOT: {
return !this.sub_conditions[0].match(message_data);
}
case ConditionType.FROM: {
return this.matchAddress(message_data.from);
}
case ConditionType.TO: {
return this.matchAddress(...message_data.to);
}
case ConditionType.CC: {
return this.matchAddress(...message_data.cc);
}
case ConditionType.BCC: {
return this.matchAddress(...message_data.bcc);
}
case ConditionType.LIST: {
return this.matchAddress(message_data.list);
}
case ConditionType.SENDER: {
return this.matchAddress(message_data.from);
}
case ConditionType.RECEIVER: {
return this.matchAddress(...message_data.receivers);
}
case ConditionType.SUBJECT: {
return this.regexp.test(message_data.subject);
}
case ConditionType.BODY: {
return this.regexp.test(message_data.body);
}
}
}
private matchAddress(...addresses: string[]) {
return addresses.some(address => this.regexp.test(address));
}
toString(): string {
const type_str = ConditionType[this.type];
const regexp_str = this.regexp ? this.regexp.source : "";
const sub_str = this.sub_conditions ? "\n" + this.sub_conditions.map(c => c.toString()).join("\n") : "";
return `(${type_str} ${regexp_str} ${sub_str})`;
}
public static testRegex(it: Function, expect: Function) {
function test_regexp(condition_str: string, target_str: string, is_address: boolean) {
const regexp = Condition.parseRegExp(condition_str, "", is_address);
return regexp.test(target_str);
}
// Matching address ignoring labels
it('Matches address', () =>
expect(test_regexp('some-mailing-list@gmail.com', 'some-mailing-list@gmail.com', true)).toBe(true))
it('Does not match address with prefix', () =>
expect(test_regexp('some-mailing-list@gmail.com', 'prefix-some-mailing-list@gmail.com', true)).toBe(false))
it('Does not match address with suffix', () =>
expect(test_regexp('some-mailing-list@gmail.com', 'some-mailing-list-suffix@gmail.com', true)).toBe(false))
it('Matches address, ignoring labels', () =>
expect(test_regexp('some-mailing-list@gmail.com', 'some-mailing-list+tag1@gmail.com', true)).toBe(true))
// Matching address with name
it('Matches address surrounded by <>', () =>
expect(test_regexp('abc@gmail.com', '<abc@gmail.com>', true)).toBe(true))
it('Matches address surrounded by <>, ignoring labels', () =>
expect(test_regexp('abc@gmail.com', '<abc+dd@gmail.com>', true)).toBe(true))
it('Matches address surrounded by <>, ignoring name prefix', () =>
expect(test_regexp('abc@gmail.com', 'dd <abc+dd@gmail.com>', true)).toBe(true))
// If label is specified, then it's required
it('Does not match if missing label', () =>
expect(test_regexp('some-mailing-list+tag1@gmail.com', 'some-mailing-list@gmail.com', true)).toBe(false))
it('Matches address with label', () =>
expect(test_regexp('some-mailing-list+tag1@gmail.com', 'some-mailing-list+tag1@gmail.com', true)).toBe(true))
it('Does not match address with incorrect label', () =>
expect(test_regexp('some-mailing-list+tag1@gmail.com', 'some-mailing-list+tag2@gmail.com', true)).toBe(false))
// Exact matching
it('Matches exact address (using quotes)', () =>
expect(test_regexp('"some-mailing-list@gmail.com"', 'some-mailing-list@gmail.com', true)).toBe(true))
it('Does not match exact address (using quotes) with prefix', () =>
expect(test_regexp('"some-mailing-list@gmail.com"', 'prefix-some-mailing-list@gmail.com', true)).toBe(false))
it('Does not match exact address (using quotes) with suffix', () =>
expect(test_regexp('"some-mailing-list@gmail.com"', 'some-mailing-list-suffix@gmail.com', true)).toBe(false))
it('Does not match exact address (using quotes) with label', () =>
expect(test_regexp('"some-mailing-list@gmail.com"', 'some-mailing-list+tag1@gmail.com', true)).toBe(false))
// Exact matching with tag
it('Does not match exact address (using quotes) with label', () =>
expect(test_regexp('"some-mailing-list+tag1@gmail.com"', 'some-mailing-list@gmail.com', true)).toBe(false))
it('Matches exact address (using quotes) with label', () =>
expect(test_regexp('"some-mailing-list+tag1@gmail.com"', 'some-mailing-list+tag1@gmail.com', true)).toBe(true))
it('Does not match exact address (using quotes) with incorrect label', () =>
expect(test_regexp('"some-mailing-list+tag1@gmail.com"', 'some-mailing-list+tag2@gmail.com', true)).toBe(false))
// Matches are case-insensitive
it('Matches address with different case', () =>
expect(test_regexp('abc+Def@gmail.com', 'abc+def@gmail.com', true)).toBe(true))
it('Matches exact address with different case', () =>
expect(test_regexp('"abc+Def@gmail.com"', 'abc+def@gmail.com', true)).toBe(true))
// Regexp matching
it('Matches address using regexp', () =>
expect(test_regexp('/some-.*@gmail.com/', 'some-mailing-list@gmail.com', true)).toBe(true))
it('Matches address using regexp with label', () =>
expect(test_regexp('/some-.*@gmail.com/', 'some-mailing-list+tag@gmail.com', true)).toBe(true))
it('Does not match address using regexp', () =>
expect(test_regexp('/some-.*@gmail.com/', 'some2-mailing-list@gmail.com', true)).toBe(false))
it('Matches address using regexp and case insensitive', () =>
expect(test_regexp('/feedback access request/i', 'Feedback access request', false)).toBe(true))
it('Matches content using regexp, case-insensitive and DOTALL', () =>
expect(test_regexp('/abc.def/si', 'Abc\nDef', false)).toBe(true))
}
public static testConditionParsing(it: Function, expect: Function) {
const base_message = {
getFrom: () => '',
getTo: () => '',
getCc: () => '',
getBcc: () => '',
getReplyTo: () => '',
getSubject: () => '',
getPlainBody: () => '',
getRawContent: () => '',
} as GoogleAppsScript.Gmail.GmailMessage;
function test_cond(condition_str: string, message: Partial<GoogleAppsScript.Gmail.GmailMessage>): boolean {
const condition = new Condition(condition_str);
const message_data = new MessageData(Object.assign({}, base_message, message));
return condition.match(message_data);
}
it('Matches nested and/or conditions', () => {
expect(test_cond(`(and
(from abc@gmail.com)
(or
(receiver ijl@gmail.com)
(receiver xyz@gmail.com)))`,
{
getFrom: () => 'dd <abc+dd@gmail.com>',
getTo: () => 'something+-random@gmail.com',
getCc: () => 'xyz+tag@gmail.com',
})).toBe(true)
})
it('Matches multiple TO: entries', () => {
expect(test_cond(`(or
(receiver abc@gmail.com)
(receiver abc@corp.com))`,
{
getFrom: () => 'DDD EEE <def@corp.com>',
getTo: () => 'AAA BBB <abc@corp.com>, DDD EEE <def@corp.com>',
})).toBe(true)
})
it('Does not match when using negation', () => {
expect(test_cond(`(not (receiver abc@gmail.com))`,
{
getTo: () => 'AAA BBB <abc@gmail.com>',
})).toBe(false)
})
it('Matches when using negation', () => {
expect(test_cond(`(not (receiver abc@gmail.com))`,
{
getTo: () => 'AAA BBB <def@gmail.com>',
})).toBe(true)
})
it('Matches receiver to TO: address with label', () => {
expect(test_cond(`(receiver abc+Def@bar.com)`,
{
getTo: () => 'abc+Def@bar.com',
})).toBe(true)
})
it('Matches receiver exactly (using quotes) to TO: address with label', () => {
expect(test_cond(`(receiver "abc+Def@bar.com")`,
{
getTo: () => 'abc+Def@bar.com',
})).toBe(true)
})
}
}