forked from ifgi/optimetaPortal
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathviewsets.py
More file actions
1911 lines (1734 loc) · 90.2 KB
/
Copy pathviewsets.py
File metadata and controls
1911 lines (1734 loc) · 90.2 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
"""publications API views."""
import logging
import os
import shutil
import tempfile
import uuid
import zipfile
from pathlib import Path
# Import geoextent at module level
import geoextent.lib.extent as geoextent
from django.conf import settings
from django.contrib.gis.geos import Point, Polygon
from django.db.models import Case, Count, IntegerField, Q, Value, When
from django_q.humanhash import humanize
from django_q.tasks import async_task
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import (
OpenApiExample,
OpenApiParameter,
OpenApiResponse,
extend_schema,
extend_schema_view,
inline_serializer,
)
from rest_framework import serializers as drf_serializers
from rest_framework import status, viewsets
from rest_framework.decorators import action
from rest_framework.permissions import AllowAny, IsAuthenticated, IsAuthenticatedOrReadOnly
from rest_framework.renderers import BrowsableAPIRenderer, JSONRenderer
from rest_framework.response import Response
from rest_framework.throttling import UserRateThrottle
from rest_framework_gis import filters
from .models import Author, Collection, Country, GlobalRegion, Source, Subscription, Work
from .serializers import (
AuthorSerializer,
CollectionSerializer,
ContributeDoiSerializer,
CountrySerializer,
GeoextentBatchSerializer,
GeoextentExtractSerializer,
GeoextentExtractTextSerializer,
GeoextentRemoteGetSerializer,
GeoextentRemoteSerializer,
GlobalRegionSerializer,
SourceSerializer,
SubscriptionSerializer,
WorkMinimalSerializer,
WorkSerializer,
)
from .utils.geometry import annotate_rounded_geometry
from .utils.provenance import append_event, public_subset
logger = logging.getLogger(__name__)
# Reusable error-response schema. Most error paths in this module return
# `{"error": "<message>"}` (and sometimes also `{"details": "<…>"}`); a
# couple of validation paths fall back to DRF's serializer-error envelope.
# Schema-wise both fit `additionalProperties: true`, so a single shape covers them.
_ERROR_RESPONSE = inline_serializer(
name="ErrorResponse",
fields={
"error": drf_serializers.CharField(),
"details": drf_serializers.CharField(required=False),
},
)
class ContributeDoiThrottle(UserRateThrottle):
"""Per-user rate limit for the contribute-by-DOI endpoint.
Each new DOI triggers external API calls (Crossref + OpenAlex + OpenAIRE),
so cap how often an authenticated user can submit. Rate is configured under
the ``contribute_doi`` scope in ``REST_FRAMEWORK['DEFAULT_THROTTLE_RATES']``.
"""
scope = "contribute_doi"
class _GeoJSONRenderer(JSONRenderer):
"""Sets Content-Type: application/geo+json per W3C SDW-BP 5."""
media_type = "application/geo+json"
format = "geo+json"
@extend_schema_view(
list=extend_schema(
summary="List harvested data sources",
tags=["Sources"],
responses={200: SourceSerializer},
),
retrieve=extend_schema(
summary="Retrieve a source by ID",
tags=["Sources"],
responses={
200: SourceSerializer,
404: OpenApiResponse(_ERROR_RESPONSE, description="No source with this ID."),
},
),
)
class SourceViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Source.objects.all()
serializer_class = SourceSerializer
permission_classes = [AllowAny]
@extend_schema_view(
list=extend_schema(
summary="List published works (paginated GeoJSON)",
description=(
"Returns published works as a GeoJSON `FeatureCollection`. Admins additionally "
"see drafts and harvested-but-unpublished works. Filter the spatial slice with "
"`?in_bbox=west,south,east,north`.\n\n"
"Pass `?minimal=true` to receive only `id`, `title`, `doi`, `status`, "
"`status_display`, and `geometry` — the reduced payload is used by the map "
"for chunked loading; full details are fetched lazily per work.\n\n"
"Pass `?author_orcid=<orcid>` to filter by a specific author's bare ORCID iD "
"(e.g. `0000-0002-1825-0097`). Only works linked to that author are returned."
),
tags=["Works"],
parameters=[
OpenApiParameter(
name="author_orcid",
type=OpenApiTypes.STR,
location=OpenApiParameter.QUERY,
required=False,
description=(
"Filter to works linked to a specific author by their bare ORCID iD "
"(e.g. `0000-0002-1825-0097`). Invalid or unknown ORCIDs return an empty result set."
),
examples=[
OpenApiExample(
name="filter by ORCID",
value="0000-0002-1825-0097",
)
],
),
],
),
retrieve=extend_schema(
summary="Retrieve a work by numeric ID",
description="See the work landing page (`/work/<id>/`) for the human-readable view.",
tags=["Works"],
responses={
200: WorkSerializer,
404: OpenApiResponse(
_ERROR_RESPONSE,
description="No work with this ID, or the work is not yet published and the request is anonymous.",
),
},
),
)
class WorkViewSet(viewsets.ReadOnlyModelViewSet):
bbox_filter_field = "geometry"
filter_backends = (filters.InBBoxFilter,)
serializer_class = WorkSerializer
permission_classes = [IsAuthenticatedOrReadOnly]
renderer_classes = [_GeoJSONRenderer, JSONRenderer, BrowsableAPIRenderer]
def get_serializer_class(self):
if self.request.query_params.get("minimal") == "true":
return WorkMinimalSerializer
return WorkSerializer
def retrieve(self, request, *args, **kwargs):
"""302-redirect a merged-away duplicate's detail to the canonical work.
Redirected works (``status='r'``) are excluded from ``get_queryset``, so a
normal lookup would 404. Resolve the pk directly and, unless
``?include=redirected`` is set, send clients to the canonical detail URL.
"""
qp = getattr(request, "query_params", request.GET)
if qp.get("include") != "redirected":
pk = kwargs.get(self.lookup_field or "pk")
work = Work.objects.filter(pk=pk).first()
if work is not None and work.status == "r":
canonical = work.canonical_work()
if canonical.id != work.id:
from django.shortcuts import redirect
from django.urls import reverse
return redirect(reverse("optimap:works:work-detail", args=[canonical.id]))
return super().retrieve(request, *args, **kwargs)
def get_queryset(self):
"""
Return all publications for admin users, only published ones for others.
Sorted by creation date (newest first) to match the works list page.
For the ``provenance`` action: curators can access works in their
collections at any publication status (not just published ones), so
they can view provenance for harvested/contributed/draft works too.
"""
# query_params is a DRF-only attribute; fall back to .GET for plain WSGIRequests.
qp = getattr(self.request, "query_params", self.request.GET)
# Merged-away duplicates (status='r') are tombstones for redirect only —
# never list them, unless explicitly requested for inspection.
include_redirected = qp.get("include") == "redirected"
if self.request.user.is_authenticated and self.request.user.is_staff:
qs = Work.objects.all().distinct()
if not include_redirected:
qs = qs.exclude(status="r")
if qp.get("minimal") == "true":
# For map loading, put published works (which have geometry) first so
# markers appear in the first chunk instead of at the end of 4k harvested ones.
qs = qs.annotate(
_status_priority=Case(
When(status="p", then=Value(0)),
default=Value(1),
output_field=IntegerField(),
)
).order_by("_status_priority", "-creationDate", "-id")
else:
qs = qs.order_by("-creationDate", "-id")
qs = annotate_rounded_geometry(qs).prefetch_related("countries", "regions", "relations_from__to_work")
author_orcid_staff = qp.get("author_orcid")
if author_orcid_staff:
from works.utils.orcid import normalize_orcid
normalized = normalize_orcid(author_orcid_staff)
if normalized:
qs = qs.filter(author_links__orcid=normalized)
return qs
if getattr(self, "action", None) == "provenance" and self.request.user.is_authenticated:
curated = Work.objects.filter(collections__curators=self.request.user)
public = Work.objects.filter(status="p")
qs = (curated | public).distinct()
if not include_redirected:
qs = qs.exclude(status="r")
return annotate_rounded_geometry(qs).prefetch_related("countries", "regions", "relations_from__to_work")
public = Work.objects.filter(status="p").order_by("-creationDate", "-id").distinct()
qs = annotate_rounded_geometry(public).prefetch_related("countries", "regions", "relations_from__to_work")
author_orcid = qp.get("author_orcid")
if author_orcid:
from works.utils.orcid import normalize_orcid
normalized = normalize_orcid(author_orcid)
if normalized:
qs = qs.filter(author_links__orcid=normalized)
return qs
@extend_schema(
summary="Retrieve provenance for a work",
tags=["Works"],
description=(
"Returns the structured provenance record for a work — where it was harvested from, "
"per-field metadata attribution, OpenAlex enrichment result, reverse-geocoding details, "
"and a chronological audit log of re-harvest/contribution/publish events.\n\n"
"**Access tiers:**\n"
"- **Staff** and **curators of any collection this work belongs to** receive the full "
"provenance, including `harvest.original_record`, `openalex_match.top_candidate`, "
"and `user_id` / `user_email` fields in events.\n"
"- **All other callers** (including anonymous users) receive the public subset with "
"those keys removed.\n\n"
"**`harvest` keys:**\n"
"| Key | Type | Description |\n"
"|-----|------|-------------|\n"
"| `harvester` | string | Task function name: `harvest_oai_endpoint`, `harvest_rss_endpoint`, `harvest_crossref_prefix`, `harvest_mountain_wetlands`, `harvest_openalex_source` |\n"
"| `source_name` | string | Display name of the source |\n"
"| `source_type` | string | One of: `oai-pmh`, `ojs`, `janeway`, `rss`, `crossref-prefix`, `mountain-wetlands`, `openalex` |\n"
"| `source_url` | string | Harvest endpoint URL |\n"
"| `harvested_at` | string | ISO 8601 timestamp of the harvest |\n"
"| `harvesting_event_id` | integer | FK to the `HarvestingEvent` record |\n"
"| `doi` | string | DOI as recorded at harvest time |\n"
"| `original_record` | object | Raw upstream record (staff/curators only) |\n\n"
"**`metadata_sources` keys and values:**\n"
"Each key names a Work field; the value names where that field's data came from.\n"
"| Key | Possible values |\n"
"|-----|-----------------|\n"
"| `abstract` | `crossref`, `openaire`, `synthesised` / `synthesised+datacite.descriptions` (IGSN samples — machine-composed, see the `sample` block) |\n"
"| `authors` | `original_source`, `openalex`, `crossref`, `openaire`, `datacite.creators` (IGSN sample collector) |\n"
"| `keywords` | `original_source`, `openalex`, `openaire`, `datacite.subjects` (IGSN sample materials) |\n"
"| `topics` | `openalex` |\n"
"| `type` | `openalex` |\n"
"| `title` | `datacite.title` (IGSN local sample number) |\n"
"| `placename` | `datacite.geoLocationPlace`, `gfz.landing_page` (IGSN samples; else set by Nominatim reverse-geocoding, recorded under `geocoding`) |\n"
"| `geometry` | `DC.SpatialCoverage`, `DC.box`, `link rel=alternate geo+json`, `study_sites`, `datacite.geoLocations`, `gfz.landing_page`, `reharvest_html` (re-extracted from the landing page by the admin re-harvest) |\n"
"| `timeperiod` | `datacite.dates[Collected]`, `reharvest_html` (re-extracted from the landing page by the admin re-harvest) |\n"
"| `doi` | `original_source`, `openalex` |\n"
"| `date` | `original_source (year-only)` |\n"
"| `volume` / `issue` / `first_page` / `last_page` | `openalex`, `openaire` |\n"
"| `language` | `openaire` |\n"
"| `publisher` | `openaire`, `datacite.publisher` (IGSN registrant) |\n"
"| `biblio` | `crossref` (volume/issue/pages from Crossref in one batch) |\n"
"| `openalex_metadata` | `openalex` (any OpenAlex enrichment was applied) |\n"
"| `openalex_doi_version_fallback` | `{queried_doi, matched_doi}` dict — present when the work's versioned DOI (e.g. `/v2`) was not found in OpenAlex and enrichment succeeded via the bare DOI or an earlier version (e.g. `/v1`) |\n"
"| `openalex` | `primary` (work was harvested directly from OpenAlex as the primary source) |\n"
"| `author_orcids` | `openalex`, `openaire` (source that supplied the ORCID links written to the Author M2M) |\n\n"
"**`sample` block** (IGSN physical samples only, #187):\n"
"| Key | Type | Description |\n"
"|-----|------|-------------|\n"
"| `resource_type` | string | DataCite `types.resourceType` — the specific sample kind (`Specimen`, `Core`, `Cuttings`, `material sample`, …) |\n"
"| `materials` | array | DataCite `subjects` (also copied to `Work.keywords`) |\n"
"| `repositories` | array | DataCite `contributors` — hosting/curating institutions |\n"
"| `place` | string | DataCite `geoLocationPlace` (or a scraped place) |\n"
"| `description` | object | `synthesised` (bool), `synthesised_from` (array of the fields used to compose the abstract), `source_description_appended` (bool — whether a real DataCite `descriptions` value was appended after the synthesised sentence) |\n\n"
"**`openalex_match` keys:**\n"
"| Key | Type | Description |\n"
"|-----|------|-------------|\n"
"| `status` | string | `verified`, `unverified`, `none`, or `skipped` (skipped means the primary source already supplied DOI + authors) |\n"
"| `score` | number | Confidence score 0.0–1.0 (absent when status is `none` or `skipped`) |\n"
"| `matched_id` | string | OpenAlex work URL, e.g. `https://openalex.org/W2741809807` |\n"
"| `top_candidate` | object | Raw OpenAlex API response for the best candidate (staff/curators only; only present when status is `unverified`) |\n\n"
"**`openaire_match` keys:**\n"
"| Key | Type | Description |\n"
"|-----|------|-------------|\n"
"| `status` | string | `matched` (an OpenAIRE record was found for the DOI) or `none`. Recorded for every DOI-bearing work checked by the post-harvest sweep, even when nothing was filled |\n"
"| `openaire_id` | string | OpenAIRE internal id, e.g. `doi_dedup___::…` (present when matched) |\n"
"| `url` | string | Public OpenAIRE Explore page for the matched record, e.g. `https://explore.openaire.eu/search/result?id=doi_dedup___::…` (present when matched) |\n"
"| `num_found` | integer | Number of OpenAIRE records found for the DOI |\n\n"
"**`geocoding` keys:**\n"
"| Key | Type | Description |\n"
"|-----|------|-------------|\n"
"| `gazetteer` | string | Always `nominatim` |\n"
"| `placename` | string | Human-readable location hierarchy, e.g. `Sulawesi, Indonesia` |\n"
"| `n_geocoded` | integer | Number of geometry points successfully reverse-geocoded |\n"
"| `geocoded_at` | string | ISO 8601 timestamp |\n"
"| `matches` | array | Per-point Nominatim results (display name, OSM type/id/url, lat, lon) |\n\n"
"**`countries` keys** (offline point-in-polygon join behind the `Work.countries` M2M):\n"
"| Key | Type | Description |\n"
"|-----|------|-------------|\n"
"| `source` | string | Outline dataset (`natural_earth`), or `manual` for a staff curation decision |\n"
"| `method` | string | `intersects` (geometry directly intersects an outline) or `buffer_snap` (matched only after buffering — coastal/island works just outside the simplified outline); `curator_assigned` or `curator_excluded` when `source` is `manual` |\n"
"| `snap_tolerance_degrees` | number | Buffer applied for the snap, in degrees (e.g. `0.12` ≈ 12 nautical miles); present only when `method` is `buffer_snap` |\n"
"| `iso_codes` | array | ISO 3166-1 alpha-2 codes of the matched countries (empty for `curator_excluded`) |\n"
"| `assigned_at` | string | ISO 8601 timestamp (automated joins) |\n"
"| `decided_by` | integer | Staff user id; present only when `source` is `manual` |\n"
"| `decided_at` | string | ISO 8601 timestamp; present only when `source` is `manual` |\n\n"
"**`regions` keys** (offline point-in-polygon join behind the `Work.regions` M2M):\n"
"| Key | Type | Description |\n"
"|-----|------|-------------|\n"
"| `source` | string | Outline dataset (`global_regions`), or `manual` for a curator decision |\n"
"| `method` | string | `intersects` (geometry directly intersects a continent/ocean outline; no buffer-snap); `curator_assigned` or `curator_excluded` when `source` is `manual` |\n"
"| `regions` | array | Matched regions as `{name, region_type}` objects (`region_type` is `Continent` or `Ocean`; empty for `curator_excluded`) |\n"
"| `assigned_at` | string | ISO 8601 timestamp (automated join only) |\n"
"| `decided_by` / `decided_at` | int / string | Staff user id and ISO 8601 timestamp of a manual decision |\n\n"
"**`events` — event types:**\n"
"| `type` | Extra fields | Description |\n"
"|--------|-------------|-------------|\n"
"| `harvest_update` | `harvesting_event_id` | Recorded each time an existing work is re-harvested |\n"
"| `reharvest_source_extents` | `geometry`, `temporal` (each `updated` when present) | Admin re-harvest re-extracted geometry / temporal extent from the landing page and overrode the stored value (only for values not user-contributed) |\n"
"| `doi_backfill` | `doi`, `harvesting_event_id` | DOI was added to a previously DOI-less work |\n"
"| `doi_contribution` | `doi`, `user_id`\\*, `user_email`\\* | A user added this work to OPTIMAP by submitting its DOI on /contribute/ (harvested from Crossref + enriched) |\n"
"| `contribution` | `kinds` (array: `spatial`, `temporal`, `bok`), `user_id`\\*, `user_email`\\*, `game` (bool, optional) | User added spatial/temporal/BoK metadata; `game: true` when submitted via the georeferencing game |\n"
"| `publish` | `status_from`, `status_to`, `user_id`\\*, `user_email`\\* | Work was published |\n"
"| `unpublish` | `status_from`, `user_id`\\*, `user_email`\\* | Work was unpublished |\n"
"| `source_migration` | `from_source`, `to_source` | Work was reassigned to a different `Source` by the `migrate_source_works` management command |\n"
"| `openaire_enrich` | `openaire_id`, `doi`, `source_url`, `fields_filled` (array), `fields_offered_not_applied` (array) | OpenAIRE enrichment ran; `fields_filled` were empty and were populated, `fields_offered_not_applied` had an OpenAIRE value but a value already existed (kept under the fill-if-empty policy) |\n"
'| `country_curation` | `decision` (`assigned`/`excluded`), `iso_codes` (array, for `assigned`), `user_id`\\*, `user_email`\\* | Staff manually assigned one or more countries, or marked the work "will not be matched", on the /countries curation section |\n'
'| `region_curation` | `decision` (`assigned`/`excluded`), `regions` (array, for `assigned`), `region` (single-region path only), `user_id`\\*, `user_email`\\* | Staff manually assigned one or more global regions, or marked the work "will not be matched", on the /regions curation section |\n'
"| `author_link` | `source` (`openalex`/`openaire`), `linked` (integer — number of Author rows linked), `orcids` (array of bare ORCIDs) | Author ORCID iDs were linked to the work via the Author M2M |\n"
"| `geometry_repair` | `method` (`make_valid`) | A topologically invalid stored geometry was repaired with GEOS `make_valid` (PostGIS `ST_MakeValid`) on save |\n\n"
"\\* `user_id` and `user_email` are present for staff and curators only.\n\n"
"**Other top-level keys:**\n"
"| Key | Type | Description |\n"
"|-----|------|-------------|\n"
"| `publication_notified_at` | string | ISO 8601 timestamp of when the publication notification email was sent to the contributor (suppresses duplicate sends on republish) |"
),
responses={
200: inline_serializer(
name="ProvenanceResponse",
fields={
"harvest": drf_serializers.DictField(
required=False,
help_text=(
"How and when this work was harvested. "
"Keys: harvester, source_name, source_type, source_url, "
"harvested_at, harvesting_event_id, doi. "
"Staff/curators also see original_record (raw upstream payload)."
),
),
"metadata_sources": drf_serializers.DictField(
required=False,
help_text=(
"Per-field attribution map. Keys name Work fields; values name their source. "
"Known keys: title, abstract, authors, keywords, topics, type, geometry, placename, doi, date, "
"volume, issue, first_page, last_page, language, publisher, biblio, openalex_metadata, openalex, author_orcids. "
"Known values: original_source, openalex, openaire, crossref, DC.SpatialCoverage, "
"DC.box, link rel=alternate geo+json, study_sites, "
"datacite.title, datacite.creators, datacite.subjects, datacite.publisher, datacite.geoLocations, "
"datacite.geoLocationPlace, datacite.dates[Collected], gfz.landing_page, "
"synthesised, synthesised+datacite.descriptions, original_source (year-only), primary."
),
),
"sample": drf_serializers.DictField(
required=False,
help_text=(
"IGSN physical-sample metadata (#187). Keys: resource_type, materials, "
"repositories, place, description (synthesised / synthesised_from / "
"source_description_appended). See the metadata_sources section above."
),
),
"openalex_match": drf_serializers.DictField(
required=False,
help_text=(
"OpenAlex enrichment result. "
"Keys: status (verified/unverified/none/skipped), score (0.0–1.0), matched_id. "
"Staff/curators also see top_candidate."
),
),
"openaire_match": drf_serializers.DictField(
required=False,
help_text=(
"OpenAIRE enrichment result. "
"Keys: status (matched/none), openaire_id, url, num_found. "
"See the openaire_enrich event for the fields filled/offered."
),
),
"geocoding": drf_serializers.DictField(
required=False,
help_text=(
"Reverse-geocoding via Nominatim. "
"Keys: gazetteer, placename, n_geocoded, geocoded_at, matches."
),
),
"countries": drf_serializers.DictField(
required=False,
help_text=(
"Offline point-in-polygon country join (Work.countries M2M), or a staff "
"curation decision. Keys: source (natural_earth/manual), method "
"(intersects/buffer_snap/curator_assigned/curator_excluded), "
"snap_tolerance_degrees (only for buffer_snap), iso_codes, assigned_at, "
"decided_by/decided_at (manual only)."
),
),
"regions": drf_serializers.DictField(
required=False,
help_text=(
"Offline point-in-polygon global-region join (Work.regions M2M), "
"or a manual staff curation decision. "
"Keys: source (global_regions/manual), method "
"(intersects/curator_assigned/curator_excluded), "
"regions (array of {name, region_type}), assigned_at, decided_by, decided_at."
),
),
"dedup": drf_serializers.DictField(
required=False,
help_text=(
"Present on a canonical work that absorbed duplicates — either siblings sharing its "
"OpenAlex id, or ESSOAr/Authorea per-version DOIs sharing its versionless DOI base. "
"Keys: openalex_id (null for version dedup), merged_work_ids, merged_identifiers, "
"method (openalex_id/doi_version), "
"primary_basis (openalex_primary_location/version_rank/existing/doi_version), at. "
"An optional dedup_conflict list records non-primary geometry/temporal extents "
"that differed from the canonical's (kept for audit)."
),
),
"redirect": drf_serializers.DictField(
required=False,
help_text=(
"Present on a merged-away duplicate (work status='r'). "
"Keys: canonical_work_id, canonical_identifier, openalex_id, at. "
"Requests for this work's identifiers 302-redirect to the canonical work."
),
),
"events": drf_serializers.ListField(
child=drf_serializers.DictField(),
required=False,
help_text=(
"Chronological audit log. Each event has type (string) and at (ISO timestamp). "
"Event types: harvest_update, reharvest_source_extents, doi_backfill, doi_contribution, "
"contribution, publish, unpublish, source_migration, openaire_enrich, dedup_merge, dedup_unmerge, author_link, geometry_repair. "
"user_id and user_email are present for staff/curators only."
),
),
"publication_notified_at": drf_serializers.CharField(
required=False,
help_text="ISO 8601 timestamp of when the publication notification email was sent to the contributor.",
),
},
),
404: OpenApiResponse(
_ERROR_RESPONSE,
description="No work with this ID, or not yet published and the caller is anonymous.",
),
},
examples=[
OpenApiExample(
name="OAI-PMH work with OpenAlex enrichment (public response)",
summary="Typical response for anonymous/regular-user callers",
description=(
"A work harvested from an OAI-PMH journal, enriched by OpenAlex, "
"with a user-contributed geometry. Private keys (original_record, "
"top_candidate, user_id, user_email) are absent."
),
value={
"harvest": {
"harvester": "harvest_oai_endpoint",
"source_name": "Earth System Science Data",
"source_type": "oai-pmh",
"source_url": "https://essd.copernicus.org/oai/",
"harvested_at": "2026-04-30T12:00:00+00:00",
"harvesting_event_id": 42,
"doi": "10.5194/essd-16-1234-2024",
},
"metadata_sources": {
"authors": "openalex",
"author_orcids": "openalex",
"keywords": "original_source",
"topics": "openalex",
"geometry": "DC.SpatialCoverage",
"volume": "openalex",
"issue": "openalex",
},
"openalex_match": {
"status": "verified",
"score": 0.97,
"matched_id": "https://openalex.org/W2741809807",
},
"geocoding": {
"gazetteer": "nominatim",
"placename": "Sulawesi, Indonesia",
"n_geocoded": 2,
"geocoded_at": "2026-04-30T12:00:05+00:00",
},
"countries": {
"source": "natural_earth",
"method": "intersects",
"iso_codes": ["ID"],
"assigned_at": "2026-04-30T12:00:06+00:00",
},
"regions": {
"source": "global_regions",
"method": "intersects",
"regions": [{"name": "Asia", "region_type": "Continent"}],
"assigned_at": "2026-04-30T12:00:07+00:00",
},
"events": [
{
"type": "harvest_update",
"at": "2026-05-15T08:00:00+00:00",
"harvesting_event_id": 51,
},
{
"type": "contribution",
"at": "2026-05-01T09:15:00+00:00",
"kinds": ["spatial"],
},
{
"type": "publish",
"at": "2026-05-02T14:30:00+00:00",
"status_from": "c",
"status_to": "p",
},
],
"publication_notified_at": "2026-05-02T14:30:01+00:00",
},
response_only=True,
status_codes=["200"],
),
OpenApiExample(
name="MaRESS work (full response, staff/curator)",
summary="Full provenance returned to staff or curators — includes private keys",
description=(
"A work harvested from the Mountain Wetlands Repository (MaRESS API). "
"The geometry comes from study-site coordinates in the API record. "
"Includes original_record and user_id which are stripped for public callers."
),
value={
"harvest": {
"harvester": "harvest_mountain_wetlands",
"source_name": "Mountain Wetlands Repository",
"source_type": "mountain-wetlands",
"source_url": "https://andes.mountain-wetlands-repository.info/api/v1/items/",
"harvested_at": "2026-03-10T06:30:00+00:00",
"harvesting_event_id": 17,
"doi": "10.5281/zenodo.7654321",
"original_record": {
"id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
"title": "Wetland extent Himalayan foothills 1990–2020",
"date": "2023",
"authors": [{"name": "Smith, J."}, {"name": "Patel, R."}],
},
},
"metadata_sources": {
"authors": "original_source",
"geometry": "study_sites",
"date": "original_source (year-only)",
"doi": "original_source",
"topics": "openalex",
},
"openalex_match": {
"status": "verified",
"score": 0.91,
"matched_id": "https://openalex.org/W3128445612",
},
"geocoding": {
"gazetteer": "nominatim",
"placename": "Uttarakhand, India",
"n_geocoded": 5,
"geocoded_at": "2026-03-10T06:30:10+00:00",
},
"countries": {
"source": "natural_earth",
"method": "buffer_snap",
"snap_tolerance_degrees": 0.12,
"iso_codes": ["IN"],
"assigned_at": "2026-03-10T06:30:11+00:00",
},
"regions": {
"source": "global_regions",
"method": "intersects",
"regions": [{"name": "Asia", "region_type": "Continent"}],
"assigned_at": "2026-03-10T06:30:12+00:00",
},
"events": [
{
"type": "contribution",
"at": "2026-03-12T11:00:00+00:00",
"kinds": ["temporal"],
"user_id": 7,
"user_email": "curator@example.org",
},
{
"type": "publish",
"at": "2026-03-13T09:00:00+00:00",
"status_from": "c",
"status_to": "p",
"user_id": 1,
"user_email": "admin@optimap.science",
},
],
},
response_only=True,
status_codes=["200"],
),
],
)
@action(detail=True, url_path="provenance", methods=["get"], permission_classes=[AllowAny])
def provenance(self, request, pk=None):
work = self.get_object()
is_privileged = request.user.is_authenticated and (
request.user.is_staff or work.collections.filter(curators=request.user).exists()
)
data = work.provenance if is_privileged else public_subset(work.provenance or {})
response = Response(data)
if request.user.is_authenticated:
response["Cache-Control"] = "private, no-store"
else:
response["Cache-Control"] = "public, max-age=3600"
return response
@extend_schema(
summary="Contribute a new work by DOI",
tags=["Contribute"],
description=(
"Add a publication to OPTIMAP by its DOI. Requires authentication.\n\n"
"The DOI may be bare (`10.5194/example`) or a resolver URL "
"(`https://doi.org/10.5194/example`); it is normalized and validated server-side.\n\n"
"- **If the DOI already exists**, returns `200` with `exists: true` and the existing "
"work's `work_url` so the client can redirect to it.\n"
"- **If the DOI is new**, it is harvested from Crossref and enriched (OpenAlex + OpenAIRE) "
"synchronously, attached to the dedicated *User contributions* source, recorded in the "
"work's provenance (`doi_contribution` event) and on the recognition board, then returned "
"with `201` and `created: true`.\n\n"
"Rate-limited per user (`contribute_doi` scope) because each new DOI triggers external "
"API calls."
),
request=ContributeDoiSerializer,
responses={
201: OpenApiResponse(
inline_serializer(
name="ContributeDoiCreatedResponse",
fields={
"exists": drf_serializers.BooleanField(),
"created": drf_serializers.BooleanField(),
"work_id": drf_serializers.IntegerField(),
"doi": drf_serializers.CharField(),
"work_url": drf_serializers.CharField(),
},
),
description="A new work was harvested and created.",
),
200: OpenApiResponse(
inline_serializer(
name="ContributeDoiExistsResponse",
fields={
"exists": drf_serializers.BooleanField(),
"work_id": drf_serializers.IntegerField(),
"doi": drf_serializers.CharField(),
"work_url": drf_serializers.CharField(),
},
),
description="A work with this DOI already exists; redirect the user to it.",
),
400: OpenApiResponse(_ERROR_RESPONSE, description="The DOI is missing or not syntactically valid."),
403: OpenApiResponse(_ERROR_RESPONSE, description="Authentication credentials were not provided."),
404: OpenApiResponse(_ERROR_RESPONSE, description="Crossref has no record for this DOI."),
429: OpenApiResponse(_ERROR_RESPONSE, description="Rate limit exceeded for DOI contributions."),
},
)
@action(
detail=False,
methods=["post"],
url_path="contribute-doi",
permission_classes=[IsAuthenticated],
throttle_classes=[ContributeDoiThrottle],
)
def contribute_doi(self, request):
from django.urls import reverse
from .harvesting.crossref import harvest_crossref_doi
from .models import Contribution
def landing_url(work):
return reverse("optimap:work-landing", args=[work.get_identifier()])
serializer = ContributeDoiSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
doi = serializer.validated_data["doi"]
existing = Work.objects.filter(doi__iexact=doi).first()
if existing is not None:
return Response(
{
"exists": True,
"work_id": existing.id,
"doi": existing.doi,
"work_url": landing_url(existing),
},
status=status.HTTP_200_OK,
)
work, action_taken = harvest_crossref_doi(doi, user=request.user)
if action_taken == "not_found" or work is None:
return Response(
{"error": f"Crossref has no record for DOI '{doi}'."},
status=status.HTTP_404_NOT_FOUND,
)
if action_taken == "exists":
# Raced with a concurrent submission, or the DOI differs only in case.
return Response(
{
"exists": True,
"work_id": work.id,
"doi": work.doi,
"work_url": landing_url(work),
},
status=status.HTTP_200_OK,
)
# The harvest may have auto-merged this DOI with an existing version of
# the same work (shared OpenAlex id) — e.g. the user added a preprint DOI
# for an article we already hold. Re-fetch and follow to the canonical row
# so the contribution and response attach to the surviving work.
work = Work.objects.get(pk=work.pk).canonical_work()
# Record the contribution: provenance event + recognition-board row.
append_event(
work,
"doi_contribution",
user_id=request.user.id,
user_email=request.user.email,
doi=work.doi,
)
work.save(update_fields=["provenance", "lastUpdate"])
Contribution.objects.create(user=request.user, work=work, kind=Contribution.DOI)
logger.info("User %s contributed new work %s via DOI %s", request.user, work.id, work.doi)
return Response(
{
"exists": False,
"created": True,
"work_id": work.id,
"doi": work.doi,
"work_url": landing_url(work),
},
status=status.HTTP_201_CREATED,
)
_SUBSCRIPTION_AUTH_RESPONSES = {
401: OpenApiResponse(_ERROR_RESPONSE, description="Authentication credentials were not provided."),
403: OpenApiResponse(
_ERROR_RESPONSE, description="Authenticated user is not allowed to access this subscription."
),
}
@extend_schema_view(
list=extend_schema(
summary="List the current user's subscriptions",
tags=["Subscriptions"],
responses={200: SubscriptionSerializer(many=True), **_SUBSCRIPTION_AUTH_RESPONSES},
),
create=extend_schema(
summary="Create a new subscription",
tags=["Subscriptions"],
responses={
201: SubscriptionSerializer,
400: OpenApiResponse(_ERROR_RESPONSE, description="Invalid payload (validation error)."),
**_SUBSCRIPTION_AUTH_RESPONSES,
},
),
retrieve=extend_schema(
summary="Retrieve a subscription by ID",
tags=["Subscriptions"],
responses={
200: SubscriptionSerializer,
404: OpenApiResponse(
_ERROR_RESPONSE, description="No subscription with this ID owned by the current user."
),
**_SUBSCRIPTION_AUTH_RESPONSES,
},
),
update=extend_schema(
summary="Replace a subscription",
tags=["Subscriptions"],
responses={
200: SubscriptionSerializer,
400: OpenApiResponse(_ERROR_RESPONSE, description="Invalid payload (validation error)."),
404: OpenApiResponse(
_ERROR_RESPONSE, description="No subscription with this ID owned by the current user."
),
**_SUBSCRIPTION_AUTH_RESPONSES,
},
),
partial_update=extend_schema(
summary="Patch a subscription",
tags=["Subscriptions"],
responses={
200: SubscriptionSerializer,
400: OpenApiResponse(_ERROR_RESPONSE, description="Invalid payload (validation error)."),
404: OpenApiResponse(
_ERROR_RESPONSE, description="No subscription with this ID owned by the current user."
),
**_SUBSCRIPTION_AUTH_RESPONSES,
},
),
destroy=extend_schema(
summary="Delete a subscription",
tags=["Subscriptions"],
responses={
204: OpenApiResponse(description="Subscription deleted."),
404: OpenApiResponse(
_ERROR_RESPONSE, description="No subscription with this ID owned by the current user."
),
**_SUBSCRIPTION_AUTH_RESPONSES,
},
),
)
class SubscriptionViewSet(viewsets.ModelViewSet):
"""
Subscription view set.
Each user can list, create, update, or delete their own Subscriptions.
"""
bbox_filter_field = "region"
filter_backends = (filters.InBBoxFilter,)
serializer_class = SubscriptionSerializer
permission_classes = [IsAuthenticatedOrReadOnly]
def get_queryset(self):
user = self.request.user
return Subscription.objects.filter(user=user)
def perform_create(self, serializer):
serializer.save(user=self.request.user)
@extend_schema_view(
list=extend_schema(
summary="List global regions (continents + oceans)",
description=(
"Continent and ocean polygons used by region-filtered feeds and subscriptions. "
"Region slugs in this response are the ones to use in `/api/v1/feeds/optimap-<slug>.rss`."
),
tags=["Global regions"],
),
retrieve=extend_schema(
summary="Retrieve a global region by ID",
tags=["Global regions"],
responses={
200: GlobalRegionSerializer,
404: OpenApiResponse(_ERROR_RESPONSE, description="No global region with this ID."),
},
),
)
class GlobalRegionViewSet(viewsets.ReadOnlyModelViewSet):
"""
GlobalRegion view set for continent and ocean geometries.
Returns GeoJSON FeatureCollection for use in map layers.
Read-only - regions are loaded via management command.
"""
queryset = GlobalRegion.objects.all().order_by("region_type", "name")
serializer_class = GlobalRegionSerializer
permission_classes = [AllowAny]
@extend_schema_view(
list=extend_schema(
summary="List countries (outline geometries)",
description=(
"Country outlines (simplified Natural Earth geometries) as a GeoJSON FeatureCollection, "
"used by the toggleable countries map layer. `iso_code` is ISO 3166-1 alpha-2 and links to "
"works via the `Work.countries` M2M; `absolute_url` links to the `/at/<country>/` landing page."
),
tags=["Global regions"],
),
retrieve=extend_schema(
summary="Retrieve a country by ID",
tags=["Global regions"],
responses={
200: CountrySerializer,
404: OpenApiResponse(_ERROR_RESPONSE, description="No country with this ID."),
},
),
)
class CountryViewSet(viewsets.ReadOnlyModelViewSet):
"""Country geometries for map layers. Read-only — loaded via load_countries."""
queryset = Country.objects.real().order_by("name")
serializer_class = CountrySerializer
permission_classes = [AllowAny]
@extend_schema_view(
list=extend_schema(
summary="List authors with published works",
description=(
"Returns all identity-bearing authors (with ORCID iD) who have at least one "
"published work on OPTIMAP. Paginated. Use the `orcid` lookup field on the "
"detail endpoint to retrieve a specific author."
),
tags=["Authors"],
),
retrieve=extend_schema(
summary="Retrieve an author by ORCID iD",
description=(
"Look up a single author by their bare ORCID iD "
"(e.g. `0000-0002-1825-0097`). Returns 404 if the author is not in OPTIMAP."
),
tags=["Authors"],
responses={
200: AuthorSerializer,
404: OpenApiResponse(_ERROR_RESPONSE, description="No author with this ORCID iD in OPTIMAP."),
},
),
)
class AuthorViewSet(viewsets.ReadOnlyModelViewSet):
"""Authors with an ORCID iD who have at least one published work in OPTIMAP."""
serializer_class = AuthorSerializer
permission_classes = [AllowAny]
lookup_field = "orcid"
lookup_value_regex = r"\d{4}-\d{4}-\d{4}-\d{3}[\dX]"
def get_queryset(self):
from django.db.models import Count
return (
Author.objects.filter(orcid__isnull=False)
.annotate(_work_count=Count("works", filter=Q(works__status="p")))
.filter(_work_count__gt=0)
.order_by("name")
)
@extend_schema_view(
list=extend_schema(
summary="List published collections",
description=(
"Returns all published collections with their work count and links to feeds and "
"downloads. Staff additionally see unpublished collections."
),
tags=["Collections"],
),
retrieve=extend_schema(
summary="Retrieve a collection by identifier",
description=(
"Look up a single collection by its slug `identifier` "
"(e.g. `mountain-wetlands`). Returns 404 for unpublished collections "
"unless the caller is staff."
),
tags=["Collections"],
responses={
200: CollectionSerializer,
404: OpenApiResponse(_ERROR_RESPONSE, description="No published collection with this identifier."),
},
),
)
class CollectionViewSet(viewsets.ReadOnlyModelViewSet):
serializer_class = CollectionSerializer
permission_classes = [AllowAny]
lookup_field = "identifier"
def get_queryset(self):
qs = Collection.objects.annotate(
works_count=Count("works", filter=Q(works__status="p"), distinct=True)
).order_by("name")
if self.request.user.is_staff: