forked from ifgi/optimetaPortal
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtasks.py
More file actions
1826 lines (1592 loc) · 70.8 KB
/
Copy pathtasks.py
File metadata and controls
1826 lines (1592 loc) · 70.8 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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SPDX-FileCopyrightText: 2022 OPTIMETA and KOMET projects <https://projects.tib.eu/komet>
# SPDX-License-Identifier: GPL-3.0-or-later
"""Django-Q task entry points.
The harvesting code lives in the ``works.harvesting`` package — one module
per source type (OAI-PMH / RSS / Crossref / MaRESS) plus shared helpers.
This module re-exports the public surface so existing dotted-path schedules
(``works.tasks.harvest_oai_endpoint`` etc.), test imports, and ``@patch``
targets keep resolving without migration.
The non-harvest tasks (monthly email digest, subscription emails, GeoJSON /
GeoPackage cache regeneration, schedule helpers) still live here.
"""
import calendar
import glob
import gzip
import json
import logging
import os
import tempfile
import time
from collections import defaultdict
from datetime import datetime, timedelta
from datetime import timezone as dt_timezone
from pathlib import Path
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.mail import EmailMessage, send_mail
from django.core.serializers.json import DjangoJSONEncoder
from django.db.models import Q
from django.urls import reverse
from django.utils import timezone
from django_q.models import Schedule
from django_q.tasks import schedule
from osgeo import gdal
# -----------------------------------------------------------------------------
# Re-exports from the harvesting package — preserve the public surface that
# Django-Q schedule rows (`works.tasks.harvest_*`), tests, and admin actions
# reference by dotted path.
# -----------------------------------------------------------------------------
from works.harvesting.common import ( # noqa: F401
HarvestStats,
HarvestWarningCollector,
_carefully_update_work,
_find_existing_work,
_get_article_link,
_is_empty_for_update,
_save_or_update_work,
complete_harvest,
fail_harvest,
get_or_create_admin_command_user,
parse_publication_date,
resolve_user,
send_harvest_email,
)
from works.harvesting.crossref import ( # noqa: F401
CROSSREF_API_URL,
CROSSREF_HTTP_TIMEOUT,
CROSSREF_PAGE_ROWS,
_build_crossref_filter,
_crossref_item_to_work_kwargs,
_crossref_session,
_strip_jats,
fetch_copernicus_abstract,
harvest_crossref_book_list,
harvest_crossref_doi,
harvest_crossref_prefix,
parse_crossref_response_and_save_works,
reharvest_work,
)
from works.harvesting.datacite import ( # noqa: F401
DATACITE_API_URL,
harvest_datacite,
parse_datacite_response_and_save_works,
)
from works.harvesting.geoscienceworld import ( # noqa: F401
harvest_geoscienceworld,
parse_gsw_response_and_save_works,
)
from works.harvesting.gfz_igsn import ( # noqa: F401
harvest_gfz_igsn,
scrape_gfz_and_save_works,
)
from works.harvesting.metadata_html import ( # noqa: F401
_extract_dc_box,
_extract_dc_spatial_coverage,
_extract_dc_temporal,
_extract_geojson_link,
_extract_jsonld_spatial,
_extract_jsonld_temporal,
_geom_from_geojson_dict,
_polygon_from_bbox,
_split_iso_interval,
_walk_jsonld,
_wrap_in_collection,
extract_geometry_from_html,
extract_timeperiod_from_html,
)
from works.harvesting.mountain_wetlands import ( # noqa: F401
MWR_HTTP_TIMEOUT,
MWR_PAGE_SIZE,
_mwr_authors_list,
_mwr_first_author_surname,
_mwr_geometry_from_study_sites,
_mwr_item_url,
_mwr_publication_year,
_mwr_session,
harvest_mountain_wetlands,
parse_mountain_wetlands_response_and_save_works,
)
from works.harvesting.oai import ( # noqa: F401
DOI_REGEX,
harvest_oai_endpoint,
parse_oai_xml_and_save_works,
)
from works.harvesting.openaire import ( # noqa: F401
build_openaire_fields,
enrich_event_from_openaire,
enrich_work_from_openaire,
fetch_openaire_record,
)
from works.harvesting.openalex import build_openalex_fields # noqa: F401
from works.harvesting.openalex_source import ( # noqa: F401
OPENALEX_API_URL,
OPENALEX_HTTP_TIMEOUT,
OPENALEX_PAGE_SIZE,
_openalex_session,
harvest_openalex_source,
parse_openalex_response_and_save_works,
)
from works.harvesting.rss import ( # noqa: F401
harvest_rss_endpoint,
parse_rss_feed_and_save_publications,
)
from works.harvesting.sessions import ( # noqa: F401
OAI_HTTP_TIMEOUT,
OAI_RETRY_TOTAL,
OAI_USER_AGENT,
_looks_like_oai_xml,
_oai_session,
_openaire_session,
_short_body,
)
from works.models import EmailLog, Subscription, Work
from works.utils.email import render_email
from works.utils.geojson import _GEOJSON_METADATA
from works.utils.geometry import annotate_rounded_geometry, round_geojson_coordinates
from works.utils.scheduling import log_scheduled_catchup
logger = logging.getLogger(__name__)
BASE_URL = settings.BASE_URL
# Wrap the re-exported harvest entry points so recurring schedules
# (`works.tasks.harvest_*`, which set intended_date_kwarg="scheduled_for") log a
# catch-up notice when they fire late after downtime. Re-binding the names here
# is what Django-Q resolves via dotted path; manual/ad-hoc calls (no
# scheduled_for) are unaffected. See works/utils/scheduling.py.
harvest_oai_endpoint = log_scheduled_catchup(harvest_oai_endpoint)
harvest_rss_endpoint = log_scheduled_catchup(harvest_rss_endpoint)
harvest_crossref_prefix = log_scheduled_catchup(harvest_crossref_prefix)
harvest_mountain_wetlands = log_scheduled_catchup(harvest_mountain_wetlands)
harvest_openalex_source = log_scheduled_catchup(harvest_openalex_source)
harvest_geoscienceworld = log_scheduled_catchup(harvest_geoscienceworld)
harvest_datacite = log_scheduled_catchup(harvest_datacite)
harvest_gfz_igsn = log_scheduled_catchup(harvest_gfz_igsn)
CACHE_DIR = Path(tempfile.gettempdir()) / "optimap_cache"
User = get_user_model()
def dedup_sweep(locations_only=False, force=False, limit=None):
"""Django-Q entry point: backfill OpenAlex locations + auto-merge duplicates.
Thin wrapper over ``works.dedup.sweep`` so recurring schedules and the
``dedup_works --async`` command can resolve it by dotted path. See
``works/dedup.py`` for the two-pass behaviour.
"""
from works.dedup import sweep
stats = sweep(locations_only=locations_only, force=force, limit=limit)
logger.info("dedup_sweep finished: %s", stats)
return stats
# -----------------------------------------------------------------------------
# Data-dump helpers (used by regenerate_geojson_cache / regenerate_geopackage_cache).
# -----------------------------------------------------------------------------
def generate_data_dump_filename(extension: str) -> str:
ts = datetime.now(dt_timezone.utc).strftime("%Y%m%dT%H%M%S")
return f"optimap_data_dump_{ts}.{extension}"
def human_size(path) -> str:
"""Return a human-readable size (e.g. ``12.3 MiB``) for the file at ``path``.
Falls back to ``"size unavailable"`` if the file can't be stat'd (e.g. it
was pruned between generation and reporting). Shared by the dump task
logging and the ``regenerate_data_dumps`` management command.
"""
try:
size = os.path.getsize(path)
except OSError:
return "size unavailable"
value = float(size)
for unit in ("B", "KiB", "MiB", "GiB", "TiB"):
if value < 1024 or unit == "TiB":
precision = 0 if unit == "B" else 1
return f"{value:.{precision}f} {unit}"
value /= 1024
def cleanup_old_data_dumps(directory: Path, keep: int):
"""Keep the newest ``keep`` dump cycles, dropping older files.
Each regen cycle now produces multiple files for the same timestamp
(``optimap_data_dump_<ts>.geojson`` + ``.geojson.gz`` + ``.gpkg`` +
``.csv``). Counting raw files would prune fresh formats from the current
cycle (e.g. drop ``.csv`` because it sorts after ``.gpkg``); instead, we
group by the ``optimap_data_dump_<ts>`` prefix and keep the newest
``keep`` *cycles*.
"""
pattern = str(directory / "optimap_data_dump_*")
files = glob.glob(pattern)
# Group by `optimap_data_dump_<TS>`. The timestamp is fixed-width
# (``%Y%m%dT%H%M%S``) so the second underscore-delimited field is the
# full prefix we want regardless of extension.
cycles = defaultdict(list)
for path in files:
name = os.path.basename(path)
# `optimap_data_dump_<TS>.<ext>` — split on the first '.' to get the
# cycle key (drops the extension, including compound `.geojson.gz`).
cycle_key = name.split(".", 1)[0]
cycles[cycle_key].append(path)
for cycle_key in sorted(cycles, reverse=True)[keep:]:
for old in cycles[cycle_key]:
try:
os.remove(old)
except OSError:
logger.warning("Could not delete old dump %s", old)
# -----------------------------------------------------------------------------
# Monthly email digest.
# -----------------------------------------------------------------------------
@log_scheduled_catchup
def send_monthly_email(trigger_source="manual", sent_by=None):
"""
Send the monthly digest of new manuscripts to users who opted in.
Rules:
- One email per distinct recipient with a non-empty address.
- Link for each work:
* if DOI present -> prefer OPTIMAP permalink, fallback to https://doi.org/<doi>
* else -> fallback to Work.url (may be empty)
- Log success/failure to EmailLog.
- Respect settings.EMAIL_SEND_DELAY if present.
"""
recipients_qs = (
User.objects.filter(userprofile__notify_new_manuscripts=True)
.exclude(email__isnull=True)
.exclude(email__exact="")
.values_list("email", flat=True)
.distinct()
)
recipients = list(recipients_qs)
last_month = timezone.now().replace(day=1) - timedelta(days=1)
new_manuscripts = Work.objects.filter(
creationDate__year=last_month.year,
creationDate__month=last_month.month,
)
if not recipients or not new_manuscripts.exists():
return
def link_for(work):
if work.doi:
try:
permalink = work.permalink()
except TypeError:
permalink = work.permalink if hasattr(work, "permalink") else None
if permalink:
return permalink
return f"https://doi.org/{work.doi}"
return work.url or ""
manuscripts = [{"title": w.title, "link": link_for(w)} for w in new_manuscripts]
subject, content = render_email("email/monthly_digest.en.txt", {"manuscripts": manuscripts})
delay_seconds = getattr(settings, "EMAIL_SEND_DELAY", 0)
for recipient in recipients:
try:
send_mail(
subject,
content,
settings.EMAIL_HOST_USER,
[recipient],
fail_silently=False,
)
EmailLog.log_email(
recipient,
subject,
content,
sent_by=sent_by,
trigger_source=trigger_source,
status="success",
)
if delay_seconds:
time.sleep(delay_seconds)
except Exception as e:
logger.error("Failed to send monthly email to %s: %s", recipient, e)
EmailLog.log_email(
recipient,
subject,
content,
sent_by=sent_by,
trigger_source=trigger_source,
status="failed",
error_message=str(e),
)
def _matching_publications(items, cutoff):
"""Map each subscribed region/source/collection to its matching published
works added since cutoff (reading persisted Work relations, not
re-computing them). Drops items with no matches, and items with no
landing-page URL (e.g. a Source with a still-blank slug) so they can't be
counted in ``total_publications`` and then silently omitted from the
email body by ``_build_subscription_groups``."""
publications = {}
for item in items:
if not item.get_absolute_url():
continue
matching_pubs = list(item.works.filter(status="p", creationDate__gte=cutoff).order_by("-creationDate")[:50])
if matching_pubs:
publications[item] = matching_pubs
return publications
def _build_subscription_group(obj, pubs, name, url, extra_fields=None):
"""Shape a (region|source|collection, matching works) pair into the dict
consumed by subscription_regional.en.txt — same shape for every section
so the email template can loop over all three identically."""
pub_items = [
{
"title": (w.title[:100] + "..." if len(w.title) > 100 else w.title),
"link": _get_article_link(w),
}
for w in pubs[:10]
]
group = {
"name": name,
"pub_count": len(pubs),
"url": url,
"pubs": pub_items,
"extra_count": max(0, len(pubs) - 10),
}
if extra_fields:
group.update(extra_fields)
return group
def _build_subscription_groups(publications, extra_fields=None):
"""Turn a {item: pubs} map (from ``_matching_publications``, which already
excludes items with no landing-page URL) into a name-sorted list of
email-template groups."""
return [
_build_subscription_group(
item,
pubs,
item.name,
f"{BASE_URL}{item.get_absolute_url()}",
extra_fields=extra_fields(item) if extra_fields else None,
)
for item, pubs in sorted(publications.items(), key=lambda pair: pair[0].name)
]
@log_scheduled_catchup
def send_subscription_based_email(trigger_source="manual", sent_by=None, user_ids=None, interval=None):
"""
Send subscription-based notifications grouped by region, source, and collection.
Publications are grouped by the regions/sources/collections the user has
subscribed to. Each group includes a link to that item's landing page.
Works may appear in more than one section (e.g. a work matching both a
subscribed region and a subscribed source) — sections are not deduplicated
against each other.
``interval`` — when given ('weekly' or 'monthly'), only processes subscriptions
whose ``notification_interval`` matches. Pass ``None`` (the default, used for
manual/admin runs) to process all active subscriptions regardless of their
interval setting.
Only publications added since ``subscription.last_notified`` are included.
If ``last_notified`` is unset, a sensible fallback window is used (7 days for
weekly, 31 days for monthly, 31 days when interval is None).
``last_notified`` is updated only after a successful send.
"""
query = Subscription.objects.filter(subscribed=True, user__isnull=False).prefetch_related(
"regions", "sources", "collections"
)
if user_ids:
query = query.filter(user__id__in=user_ids)
if interval is not None:
query = query.filter(notification_interval=interval)
fallback_days = 7 if interval == "weekly" else 31
for subscription in query:
user_email = subscription.user.email
subscribed_regions = list(subscription.regions.all())
subscribed_sources = list(subscription.sources.all())
# Re-check is_published here (not just at subscribe-time in add_subscriptions):
# a collection can be unpublished after a user already subscribed to it, or
# be added directly via the admin without going through that guard.
subscribed_collections = list(subscription.collections.filter(is_published=True))
if not (subscribed_regions or subscribed_sources or subscribed_collections):
logger.info(f"Skipping subscription for {user_email} - no regions/sources/collections selected")
continue
cutoff = (
subscription.last_notified
if subscription.last_notified
else (timezone.now() - timedelta(days=fallback_days))
)
# Read the persisted Work.regions M2M (populated by the
# assign_work_regions signal / backfill_work_regions sweep) rather
# than re-intersecting every published work's geometry here.
region_publications = _matching_publications(subscribed_regions, cutoff)
source_publications = _matching_publications(subscribed_sources, cutoff)
collection_publications = _matching_publications(subscribed_collections, cutoff)
total_publications = sum(
len(pubs)
for publications in (region_publications, source_publications, collection_publications)
for pubs in publications.values()
)
if total_publications == 0:
logger.info(f"Skipping subscription for {user_email} - no new publications since {cutoff}")
continue
unsubscribe_all = f"{BASE_URL}{reverse('optimap:unsubscribe')}?all=true"
manage_subscriptions = f"{BASE_URL}{reverse('optimap:subscriptions')}"
region_groups = _build_subscription_groups(
region_publications, extra_fields=lambda r: {"region_type": r.get_region_type_display()}
)
source_groups = _build_subscription_groups(source_publications)
collection_groups = _build_subscription_groups(collection_publications)
subject, content = render_email(
"email/subscription_regional.en.txt",
{
"total_publications": total_publications,
"username": subscription.user.username,
"region_groups": region_groups,
"source_groups": source_groups,
"collection_groups": collection_groups,
"manage_subscriptions": manage_subscriptions,
"unsubscribe_all": unsubscribe_all,
"base_url": BASE_URL,
},
)
try:
email = EmailMessage(subject, content, settings.EMAIL_HOST_USER, [user_email])
email.send()
EmailLog.log_email(
user_email, subject, content, sent_by=sent_by, trigger_source=trigger_source, status="success"
)
logger.info(
f"Sent subscription email to {user_email} with {total_publications} publications across "
f"{len(region_publications)} regions, {len(source_publications)} sources, "
f"{len(collection_publications)} collections"
)
subscription.last_notified = timezone.now()
subscription.save(update_fields=["last_notified"])
time.sleep(settings.EMAIL_SEND_DELAY)
except Exception as e:
error_message = str(e)
logger.error(f"Failed to send subscription email to {user_email}: {error_message}")
EmailLog.log_email(
user_email,
subject,
content,
sent_by=sent_by,
trigger_source=trigger_source,
status="failed",
error_message=error_message,
)
def schedule_monthly_email_task(sent_by=None):
if not Schedule.objects.filter(func="works.tasks.send_monthly_email").exists():
now = timezone.localtime()
last_day_of_month = calendar.monthrange(now.year, now.month)[1]
next_run_date = now.replace(day=last_day_of_month, hour=23, minute=59)
# Function kwargs are spread, not passed as kwargs={...}: django_q's
# schedule() treats leftover keyword args as the task's own kwargs.
schedule(
"works.tasks.send_monthly_email",
schedule_type="M",
repeats=-1,
next_run=next_run_date,
intended_date_kwarg="scheduled_for",
trigger_source="scheduled",
sent_by=sent_by.id if sent_by else None,
)
logger.info(f"Scheduled 'schedule_monthly_email_task' for {next_run_date}")
def schedule_subscription_email_task(sent_by=None):
# Monthly subscription digest — distinguished from the weekly one by schedule_type "M".
if not Schedule.objects.filter(func="works.tasks.send_subscription_based_email", schedule_type="M").exists():
now = timezone.localtime()
last_day_of_month = calendar.monthrange(now.year, now.month)[1]
next_run_date = now.replace(day=last_day_of_month, hour=23, minute=59)
schedule(
"works.tasks.send_subscription_based_email",
schedule_type="M",
repeats=-1,
next_run=next_run_date,
intended_date_kwarg="scheduled_for",
trigger_source="scheduled",
interval="monthly",
sent_by=sent_by.id if sent_by else None,
)
logger.info(f"Scheduled monthly 'send_subscription_based_email' for {next_run_date}")
def schedule_weekly_subscription_email_task(sent_by=None):
# Weekly subscription digest — distinguished from the monthly one by weekly schedule_type "W".
# Uses "W" (not cron "C") so it works without the optional croniter dependency.
if not Schedule.objects.filter(func="works.tasks.send_subscription_based_email", schedule_type="W").exists():
next_run = _next_monday().replace(hour=2, minute=0, second=0, microsecond=0)
schedule(
"works.tasks.send_subscription_based_email",
schedule_type="W",
repeats=-1,
next_run=next_run,
intended_date_kwarg="scheduled_for",
trigger_source="scheduled",
interval="weekly",
sent_by=sent_by.id if sent_by else None,
)
logger.info("Scheduled weekly 'send_subscription_based_email' (Mondays 02:00).")
# -----------------------------------------------------------------------------
# Inactivity warning (#120) and deletion list (#121).
# -----------------------------------------------------------------------------
def _next_monday():
"""Return next Monday at 08:00 (always at least 1 day ahead)."""
now = timezone.now()
days_ahead = (7 - now.weekday()) % 7 or 7
return (now + timedelta(days=days_ahead)).replace(hour=8, minute=0, second=0, microsecond=0)
@log_scheduled_catchup
def send_inactivity_warning_emails(trigger_source="scheduled"):
"""Email users in the 12-to-13-month inactivity window (#120)."""
from django.contrib.auth import get_user_model
from works.models import EmailLog
from works.views.auth import is_email_blocked
User = get_user_model()
now = timezone.now()
warning_cutoff = now - timedelta(days=settings.INACTIVITY_WARNING_DAYS)
deletion_cutoff = now - timedelta(days=settings.INACTIVITY_DELETION_DAYS)
users = User.objects.filter(
is_active=True,
last_login__lt=warning_cutoff,
last_login__gte=deletion_cutoff,
).exclude(email="")
login_url = settings.BASE_URL
for user in users:
if is_email_blocked(user.email):
logger.info("Skipping blocked address %s for inactivity warning.", user.email)
continue
subject, body = render_email(
"email/account_inactivity_warning.en.txt",
{
"email": user.email,
"login_url": login_url,
},
)
try:
send_mail(subject, body, settings.EMAIL_HOST_USER, [user.email], fail_silently=False)
EmailLog.log_email(user.email, subject, body, trigger_source=trigger_source, status="success")
except Exception as ex: # noqa: BLE001
logger.exception("Failed to send inactivity warning to %s.", user.email)
EmailLog.log_email(
user.email, subject, body, trigger_source=trigger_source, status="failed", error_message=str(ex)
)
time.sleep(settings.EMAIL_SEND_DELAY)
@log_scheduled_catchup
def send_inactivity_deletion_list_to_admins(trigger_source="scheduled"):
"""Email admins a list of users inactive for 13+ months (#121)."""
from django.contrib.auth import get_user_model
from works.models import EmailLog
User = get_user_model()
now = timezone.now()
deletion_cutoff = now - timedelta(days=settings.INACTIVITY_DELETION_DAYS)
stale_users = list(
User.objects.filter(is_active=True, last_login__lt=deletion_cutoff).exclude(email="").order_by("last_login")
)
if not stale_users:
logger.info("send_inactivity_deletion_list_to_admins: no users pending deletion.")
return
admin_emails = list(User.objects.filter(is_staff=True).exclude(email="").values_list("email", flat=True))
if not admin_emails:
logger.warning("send_inactivity_deletion_list_to_admins: no admin emails configured.")
return
# Attach the date of the most recent successful warning email to each user.
stale_emails = [u.email for u in stale_users]
warning_log_by_email = {}
for log in EmailLog.objects.filter(
recipient_email__in=stale_emails, subject__icontains="account will be deleted", status="success"
).order_by("-sent_at"):
warning_log_by_email.setdefault(log.recipient_email, log)
for user in stale_users:
user.warning_log = warning_log_by_email.get(user.email)
admin_url = f"{settings.BASE_URL}{reverse('admin:works_customuser_changelist')}"
subject, body = render_email(
"email/account_deletion_pending.en.txt",
{
"count": len(stale_users),
"users": stale_users,
"admin_url": admin_url,
},
)
for admin_email in admin_emails:
try:
send_mail(subject, body, settings.EMAIL_HOST_USER, [admin_email], fail_silently=False)
EmailLog.log_email(admin_email, subject, body, trigger_source=trigger_source, status="success")
except Exception as ex: # noqa: BLE001
logger.exception("Failed to send deletion list to admin %s.", admin_email)
EmailLog.log_email(
admin_email, subject, body, trigger_source=trigger_source, status="failed", error_message=str(ex)
)
time.sleep(settings.EMAIL_SEND_DELAY)
def schedule_inactivity_warning_task():
if not Schedule.objects.filter(func="works.tasks.send_inactivity_warning_emails").exists():
schedule(
"works.tasks.send_inactivity_warning_emails",
schedule_type="W",
repeats=-1,
next_run=_next_monday(),
intended_date_kwarg="scheduled_for",
)
logger.info("Scheduled send_inactivity_warning_emails weekly.")
def schedule_inactivity_deletion_task():
if not Schedule.objects.filter(func="works.tasks.send_inactivity_deletion_list_to_admins").exists():
schedule(
"works.tasks.send_inactivity_deletion_list_to_admins",
schedule_type="W",
repeats=-1,
next_run=_next_monday(),
intended_date_kwarg="scheduled_for",
)
logger.info("Scheduled send_inactivity_deletion_list_to_admins weekly.")
# -----------------------------------------------------------------------------
# External-service token renewal reminders.
# -----------------------------------------------------------------------------
@log_scheduled_catchup
def check_service_token_renewals(trigger_source="scheduled"):
"""Email staff when any external-service refresh token nears expiry.
Generic over every service registered in
``works.utils.service_tokens.get_service_token_specs`` (OpenAIRE today).
A refresh token must be rotated about once a month; this weekly check emails
active staff whenever a token expires within the renewal window (default 9
days), with a link to the provider docs and step-by-step renewal instructions
(Django admin — no SSH). When nothing is due it simply logs and returns.
"""
from works.models import EmailLog, ServiceToken
from works.utils.service_tokens import get_service_token_specs
User = get_user_model()
specs = get_service_token_specs()
logger.info("check_service_token_renewals: checking %d registered service(s).", len(specs))
due = []
for token_row in ServiceToken.objects.filter(service__in=specs.keys()):
if not token_row.refresh_token or not token_row.refresh_token_set_at:
continue
if not token_row.due_for_reminder():
continue
spec = specs[token_row.service]
admin_url = f"{settings.BASE_URL}{reverse(spec.admin_change_viewname, args=[token_row.pk])}"
due.append(
{
"row": token_row,
"label": spec.label,
"days_until_expiry": token_row.days_until_refresh_expiry(),
"expires_at": token_row.refresh_token_expires_at,
"docs_url": spec.docs_url,
"token_page_url": spec.token_page_url,
"admin_url": admin_url,
}
)
if not due:
logger.info("check_service_token_renewals: no tokens due for renewal.")
return
admin_emails = list(
User.objects.filter(is_staff=True, is_active=True).exclude(email="").values_list("email", flat=True)
)
if not admin_emails:
logger.warning("check_service_token_renewals: no staff emails configured.")
return
subject, body = render_email(
"email/service_token_renewal.en.txt",
{"count": len(due), "tokens": due},
)
sent_any = False
for admin_email in admin_emails:
try:
send_mail(subject, body, settings.EMAIL_HOST_USER, [admin_email], fail_silently=False)
EmailLog.log_email(admin_email, subject, body, trigger_source=trigger_source, status="success")
sent_any = True
except Exception as ex: # noqa: BLE001
logger.exception("Failed to send service-token renewal reminder to %s.", admin_email)
EmailLog.log_email(
admin_email, subject, body, trigger_source=trigger_source, status="failed", error_message=str(ex)
)
time.sleep(settings.EMAIL_SEND_DELAY)
# Record when each flagged token was last reminded (informational only).
if sent_any:
reminded_at = timezone.now()
for entry in due:
row = entry["row"]
row.last_reminder_sent_at = reminded_at
row.save(update_fields=["last_reminder_sent_at", "updated_at"])
logger.info("check_service_token_renewals: reminded staff for %d token(s).", len(due))
def schedule_service_token_renewal_check():
if not Schedule.objects.filter(func="works.tasks.check_service_token_renewals").exists():
schedule(
"works.tasks.check_service_token_renewals",
schedule_type="W",
repeats=-1,
next_run=_next_monday(),
intended_date_kwarg="scheduled_for",
)
logger.info("Scheduled check_service_token_renewals weekly.")
# -----------------------------------------------------------------------------
# Country-code backfill sweep (issue #261).
# -----------------------------------------------------------------------------
@log_scheduled_catchup
def backfill_work_countries(trigger_source="scheduled", limit=None, dry_run=False):
"""Link ``Work.countries`` for works that have geometry but no countries yet.
Self-healing catch-up for the on-save signal: fills works saved with
geocoding off, harvested before #261, or whose geometry never matched (the
offline point-in-polygon join is deterministic and cheap, so ocean / no-match
works are simply retried each run). Uses
``works.services.countries.lookup_countries`` — the same helper as the
post-save signal — so multi-country geometries link every intersecting
country and the join method (direct vs. snap) is recorded in provenance.
Emails active staff a summary **only when something changed or errored**
(silent on no-op runs), following the ``check_service_token_renewals``
pattern. Returns the tally dict for callers/tests.
"""
from works.models import Country
from works.services.countries import lookup_countries
from works.utils.provenance import set_block
tally = {"processed": 0, "updated": 0, "multi_country": 0, "no_match": 0, "errors": 0}
# .real() excludes the always-present sentinel row, so this still detects a
# Country table with no real countries loaded yet.
if not Country.objects.real().exists():
logger.warning("backfill_work_countries: Country table empty — run load_countries first; skipping.")
return tally
qs = (
Work.objects.filter(geometry__isnull=False)
.exclude(geometry__isempty=True)
.filter(countries__isnull=True)
.order_by("id")
)
if limit:
qs = qs[:limit]
for work in qs.iterator():
tally["processed"] += 1
# Intermediate progress so a long sweep over thousands of works is
# visible in the Q-cluster log rather than going silent until the end.
if tally["processed"] % 100 == 0:
logger.info(
"backfill_work_countries: progress — processed %d, updated %d, no-match %d, errors %d.",
tally["processed"],
tally["updated"],
tally["no_match"],
tally["errors"],
)
try:
countries, prov = lookup_countries(work.geometry)
except Exception: # noqa: BLE001
logger.exception("backfill_work_countries: lookup failed for work %s.", work.pk)
tally["errors"] += 1
continue
if not countries:
tally["no_match"] += 1
continue
if len(countries) > 1:
tally["multi_country"] += 1
if not dry_run:
work.countries.set(countries)
# Record how the join was made (direct vs. territorial-sea snap).
set_block(work, "countries", prov)
tally["updated"] += 1
logger.info(
"backfill_work_countries: processed %d, updated %d (multi %d), no-match %d, errors %d%s.",
tally["processed"],
tally["updated"],
tally["multi_country"],
tally["no_match"],
tally["errors"],
" (dry-run)" if dry_run else "",
)
if dry_run or not (tally["updated"] or tally["errors"]):
return tally
User = get_user_model()
admin_emails = list(
User.objects.filter(is_staff=True, is_active=True).exclude(email="").values_list("email", flat=True)
)
if not admin_emails:
logger.warning("backfill_work_countries: no staff emails configured; skipping notification.")
return tally
subject, body = render_email(
"email/country_backfill.en.txt",
{"tally": tally, "base_url": settings.BASE_URL},
)
for admin_email in admin_emails:
try:
send_mail(subject, body, settings.EMAIL_HOST_USER, [admin_email], fail_silently=False)
EmailLog.log_email(admin_email, subject, body, trigger_source=trigger_source, status="success")
except Exception as ex: # noqa: BLE001
logger.exception("backfill_work_countries: failed to email %s.", admin_email)
EmailLog.log_email(
admin_email, subject, body, trigger_source=trigger_source, status="failed", error_message=str(ex)
)
time.sleep(settings.EMAIL_SEND_DELAY)
return tally
def schedule_backfill_work_countries():
if not Schedule.objects.filter(func="works.tasks.backfill_work_countries").exists():
schedule(
"works.tasks.backfill_work_countries",
schedule_type="W",
repeats=-1,
# Offset from the other weekly sweeps so they don't all fire at 08:00.
next_run=_next_monday().replace(hour=4),
intended_date_kwarg="scheduled_for",
)
logger.info("Scheduled backfill_work_countries weekly.")
@log_scheduled_catchup
def backfill_work_regions(trigger_source="scheduled", limit=None, dry_run=False):
"""Link ``Work.regions`` for works that have geometry but no regions yet.
The global-region mirror of :func:`backfill_work_countries`: self-healing
catch-up for the on-save signal, filling works saved with geocoding off,
harvested before regions were persisted, or whose geometry never matched
(the offline join is deterministic and cheap, so no-match works are simply
retried each run). Uses ``works.services.regions.lookup_regions`` — the same
helper as the post-save signal — so a coastal work links its continent and
ocean and the join is recorded in provenance.
Emails active staff a summary **only when something changed or errored**
(silent on no-op runs). Returns the tally dict for callers/tests.
"""
from works.models import GlobalRegion
from works.services.regions import lookup_regions
from works.utils.provenance import set_block
tally = {"processed": 0, "updated": 0, "multi_region": 0, "no_match": 0, "errors": 0}
if not GlobalRegion.objects.exists():
logger.warning("backfill_work_regions: GlobalRegion table empty — run load_global_regions first; skipping.")
return tally
from works.views_regions import NOT_MANUAL_REGION
qs = (
Work.objects.filter(geometry__isnull=False)
.exclude(geometry__isempty=True)
.filter(regions__isnull=True)
# Skip works a curator decided manually (assigned a region, or marked
# "will not be matched" with zero regions) so the sweep does not undo it.
.filter(NOT_MANUAL_REGION)
.order_by("id")
)
if limit:
qs = qs[:limit]
touched_regions = set()
for work in qs.iterator():
tally["processed"] += 1
if tally["processed"] % 100 == 0:
logger.info(
"backfill_work_regions: progress — processed %d, updated %d, no-match %d, errors %d.",
tally["processed"],
tally["updated"],
tally["no_match"],
tally["errors"],
)
try:
regions, prov = lookup_regions(work.geometry)
except Exception: # noqa: BLE001
logger.exception("backfill_work_regions: lookup failed for work %s.", work.pk)
tally["errors"] += 1
continue
if not regions:
tally["no_match"] += 1
continue
if len(regions) > 1:
tally["multi_region"] += 1
if not dry_run:
work.regions.set(regions)
set_block(work, "regions", prov)
touched_regions.update(regions)
tally["updated"] += 1
if touched_regions:
from works.views_regions import invalidate_region_page_cache
for region in touched_regions:
invalidate_region_page_cache(region)
logger.info(
"backfill_work_regions: processed %d, updated %d (multi %d), no-match %d, errors %d%s.",
tally["processed"],
tally["updated"],
tally["multi_region"],
tally["no_match"],
tally["errors"],
" (dry-run)" if dry_run else "",
)
if dry_run or not (tally["updated"] or tally["errors"]):
return tally
User = get_user_model()
admin_emails = list(
User.objects.filter(is_staff=True, is_active=True).exclude(email="").values_list("email", flat=True)
)
if not admin_emails:
logger.warning("backfill_work_regions: no staff emails configured; skipping notification.")