-
Notifications
You must be signed in to change notification settings - Fork 13
/
notifications.py
493 lines (404 loc) · 21.6 KB
/
notifications.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
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
"""Functions for user notifications."""
__copyright__ = 'Copyright (c) 2021-2024, Utrecht University'
__license__ = 'GPLv3, see LICENSE'
import json
import random
import string
import time
import urllib.parse
from datetime import datetime, timedelta
from typing import List, Tuple
import genquery
from dateutil import relativedelta
from genquery import Query
import data_access_token
import folder
import mail
import meta
import settings
from util import *
__all__ = ['api_notifications_load',
'api_notifications_dismiss',
'api_notifications_dismiss_all',
'rule_mail_notification_report',
'rule_process_ending_retention_packages',
'rule_process_groups_expiration_date',
'rule_process_inactive_research_groups',
'rule_process_data_access_token_expiry']
NOTIFICATION_KEY = constants.UUORGMETADATAPREFIX + "notification"
def generate_random_id(ctx: rule.Context) -> str:
"""Generate random ID for notification."""
characters = string.ascii_lowercase + string.digits
return ''.join(random.choice(characters) for x in range(10))
def set(ctx: rule.Context, actor: str, receiver: str, target: str, message: str) -> None:
"""Set user notification and send mail notification when configured.
:param ctx: Combined type of a callback and rei struct
:param actor: Actor of notification message
:param receiver: Receiving user of notification message
:param target: Target path of the notification
:param message: Notification message for user
"""
if user.exists(ctx, receiver):
identifier = generate_random_id(ctx)
timestamp = int(time.time())
notification = {"identifier": identifier, "timestamp": timestamp, "actor": actor, "target": target, "message": message}
ctx.uuUserModify(receiver, "{}_{}".format(NOTIFICATION_KEY, identifier), json.dumps(notification), '', '')
# Send mail notification if immediate notifications are on.
receiver = user.from_str(ctx, receiver)[0]
mail_notifications = settings.load(ctx, 'mail_notifications', username=receiver)
if mail_notifications == "IMMEDIATE":
send_notification(ctx, receiver, actor, message)
@api.make()
def api_notifications_load(ctx: rule.Context, sort_order: str = "desc") -> List:
"""Load user notifications.
:param ctx: Combined type of a callback and rei struct
:param sort_order: Sort order of notifications on timestamp ("asc" or "desc", default "desc")
:returns: List with all notifications
"""
results = [v for v
in Query(ctx, "META_USER_ATTR_VALUE",
"USER_NAME = '{}' AND USER_TYPE != 'rodsgroup' AND META_USER_ATTR_NAME like '{}_%%'".format(user.name(ctx), NOTIFICATION_KEY))]
notifications = []
for result in results:
try:
notification = jsonutil.parse(result)
notification["datetime"] = (datetime.fromtimestamp(notification["timestamp"])).strftime('%Y-%m-%d %H:%M')
notification["actor"] = user.from_str(ctx, notification["actor"])[0]
# Get data package and link from target path for research and vault packages.
space, _, group, subpath = pathutil.info(notification["target"])
if space is pathutil.Space.RESEARCH:
notification["data_package"] = group if subpath == '' else pathutil.basename(subpath)
notification["link"] = "/research/browse?dir=" + urllib.parse.quote(f"/{group}/{subpath}")
elif space is pathutil.Space.VAULT:
notification["data_package"] = group if subpath == '' else pathutil.basename(subpath)
notification["link"] = "/vault/browse?dir=" + urllib.parse.quote(f"/{group}/{subpath}")
# Deposit situation required different information to be presented.
if subpath.startswith('deposit-'):
data_package_reference = ""
iter = genquery.row_iterator(
"META_COLL_ATTR_VALUE",
"COLL_NAME = '{}' AND META_COLL_ATTR_NAME = '{}'".format(notification["target"], constants.DATA_PACKAGE_REFERENCE),
genquery.AS_LIST, ctx
)
for row in iter:
data_package_reference = row[0]
deposit_title = '(no title)'
iter = genquery.row_iterator(
"META_COLL_ATTR_VALUE",
"COLL_NAME = '{}' AND META_COLL_ATTR_NAME = 'Title'".format(notification["target"]),
genquery.AS_LIST, ctx
)
for row in iter:
deposit_title = row[0]
notification["data_package"] = deposit_title
notification["link"] = "/vault/yoda/{}".format(data_package_reference)
# Find real actor when
if notification["actor"] == 'system':
# Get actor from action log on action = "submitted for vault"
iter2 = genquery.row_iterator(
"order_desc(META_COLL_MODIFY_TIME), META_COLL_ATTR_VALUE",
"COLL_NAME = '" + notification["target"] + "' AND META_COLL_ATTR_NAME = '" + constants.UUORGMETADATAPREFIX + 'action_log' + "'",
genquery.AS_LIST, ctx
)
for row2 in iter2:
# row2 contains json encoded [str(int(time.time())), action, actor]
log_item_list = jsonutil.parse(row2[1])
if log_item_list[1] == "submitted for vault":
notification["actor"] = log_item_list[2].split('#')[0]
break
elif notification["target"] != "":
notification["link"] = notification["target"]
notifications.append(notification)
except Exception:
continue
# Return notifications sorted on timestamp
if sort_order == "asc":
return sorted(notifications, key=lambda k: k['timestamp'], reverse=False)
else:
return sorted(notifications, key=lambda k: k['timestamp'], reverse=True)
@api.make()
def api_notifications_dismiss(ctx: rule.Context, identifier: str) -> api.Result:
"""Dismiss user notification.
:param ctx: Combined type of a callback and rei struct
:param identifier: Identifier of notification message
"""
key = "{}_{}".format(NOTIFICATION_KEY, str(identifier))
user_name = user.full_name(ctx)
ctx.uuUserMetaRemove(user_name, key, '', '')
@api.make()
def api_notifications_dismiss_all(ctx: rule.Context) -> api.Result:
"""Dismiss all user notifications.
:param ctx: Combined type of a callback and rei struct
"""
key = "{}_%".format(NOTIFICATION_KEY)
user_name = user.full_name(ctx)
ctx.uuUserMetaRemove(user_name, key, '', '')
def send_notification(ctx: rule.Context, to: str, actor: str, message: str) -> api.Result:
return mail.send(ctx,
to=to,
actor=actor,
subject='[Yoda] {}'.format(message),
body="""
You received a new notification: {}
Login to view all your notifications: https://{}/user/notifications
If you do not want to receive these emails, you can change your notification preferences here: https://{}/user/settings
Best regards,
Yoda system
""".format(message, config.yoda_portal_fqdn, config.yoda_portal_fqdn))
@rule.make(inputs=[0, 1], outputs=[2, 3])
def rule_mail_notification_report(ctx: rule.Context, to: str, notifications: str) -> Tuple[str, str]:
if not user.is_admin(ctx):
return '0', 'Only rodsadmin can send test mail'
return mail.wrapper(ctx,
to=to,
actor='system',
subject='[Yoda] {} notification(s)'.format(notifications),
body="""
You have {} notification(s).
Login to view all your notifications: https://{}/user/notifications
If you do not want to receive these emails, you can change your notification preferences here: https://{}/user/settings
Best regards,
Yoda system
""".format(notifications, config.yoda_portal_fqdn, config.yoda_portal_fqdn))
@rule.make()
def rule_process_ending_retention_packages(ctx: rule.Context) -> None:
"""Rule interface for checking vault packages for ending retention.
:param ctx: Combined type of a callback and rei struct
"""
# check permissions - rodsadmin only
if user.user_type(ctx) != 'rodsadmin':
log.write(ctx, "retention - Insufficient permissions - should only be called by rodsadmin")
return
log.write(ctx, 'retention - Checking Vault packages for ending retention')
zone = user.zone(ctx)
errors = 0
dp_notify_count = 0
# Retrieve all data packages in this vault.
iter = genquery.row_iterator(
"COLL_NAME",
"META_COLL_ATTR_NAME = 'org_vault_status' AND COLL_NAME not like '%/original'",
genquery.AS_LIST, ctx
)
for row in iter:
dp_coll = row[0]
meta_path = meta.get_latest_vault_metadata_path(ctx, dp_coll)
# Try to load the metadata file.
try:
metadata = jsonutil.read(ctx, meta_path)
current_schema_id = meta.metadata_get_schema_id(metadata)
if current_schema_id is None:
log.write(ctx, 'retention - Schema id missing - Please check the structure of this file. <{}>'.format(dp_coll))
errors += 1
continue
except jsonutil.ParseError:
log.write(ctx, 'retention - JSON invalid - Please check the structure of this file. <{}>'.format(dp_coll))
errors += 1
continue
except msi.Error as e:
log.write(ctx, 'retention - The metadata file could not be read. ({}) <{}>'.format(e, dp_coll))
errors += 1
continue
# Get deposit date and end preservation date based upon retention period.
iter2 = genquery.row_iterator(
"order_desc(META_COLL_MODIFY_TIME), META_COLL_ATTR_VALUE",
"COLL_NAME = '" + dp_coll + "' AND META_COLL_ATTR_NAME = '" + constants.UUORGMETADATAPREFIX + 'action_log' + "'",
genquery.AS_LIST, ctx
)
for row2 in iter2:
# row2 contains json encoded [str(int(time.time())), action, actor]
log_item_list = jsonutil.parse(row2[1])
if log_item_list[1] == "submitted for vault":
deposit_timestamp = datetime.fromtimestamp(int(log_item_list[0]))
date_deposit = deposit_timestamp.date()
break
try:
retention = int(metadata['Retention_Period'])
except KeyError:
log.write(ctx, 'retention - No retention period set in metadata. <{}>'.format(dp_coll))
continue
try:
date_end_retention = date_deposit.replace(year=date_deposit.year + retention)
except ValueError:
log.write(ctx, 'retention - Could not determine retention end date. Retention period: <{}>'.format(retention))
continue
r = relativedelta.relativedelta(date_end_retention, datetime.now().date())
formatted_date = date_end_retention.strftime('%Y-%m-%d')
log.write(ctx, 'retention - Retention period ({} years) ending in {} years, {} months and {} days ({}): <{}>'.format(retention, r.years, r.months, r.days, formatted_date, dp_coll))
if r.years == 0 and r.months <= 1:
group_name = folder.collection_group_name(ctx, dp_coll)
category = group.get_category(ctx, group_name)
datamanager_group_name = "datamanager-" + category
if group.exists(ctx, datamanager_group_name):
dp_notify_count += 1
# Send notifications to datamanager(s).
datamanagers = folder.get_datamanagers(ctx, '/{}/home/'.format(zone) + datamanager_group_name)
message = "Data package reaching end of preservation date: {}".format(formatted_date)
for datamanager in datamanagers:
datamanager = '{}#{}'.format(*datamanager)
actor = 'system'
set(ctx, actor, datamanager, dp_coll, message)
log.write(ctx, 'retention - Notifications set for ending retention period on {}. <{}>'.format(formatted_date, dp_coll))
log.write(ctx, 'retention - Finished checking vault packages for ending retention | notified: {} | errors: {}'.format(dp_notify_count, errors))
@rule.make()
def rule_process_groups_expiration_date(ctx: rule.Context) -> None:
"""Rule interface for checking research groups for reaching group expiration date.
:param ctx: Combined type of a callback and rei struct
"""
# check permissions - rodsadmin only
if user.user_type(ctx) != 'rodsadmin':
log.write(ctx, "group expiration date - Insufficient permissions - should only be called by rodsadmin")
return
log.write(ctx, 'group expiration date - Checking research groups for reaching group expiration date')
zone = user.zone(ctx)
notify_count = 0
today = datetime.now().strftime('%Y-%m-%d')
# First query: obtain a list of groups with group attributes
# and group expiration date less or equal than today
# and group expiration date != '.' (actually meaning empty)
iter = genquery.row_iterator(
"USER_GROUP_NAME, META_USER_ATTR_NAME, META_USER_ATTR_VALUE",
"USER_TYPE = 'rodsgroup' AND USER_GROUP_NAME like 'research-%' AND META_USER_ATTR_NAME = 'expiration_date'"
" AND META_USER_ATTR_VALUE <= '{}' AND META_USER_ATTR_VALUE != '.'".format(today),
genquery.AS_LIST, ctx
)
for row in iter:
group_name = row[0]
coll = '/{}/home/{}'.format(zone, group_name)
expiration_date = row[2]
# find corresponding datamanager
category = group.get_category(ctx, group_name)
datamanager_group_name = "datamanager-" + category
if group.exists(ctx, datamanager_group_name):
notify_count += 1
# Send notifications to datamanager(s).
datamanagers = folder.get_datamanagers(ctx, '/{}/home/'.format(zone) + datamanager_group_name)
message = "Group '{}' reached expiration date: {}".format(group_name, expiration_date)
for datamanager in datamanagers:
datamanager = '{}#{}'.format(*datamanager)
actor = 'system'
set(ctx, actor, datamanager, coll, message)
log.write(ctx, 'group expiration date - Notifications set for group {} reaching expiration date on {}. <{}>'.format(group_name, expiration_date, coll))
log.write(ctx, 'group expiration date - Finished checking research groups for reaching group expiration date | notified: {}'.format(notify_count))
@rule.make()
def rule_process_inactive_research_groups(ctx: rule.Context) -> None:
"""Rule interface for checking for research groups that have not been modified after a certain amount of months.
:param ctx: Combined type of a callback and rei struct
"""
# Only send notifications if inactivity notifications are enabled.
if not config.enable_inactivity_notification:
return
# check permissions - rodsadmin only
if user.user_type(ctx) != 'rodsadmin':
log.write(ctx, "inactive research group - Insufficient permissions - should only be called by rodsadmin")
return
log.write(ctx, 'inactive research group - Checking Research packages for last modification dates')
zone = user.zone(ctx)
notify_count = 0
inactivity_cutoff = datetime.now() - timedelta(weeks=4.35 * config.inactivity_cutoff_months)
inactivity_cutoff_epoch = int((inactivity_cutoff - datetime(1970, 1, 1)).total_seconds())
# First query: obtain a list of groups with group attributes
iter = genquery.row_iterator(
"USER_GROUP_NAME",
"USER_TYPE = 'rodsgroup' AND USER_GROUP_NAME like 'research-%'",
genquery.AS_LIST, ctx
)
for row in iter:
group_name = row[0]
coll = '/{}/home/{}'.format(zone, group_name)
# Trigger this flag if there are any files that have been modified after the cut off
# If the flag is still false after going through all the files, then that is when we send the notification
recent_files_modified = False
data_objects_count = 0
where_clause = {
'self': "COLL_NAME = '{}' AND USER_GROUP_NAME = '{}'".format(coll, group_name),
'subfolders': "COLL_NAME LIKE '{}/%' AND USER_GROUP_NAME = '{}'".format(coll, group_name)
}
# Per group two statements are required to gather all data
# 1) data in folder itself
# 2) data in all subfolders of the folder
for folder_type in ['self', 'subfolders']:
iter_subcoll = genquery.row_iterator(
"COUNT(DATA_NAME)",
where_clause[folder_type],
genquery.AS_LIST, ctx
)
# This loop should only run once
for sub_row in iter_subcoll:
data_objects_count += int(sub_row[0])
if data_objects_count > 0:
for folder_type in ['self', 'subfolders']:
if recent_files_modified:
break
iter_subcoll = genquery.row_iterator(
"DATA_NAME, COLL_NAME",
where_clause[folder_type],
genquery.AS_LIST, ctx
)
for sub_row in iter_subcoll:
if recent_files_modified:
break
sub_coll = sub_row[1]
# Get count of any data objects that have been modified after the inactivity cut off
iter_recent_data = genquery.row_iterator(
"COUNT(DATA_NAME)",
"COLL_NAME = '{}' AND USER_GROUP_NAME = '{}' AND DATA_MODIFY_TIME n> '{}'".format(sub_coll, group_name, inactivity_cutoff_epoch),
genquery.AS_LIST, ctx
)
# This loop should only run once
for count_row in iter_recent_data:
if int(count_row[0]) > 0:
recent_files_modified = True
else:
# Empty research group, so check the modified date of the collection, then send a notification
iter_data = genquery.row_iterator(
"COLL_MODIFY_TIME",
"COLL_NAME = '{}'".format(coll),
genquery.AS_LIST, ctx
)
# This loop should only run once
for sub_row in iter_data:
if int(sub_row[0]) > inactivity_cutoff_epoch:
recent_files_modified = True
if not recent_files_modified:
# find corresponding datamanager
category = group.get_category(ctx, group_name)
datamanager_group_name = "datamanager-" + category
if group.exists(ctx, datamanager_group_name):
notify_count += 1
# Send notifications to datamanager(s).
datamanagers = folder.get_datamanagers(ctx, '/{}/home/'.format(zone) + datamanager_group_name)
message = "Group '{}' has been inactive for more than {} months".format(group_name, config.inactivity_cutoff_months)
for datamanager in datamanagers:
datamanager = '{}#{}'.format(*datamanager)
actor = 'system'
set(ctx, actor, datamanager, coll, message)
log.write(ctx, 'inactive research group - Notifications set for group {} having been inactive since at least {}. <{}>'.format(group_name, inactivity_cutoff, coll))
log.write(ctx, 'inactive research group - Finished checking research groups for inactivity | notified: {}'.format(notify_count))
@rule.make()
def rule_process_data_access_token_expiry(ctx: rule.Context) -> None:
"""Rule interface for checking for data access tokens that are expiring soon.
:param ctx: Combined type of a callback and rei struct
"""
# Only send notifications if expiration notifications are enabled.
if config.token_expiration_notification == 0:
return
# check permissions - rodsadmin only
if user.user_type(ctx) != 'rodsadmin':
log.write(ctx, "data access token - Insufficient permissions - should only be called by rodsadmin")
return
log.write(ctx, 'data access token - Checking for expiring data access tokens')
tokens = data_access_token.get_all_tokens(ctx)
for token in tokens:
# Calculate token expiration notification date.
exp_time = datetime.strptime(token['exp_time'], '%Y-%m-%d %H:%M:%S.%f')
date_exp_time = exp_time - timedelta(hours=config.token_expiration_notification)
r = relativedelta.relativedelta(date_exp_time, datetime.now().date())
total_hours = r.years * 12 * 30 * 24 + r.months * 30 * 24 + r.days * 24 + r.hours
# Send notification if token expires in less than configured hours.
if total_hours <= config.token_expiration_notification:
actor = 'system'
target = str(user.from_str(ctx, token['user']))
message = "Data access password with label <{}> is expiring".format(token["label"])
set(ctx, actor, target, "/user/data_access", message)
log.write(ctx, 'data access token - Notification set for expiring data access token from user <{}>'.format(token["user"]))
log.write(ctx, 'data access token - Finished checking for expiring data access tokens')