-
Notifications
You must be signed in to change notification settings - Fork 2
/
address.py
270 lines (215 loc) · 8.02 KB
/
address.py
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
import re
import logging
import functools
from collections import namedtuple
from emailtunnel import InvalidRecipient
import tkmail.database
from tkmail.config import ADMINS
import tktitler as tk
GroupAliasBase = namedtuple("GroupAlias", "name")
PeriodAliasBase = namedtuple("PeriodAlias", "kind period name")
DirectAliasBase = namedtuple("DirectAlias", "pk name")
BEST = 'CERM FORM INKA KASS NF PR SEKR VC'.split()
class GroupAlias(GroupAliasBase):
def __str__(self):
return self.name
class PeriodAlias(PeriodAliasBase):
def __str__(self):
return '%s%s' % (self.kind, self.period)
class DirectAlias(DirectAliasBase):
def __str__(self):
return 'DIRECTUSER%s' % self.pk
def get_current_period(db=None):
if db is None:
db = tkmail.database.Database()
try:
old_value = get_current_period.cached_value
get_current_period.cached_value = db.get_current_period()
except Exception:
logging.exception(
"Failed to get current period from database, " +
"reusing cached value %r", get_current_period.cached_value)
else:
if get_current_period.cached_value != old_value:
if old_value is not None:
logging.info("Current period changed from %r to %r",
old_value, get_current_period.cached_value)
return get_current_period.cached_value
get_current_period.cached_value = None
def get_admin_emails():
"""Resolve the group "admin" or fallback if the database is unavailable.
The default set of admins is set in the tkmail.database module.
"""
email_addresses = []
try:
db = tkmail.database.Database()
email_addresses = db.get_admin_emails()
except:
pass
if not email_addresses:
email_addresses = list(ADMINS)
return email_addresses
def translate_recipient(year, name, list_ids=False):
"""Translate recipient `name` in GF year `year`.
>>> translate_recipient(2010, "K3FORM")
["mathiasrav@gmail.com"]
>>> translate_recipient(2010, "GFORM14")
["mathiasrav@gmail.com"]
>>> translate_recipient(2010, "BEST2013")
["mathiasrav@gmail.com", ...]
>>> translate_recipient(2006, 'FUAA')
['sidse...']
>>> translate_recipient(2011, 'FUIØ')
['...@post.au.dk']
>>> translate_recipient(2011, 'FUIOE')
['...@post.au.dk']
"""
name = name.replace('$', 'S') # KA$$ -> KASS hack
db = tkmail.database.Database()
recipient_ids, origin = parse_recipient(name.upper(), db, year)
assert isinstance(recipient_ids, list) and isinstance(origin, list)
assert len(recipient_ids) == len(origin)
email_addresses = db.get_email_addresses(recipient_ids)
if list_ids:
return email_addresses, dict(zip(email_addresses, origin))
else:
return email_addresses
def parse_recipient(recipient, db, current_period):
"""
Evaluate each address which is divided by + and -.
Collects the resulting sets of not matched and the set of spam addresses.
And return the set of person indexes that are to receive the email.
"""
personIdOps = []
invalid_recipients = []
for sign, name in re.findall(r'([+-]?)([^+-]+)', recipient):
try:
personIds, source = parse_alias(name, db, current_period)
personIdOps.append((sign or '+', personIds, source))
except InvalidRecipient as e:
invalid_recipients.append(e.args[0])
if invalid_recipients:
raise InvalidRecipient(invalid_recipients)
recipient_ids = set()
origin = {}
for sign, personIds, source in personIdOps:
if sign == '+': # union
recipient_ids = recipient_ids.union(personIds)
for p in personIds:
origin[p] = source
else: # minus
recipient_ids = recipient_ids.difference(personIds)
for p in personIds:
origin.pop(p, None)
recipient_ids = sorted(recipient_ids)
if not recipient_ids:
raise InvalidRecipient(recipient)
return recipient_ids, [origin[r] for r in recipient_ids]
def parse_alias_group(alias, db, current_period):
groups = db.get_groups()
matches = []
for groupId, name, groupRegexp in groups:
groupId = int(groupId)
regexp = '^(?P<name>%s)$' % groupRegexp
mo = re.match(regexp, alias)
if mo:
# We cannot use a lambda that closes over groupId
# since the captured groupId would change in the next iteration.
matches.append(
(functools.partial(db.get_group_members, groupId),
GroupAlias(name)))
if len(matches) > 1:
raise ValueError("The alias %r matches more than one group"
% alias)
if matches:
return matches[0]
return None, None
def parse_alias_title(alias, db, current_period):
try:
base, period = tk.parse(alias, current_period)
except ValueError:
return None, None
if base == 'BESTFU':
def f():
return (db.get_bestfu_members('BEST', period) +
db.get_bestfu_members('FU', period))
elif base in ('BEST', 'FU'):
def f():
return db.get_bestfu_members(base, period)
elif base in BEST or re.match(r'^E?FU\w+$', base):
def f():
return db.get_user_by_title(base, period)
else:
return None, None
return f, PeriodAlias('BESTFU', period, alias)
def parse_alias_direct_user(alias, db, current_period):
mo = re.match(r'^DIRECTUSER(\d+)$', alias)
if mo is not None:
pk = int(mo.group(1))
return (lambda: db.get_user_by_id(pk)), DirectAlias(pk, alias)
return None, None
def parse_alias(alias, db, current_period):
"""
Evaluates the alias, returning a non-empty list of person IDs.
Raise exception if a spam or no match email.
"""
# Try these functions until one matches
matchers = [
parse_alias_group,
parse_alias_title,
parse_alias_direct_user,
]
for f in matchers:
match, canonical = f(alias, db, current_period)
if match is not None:
break
else:
raise InvalidRecipient(alias)
# Perform database lookup according to matched alias
person_ids = match()
if not person_ids:
# No users in the database fit the matched alias
raise InvalidRecipient(alias)
return person_ids, canonical
def get_period(prefix, postfix, current_period):
"""
current_period is the year where the current BEST was elected.
Assumes current_period <= 2056.
Returns the corresponding period of prefix, postfix and current_period.
(Calculates as the person have the prefix in year postfix)
"""
if not postfix:
period = current_period
else:
if len(postfix) == 4:
first, second = int(postfix[0:2]), int(postfix[2:4])
# Note that postfix 1920, 2021 and 2122 are technically ambiguous,
# but luckily there was no BEST in 1920 and this script hopefully
# won't live until the year 2122, so they are not actually
# ambiguous.
if (first + 1) % 100 == second:
# There should be exactly one year between the two numbers
if first > 56:
period = 1900 + first
else:
period = 2000 + first
elif first in (19, 20):
# 19xx or 20xx
period = int(postfix)
else:
raise InvalidRecipient(postfix)
elif len(postfix) == 2:
year = int(postfix[0:2])
if year > 56: # 19??
period = 1900 + year
else: # 20??
period = 2000 + year
else:
raise InvalidRecipient(postfix)
# Now evaluate the prefix:
prefix_value = dict(K=-1, G=1, B=2, O=3, T=1)
grad = 0
for base, exponent in re.findall(r"([KGBOT])([0-9]*)", prefix):
exponent = int(exponent or 1)
grad += prefix_value[base] * exponent
return period - grad