forked from ifgi/optimetaPortal
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnotifications.py
More file actions
541 lines (449 loc) · 20.3 KB
/
Copy pathnotifications.py
File metadata and controls
541 lines (449 loc) · 20.3 KB
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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
# SPDX-FileCopyrightText: 2026 OPTIMETA and KOMET projects <https://projects.tib.eu/komet>
# SPDX-License-Identifier: GPL-3.0-or-later
"""Admin-routed email notifications.
``Work`` state changes (today: ``contribution`` and ``publish``) dispatch via
``notify_work_event(work, event_type, actor=user)`` after ``work.save()``; add a
third by writing a private ``_enqueue_<event>`` function and adding it to
``WORK_EVENT_HANDLERS``.
User-lifecycle events dispatch separately — see
``notify_admins_new_user_registered(user)`` further down, called from the
magic-link view when a brand-new account is persisted for the first time.
Email sending happens inside Django-Q tasks (``send_*`` below) so the request
that triggered the state change stays fast. Recipient resolution stays in the
caller's transaction so the queue payload is a stable list of user IDs.
Recipient transparency: each contribution-review email body lists the *roles +
counts* of who else got the notification (e.g. "1 admin and 2 curators of
'Mountain Wetlands'") so a curator who picks up the work knows others may act
on it concurrently. Individual emails are not leaked between recipients.
"""
from __future__ import annotations
import logging
from typing import Iterable
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.mail import send_mail
from django.urls import reverse
from django.utils import timezone
from works.utils.email import render_email
logger = logging.getLogger(__name__)
User = get_user_model()
# ---------------------------------------------------------------------------
# Public dispatch
# ---------------------------------------------------------------------------
def notify_work_event(work, event_type: str, actor=None) -> None:
"""Queue notifications for a ``Work`` state change.
No-op (with a debug log) when ``event_type`` has no registered handler, so
callers can sprinkle this on every state transition without fear.
"""
handler = WORK_EVENT_HANDLERS.get(event_type)
if not handler:
logger.debug("No notification handler for work event %r — skipping.", event_type)
return
try:
handler(work, actor)
except Exception: # noqa: BLE001 — notification must never crash the state change
logger.exception(
"notify_work_event(%r) failed for work id=%s; state change is unaffected.",
event_type,
getattr(work, "pk", None),
)
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _absolute_work_url(work) -> str:
"""Absolute URL to the public work landing page."""
return f"{settings.BASE_URL}{reverse('optimap:work-landing', args=[work.get_identifier()])}"
def _opted_in(qs):
"""Filter a User queryset to those who haven't opted out of work-event emails.
Uses ``exclude(...=False)`` rather than ``filter(...=True)`` so that any
user without a ``UserProfile`` row (legacy / fixture-loaded accounts that
bypass the ``post_save`` signal) is treated as opted-in by default — the
field is opt-out per the docstring on ``UserProfile.notify_work_events``.
"""
return qs.exclude(userprofile__notify_work_events=False)
def _curators_for_work(work):
"""Return a queryset of curator users for any collection that contains ``work``."""
return _opted_in(
User.objects.filter(
curated_collections__in=work.collections.all(),
email__gt="",
is_active=True,
).distinct()
)
def _admins():
"""Return a queryset of active staff users with an email address.
Inactive (deactivated) staff accounts are excluded — a disabled account
must not receive any operational notification.
"""
return _opted_in(User.objects.filter(is_staff=True, is_active=True).exclude(email__exact="").distinct())
def _format_role_summary(admins_count: int, curator_collections: list[str]) -> str:
"""Roles + counts for the recipient-transparency block.
>>> _format_role_summary(1, ["Mountain Wetlands"])
"1 admin and 1 curator of 'Mountain Wetlands'"
>>> _format_role_summary(2, ["A", "B"])
"2 admins and 2 curators of 'A', 'B'"
"""
parts = []
if admins_count:
parts.append(f"{admins_count} admin" + ("s" if admins_count != 1 else ""))
if curator_collections:
n = len(curator_collections)
names = ", ".join(f"'{c}'" for c in curator_collections)
parts.append(f"{n} curator" + ("s" if n != 1 else "") + f" of {names}")
if not parts:
return "0 recipients"
if len(parts) == 1:
return parts[0]
return " and ".join(parts)
# ---------------------------------------------------------------------------
# Contribution review notification — admins + curators
# ---------------------------------------------------------------------------
def _enqueue_contribution_review(work, actor) -> None:
from django_q.tasks import async_task # local import to keep test isolation simple
admin_ids = list(_admins().exclude(pk=getattr(actor, "pk", None)).values_list("id", flat=True))
curator_ids_by_collection = {}
for collection in work.collections.all():
ids = list(
_opted_in(collection.curators.filter(email__gt="", is_active=True))
.exclude(pk=getattr(actor, "pk", None))
.values_list("id", flat=True)
)
if ids:
curator_ids_by_collection[collection.name] = ids
# Distinct recipient set across all roles, plus the role label per user
# (deduplicated: an admin who also happens to curate a collection is
# listed once with the "admin" role to avoid double-emailing).
all_curator_ids = {uid for ids in curator_ids_by_collection.values() for uid in ids}
distinct_recipient_ids = set(admin_ids) | all_curator_ids
if not distinct_recipient_ids:
logger.info("Contribution to work id=%s — no admin or curator recipients.", work.pk)
return
role_summary = _format_role_summary(
admins_count=len(admin_ids),
curator_collections=sorted(curator_ids_by_collection.keys()),
)
async_task(
"works.notifications.send_contribution_review_email",
list(distinct_recipient_ids),
work.pk,
getattr(actor, "pk", None),
role_summary,
)
def send_contribution_review_email(
recipient_ids: Iterable[int],
work_id: int,
actor_id: int | None,
role_summary: str,
) -> None:
"""Django-Q task: notify admins + curators of a new contribution."""
from works.models import Work # local: avoid circular import on app boot
try:
work = Work.objects.get(pk=work_id)
except Work.DoesNotExist:
logger.warning("send_contribution_review_email: work id=%s vanished.", work_id)
return
actor = User.objects.filter(pk=actor_id).first() if actor_id else None
actor_label = actor.email if actor and actor.email else (actor.username if actor else "(unknown)")
subject, body = render_email(
"email/contribution_review.en.txt",
{
"actor_label": actor_label,
"work_title": work.title[:120],
"work_doi": work.doi or "(none)",
"submitted_at": timezone.now().isoformat(timespec="seconds"),
"work_url": _absolute_work_url(work),
"role_summary": role_summary,
},
)
recipients = list(
User.objects.filter(pk__in=list(recipient_ids), is_active=True)
.exclude(email__exact="")
.values_list("email", flat=True)
)
for email in recipients:
try:
send_mail(subject, body, settings.EMAIL_HOST_USER, [email], fail_silently=False)
except Exception: # noqa: BLE001
logger.exception("Failed to send contribution-review email to %s.", email)
# ---------------------------------------------------------------------------
# Publication notification — original contributors
# ---------------------------------------------------------------------------
def _enqueue_publication_to_contributors(work, actor) -> None:
from django_q.tasks import async_task
# Suppress double-notification on republish cycles.
provenance = work.provenance if isinstance(work.provenance, dict) else {}
if provenance.get("publication_notified_at"):
logger.debug(
"Work id=%s already notified on a previous publish — skipping.",
work.pk,
)
return
from works.models import Contribution
contributor_ids = list(
Contribution.objects.filter(work=work, user__is_active=True)
.exclude(user__pk=getattr(actor, "pk", None))
# Honour the per-user opt-out — same exclude-False pattern as
# ``_opted_in`` so users without a UserProfile row stay opted-in by
# default (the field defaults to True at create time).
.exclude(user__userprofile__notify_work_events=False)
.values_list("user_id", flat=True)
.distinct()
)
if not contributor_ids:
return
async_task(
"works.notifications.send_publication_to_contributor_emails",
contributor_ids,
work.pk,
)
def send_publication_to_contributor_emails(contributor_ids: Iterable[int], work_id: int) -> None:
"""Django-Q task: notify original contributors that a work has been published."""
from works.models import Contribution, Work
try:
work = Work.objects.get(pk=work_id)
except Work.DoesNotExist:
logger.warning("send_publication_to_contributor_emails: work id=%s vanished.", work_id)
return
work_url = _absolute_work_url(work)
for contributor_id in contributor_ids:
contributor = User.objects.filter(pk=contributor_id, is_active=True).exclude(email__exact="").first()
if not contributor:
continue
# Per-contributor body so we can list the specific contribution kinds.
kinds = list(
Contribution.objects.filter(work=work, user=contributor).values_list("kind", flat=True).distinct()
)
kind_label = ", ".join(sorted(kinds)) if kinds else "metadata"
subject, body = render_email(
"email/publication_to_contributor.en.txt",
{
"work_title": work.title[:120],
"work_doi": work.doi or "(none)",
"kind_label": kind_label,
"work_url": work_url,
},
)
try:
send_mail(subject, body, settings.EMAIL_HOST_USER, [contributor.email], fail_silently=False)
except Exception: # noqa: BLE001
logger.exception(
"Failed to send publication notification to contributor %s.",
contributor.email,
)
# Stamp the suppression marker after the fan-out so a republish cycle
# does not re-notify. We use update() to avoid bumping lastUpdate /
# re-running pre_save signals.
new_provenance = dict(work.provenance) if isinstance(work.provenance, dict) else {}
new_provenance["publication_notified_at"] = timezone.now().isoformat(timespec="seconds")
Work.objects.filter(pk=work.pk).update(provenance=new_provenance)
# ---------------------------------------------------------------------------
# User lifecycle — admins on first confirmed login (new account persisted).
# ---------------------------------------------------------------------------
def notify_admins_new_user_registered(user) -> None:
"""Queue an admin notification for a freshly persisted user account.
Called from ``authenticate_via_magic_link`` immediately after
``User.objects.create_user(...)``. A new ``CustomUser`` row is *only*
created when a magic-link recipient clicks the "confirm" step of the
two-step new-account flow, so reaching this code path is by construction
a first-time confirmed registration — no separate "first login" check is
needed.
Failures must never break the login. Same defensive ``except Exception``
wrapper as ``notify_work_event``.
"""
try:
from django_q.tasks import async_task
admin_ids = list(
_opted_in(User.objects.filter(is_staff=True, is_active=True))
.exclude(email__exact="")
.exclude(pk=getattr(user, "pk", None)) # the new user *could* be staff, e.g. a fixture seed
.values_list("id", flat=True)
.distinct()
)
if not admin_ids:
logger.info(
"New user %s registered — no staff recipients to notify.",
getattr(user, "email", "(unknown)"),
)
return
async_task(
"works.notifications.send_new_user_admin_email",
admin_ids,
user.pk,
)
except Exception: # noqa: BLE001 — notification must never crash login
logger.exception(
"notify_admins_new_user_registered failed for user id=%s; login is unaffected.",
getattr(user, "pk", None),
)
def send_new_user_admin_email(recipient_ids: Iterable[int], user_id: int) -> None:
"""Django-Q task: tell each admin that a new user just confirmed registration.
Recipients are resolved in ``notify_admins_new_user_registered`` to active
staff who have not opted out via ``notify_work_events``; this task only
re-checks the address (and active flag, defensively) before sending.
"""
from works.models import EmailLog
try:
user = User.objects.get(pk=user_id)
except User.DoesNotExist:
logger.warning(
"send_new_user_admin_email: user id=%s vanished before send.",
user_id,
)
return
user_admin_url = f"{settings.BASE_URL}{reverse('admin:works_customuser_change', args=[user.pk])}"
subject, body = render_email(
"email/new_user_admin.en.txt",
{
"user_email": user.email,
"username": user.username,
"registered_at": user.date_joined.isoformat(timespec="seconds"),
"user_admin_url": user_admin_url,
},
)
admin_emails = list(
User.objects.filter(pk__in=list(recipient_ids), is_active=True)
.exclude(email__exact="")
.values_list("email", flat=True)
)
for admin_email in admin_emails:
try:
send_mail(subject, body, settings.EMAIL_HOST_USER, [admin_email], fail_silently=False)
EmailLog.log_email(
recipient=admin_email,
subject=subject,
content=body,
trigger_source="scheduled",
status="success",
)
except Exception as ex: # noqa: BLE001
logger.exception("Failed to send new-user admin email to %s.", admin_email)
EmailLog.log_email(
recipient=admin_email,
subject=subject,
content=body,
trigger_source="scheduled",
status="failed",
error_message=str(ex),
)
# ---------------------------------------------------------------------------
# Curator change notification — all curators + admins + actor + changed user
# ---------------------------------------------------------------------------
def notify_curator_change(collection, changed_user, action: str, actor) -> None:
"""Queue a notification when a curator is added to or removed from a collection.
action: 'added' or 'removed'
Recipients: all curators currently on the collection (post-change state)
+ all admins + the actor + the changed user. Everyone in one email —
no separate "you were added" message.
Recipients are gated like the other admin-routed work emails: only active
accounts are emailed, and the ``notify_work_events`` opt-out is honored
(so an opted-out user — even the actor or the changed curator — is not
notified). Never crashes the calling request.
"""
try:
from django_q.tasks import async_task
curator_ids = set(collection.curators.exclude(email__exact="").values_list("id", flat=True))
admin_ids = set(User.objects.filter(is_staff=True).exclude(email__exact="").values_list("id", flat=True))
candidate_ids = curator_ids | admin_ids
if getattr(actor, "pk", None):
candidate_ids.add(actor.pk)
if getattr(changed_user, "pk", None):
candidate_ids.add(changed_user.pk)
# Keep only active users with an email address who have not opted out
# of work-event notifications (``_opted_in`` keeps profile-less users in).
recipient_ids = list(
_opted_in(User.objects.filter(pk__in=candidate_ids, is_active=True))
.exclude(email__exact="")
.values_list("id", flat=True)
)
if not recipient_ids:
logger.info(
"Curator %s on collection id=%s — no recipients to notify.",
action,
collection.pk,
)
return
async_task(
"works.notifications.send_curator_change_email",
recipient_ids,
collection.pk,
changed_user.pk,
action,
getattr(actor, "pk", None),
)
except Exception: # noqa: BLE001 — notification must never crash the request
logger.exception(
"notify_curator_change failed for collection id=%s; action is unaffected.",
getattr(collection, "pk", None),
)
def send_curator_change_email(
recipient_ids: Iterable[int],
collection_id: int,
changed_user_id: int,
action: str,
actor_id: int | None,
) -> None:
"""Django-Q task: notify everyone about a curator list change."""
from works.models import Collection # local: avoid circular import
try:
collection = Collection.objects.get(pk=collection_id)
except Collection.DoesNotExist:
logger.warning("send_curator_change_email: collection id=%s vanished.", collection_id)
return
changed_user = User.objects.filter(pk=changed_user_id).first()
if not changed_user:
logger.warning("send_curator_change_email: changed_user id=%s vanished.", changed_user_id)
return
actor = User.objects.filter(pk=actor_id).first() if actor_id else None
actor_label = actor.email if actor and actor.email else (actor.username if actor else "(unknown)")
changed_label = changed_user.email or changed_user.username
verb = "was added to" if action == "added" else "was removed from"
current_curators = list(collection.curators.exclude(email__exact="").values_list("email", flat=True))
curators_line = ", ".join(sorted(current_curators)) if current_curators else "(none)"
collection_url = f"{settings.BASE_URL}{collection.get_absolute_url()}"
subject, body = render_email(
"email/curator_change.en.txt",
{
"action": action,
"collection_name": collection.name,
"changed_label": changed_label,
"verb": verb,
"actor_label": actor_label,
"collection_url": collection_url,
"curators_line": curators_line,
},
)
from works.models import EmailLog # local: avoid circular import
recipients = list(
User.objects.filter(pk__in=list(recipient_ids), is_active=True)
.exclude(email__exact="")
.values_list("email", flat=True)
)
for email in recipients:
try:
send_mail(subject, body, settings.EMAIL_HOST_USER, [email], fail_silently=False)
EmailLog.log_email(
recipient=email,
subject=subject,
content=body,
trigger_source="scheduled",
status="success",
)
except Exception as ex: # noqa: BLE001
logger.exception("Failed to send curator-change email to %s.", email)
EmailLog.log_email(
recipient=email,
subject=subject,
content=body,
trigger_source="scheduled",
status="failed",
error_message=str(ex),
)
# ---------------------------------------------------------------------------
# Registry — extend by adding entries here.
# ---------------------------------------------------------------------------
WORK_EVENT_HANDLERS = {
"contribution": _enqueue_contribution_review,
"publish": _enqueue_publication_to_contributors,
# Future:
# "unpublish": _enqueue_unpublish_audit,
}