forked from ietf-tools/datatracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserializers_rpc.py
More file actions
804 lines (713 loc) · 30.6 KB
/
serializers_rpc.py
File metadata and controls
804 lines (713 loc) · 30.6 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
# Copyright The IETF Trust 2025-2026, All Rights Reserved
import datetime
from pathlib import Path
from typing import Literal, Optional
from django.db import transaction
from django.urls import reverse as urlreverse
from django.utils import timezone
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import extend_schema_field
from rest_framework import serializers
from ietf.doc.expire import move_draft_files_to_archive
from ietf.doc.models import (
DocumentAuthor,
Document,
RelatedDocument,
State,
DocEvent,
RfcAuthor,
)
from ietf.doc.serializers import RfcAuthorSerializer
from ietf.doc.tasks import trigger_red_precomputer_task, update_rfc_searchindex_task
from ietf.doc.utils import (
default_consensus,
prettify_std_name,
update_action_holders,
update_rfcauthors,
)
from ietf.group.models import Group, Role
from ietf.group.serializers import AreaSerializer
from ietf.name.models import StreamName, StdLevelName
from ietf.person.models import Person
from ietf.utils import log
class PersonSerializer(serializers.ModelSerializer):
email = serializers.EmailField(read_only=True)
picture = serializers.URLField(source="cdn_photo_url", read_only=True)
url = serializers.SerializerMethodField(
help_text="relative URL for datatracker person page"
)
class Meta:
model = Person
fields = ["id", "plain_name", "email", "picture", "url"]
read_only_fields = ["id", "plain_name", "email", "picture", "url"]
@extend_schema_field(OpenApiTypes.URI)
def get_url(self, object: Person):
return urlreverse(
"ietf.person.views.profile",
kwargs={"email_or_name": object.email_address() or object.name},
)
class EmailPersonSerializer(serializers.Serializer):
email = serializers.EmailField(source="address")
person_pk = serializers.IntegerField(source="person.pk")
name = serializers.CharField(source="person.name")
last_name = serializers.CharField(source="person.last_name")
initials = serializers.CharField(source="person.initials")
class LowerCaseEmailField(serializers.EmailField):
def to_representation(self, value):
return super().to_representation(value).lower()
class AuthorPersonSerializer(serializers.ModelSerializer):
person_pk = serializers.IntegerField(source="pk", read_only=True)
last_name = serializers.CharField()
initials = serializers.CharField()
email_addresses = serializers.ListField(
source="email_set.all", child=LowerCaseEmailField()
)
class Meta:
model = Person
fields = ["person_pk", "name", "last_name", "initials", "email_addresses"]
class RfcWithAuthorsSerializer(serializers.ModelSerializer):
authors = AuthorPersonSerializer(many=True, source="author_persons")
class Meta:
model = Document
fields = ["rfc_number", "authors"]
class DraftWithAuthorsSerializer(serializers.ModelSerializer):
draft_name = serializers.CharField(source="name")
authors = AuthorPersonSerializer(many=True, source="author_persons")
class Meta:
model = Document
fields = ["draft_name", "authors"]
class WgChairSerializer(serializers.Serializer):
"""Serialize a WG chair's name and email from a Role"""
name = serializers.SerializerMethodField()
email = serializers.SerializerMethodField()
@extend_schema_field(serializers.CharField)
def get_name(self, role: Role) -> str:
return role.person.plain_name()
@extend_schema_field(serializers.EmailField)
def get_email(self, role: Role) -> str:
return role.email.email_address()
class DocumentAuthorSerializer(serializers.ModelSerializer):
"""Serializer for a Person in a response"""
plain_name = serializers.SerializerMethodField()
class Meta:
model = DocumentAuthor
fields = ["person", "plain_name", "affiliation"]
def get_plain_name(self, document_author: DocumentAuthor) -> str:
return document_author.person.plain_name()
class FullDraftSerializer(serializers.ModelSerializer):
# Redefine these fields so they don't pick up the regex validator patterns.
# There seem to be some non-compliant drafts in the system! If this serializer
# is used for a writeable view, the validation will need to be added back.
name = serializers.CharField(max_length=255)
title = serializers.CharField(max_length=255)
group = serializers.SlugRelatedField(slug_field="acronym", read_only=True)
area = AreaSerializer(read_only=True)
# Other fields we need to add / adjust
source_format = serializers.SerializerMethodField()
authors = DocumentAuthorSerializer(many=True, source="documentauthor_set")
shepherd = serializers.PrimaryKeyRelatedField(
source="shepherd.person", read_only=True
)
consensus = serializers.SerializerMethodField()
wg_chairs = serializers.SerializerMethodField()
class Meta:
model = Document
fields = [
"id",
"name",
"rev",
"stream",
"title",
"group",
"area",
"abstract",
"pages",
"source_format",
"authors",
"intended_std_level",
"consensus",
"shepherd",
"ad",
"wg_chairs",
]
def get_consensus(self, doc: Document) -> Optional[bool]:
return default_consensus(doc)
@extend_schema_field(WgChairSerializer(many=True))
def get_wg_chairs(self, doc: Document):
if doc.group is None:
return []
chairs = doc.group.role_set.filter(name_id="chair").select_related(
"person", "email"
)
return WgChairSerializer(chairs, many=True).data
def get_source_format(
self, doc: Document
) -> Literal["unknown", "xml-v2", "xml-v3", "txt"]:
submission = doc.submission()
if submission is None:
return "unknown"
if ".xml" in submission.file_types:
if submission.xml_version == "3":
return "xml-v3"
else:
return "xml-v2"
elif ".txt" in submission.file_types:
return "txt"
return "unknown"
class DraftSerializer(FullDraftSerializer):
class Meta:
model = Document
fields = [
"id",
"name",
"rev",
"stream",
"title",
"group",
"pages",
"source_format",
"authors",
"consensus",
]
class SubmittedToQueueSerializer(FullDraftSerializer):
submitted = serializers.SerializerMethodField()
consensus = serializers.SerializerMethodField()
class Meta:
model = Document
fields = [
"id",
"name",
"stream",
"submitted",
"consensus",
]
def get_submitted(self, doc) -> Optional[datetime.datetime]:
event = doc.sent_to_rfc_editor_event()
return None if event is None else event.time
def get_consensus(self, doc) -> Optional[bool]:
return default_consensus(doc)
class OriginalStreamSerializer(serializers.ModelSerializer):
stream = serializers.CharField(read_only=True, source="orig_stream_id")
class Meta:
model = Document
fields = ["rfc_number", "stream"]
class ReferenceSerializer(serializers.ModelSerializer):
class Meta:
model = Document
fields = ["id", "name"]
read_only_fields = ["id", "name"]
def _update_authors(rfc, authors_data):
# Construct unsaved instances from validated author data
new_authors = [RfcAuthor(**authdata) for authdata in authors_data]
# Update the RFC with the new author set
with transaction.atomic():
change_events = update_rfcauthors(rfc, new_authors)
for event in change_events:
event.save()
return change_events
class SubseriesNameField(serializers.RegexField):
def __init__(self, **kwargs):
# pattern: no leading 0, finite length (arbitrarily set to 5 digits)
regex = r"^(bcp|std|fyi)[1-9][0-9]{0,4}$"
super().__init__(regex, **kwargs)
class RfcPubSerializer(serializers.ModelSerializer):
"""Write-only serializer for RFC publication"""
# publication-related fields
published = serializers.DateTimeField(default_timezone=datetime.timezone.utc)
draft_name = serializers.RegexField(
required=False, regex=r"^draft-[a-zA-Z0-9-]+$"
)
draft_rev = serializers.RegexField(
required=False, regex=r"^[0-9][0-9]$"
)
# fields on the RFC Document that need tweaking from ModelSerializer defaults
rfc_number = serializers.IntegerField(min_value=1, required=True)
group = serializers.SlugRelatedField(
slug_field="acronym", queryset=Group.objects.all(), required=False
)
stream = serializers.PrimaryKeyRelatedField(
queryset=StreamName.objects.filter(used=True)
)
std_level = serializers.PrimaryKeyRelatedField(
queryset=StdLevelName.objects.filter(used=True),
)
ad = serializers.PrimaryKeyRelatedField(
queryset=Person.objects.all(),
allow_null=True,
required=False,
)
obsoletes = serializers.SlugRelatedField(
many=True,
required=False,
slug_field="rfc_number",
queryset=Document.objects.filter(type_id="rfc"),
)
updates = serializers.SlugRelatedField(
many=True,
required=False,
slug_field="rfc_number",
queryset=Document.objects.filter(type_id="rfc"),
)
subseries = serializers.ListField(child=SubseriesNameField(required=False))
# N.b., authors is _not_ a field on Document!
authors = RfcAuthorSerializer(many=True)
class Meta:
model = Document
fields = [
"published",
"draft_name",
"draft_rev",
"rfc_number",
"title",
"authors",
"group",
"stream",
"abstract",
"pages",
"std_level",
"ad",
"obsoletes",
"updates",
"subseries",
"keywords",
]
def validate(self, data):
if "draft_name" in data or "draft_rev" in data:
if "draft_name" not in data:
raise serializers.ValidationError(
{"draft_name": "Missing draft_name"},
code="invalid-draft-spec",
)
if "draft_rev" not in data:
raise serializers.ValidationError(
{"draft_rev": "Missing draft_rev"},
code="invalid-draft-spec",
)
return data
def update(self, instance, validated_data):
raise RuntimeError("Cannot update with this serializer")
def create(self, validated_data):
"""Publish an RFC"""
published = validated_data.pop("published")
draft_name = validated_data.pop("draft_name", None)
draft_rev = validated_data.pop("draft_rev", None)
obsoletes = validated_data.pop("obsoletes", [])
updates = validated_data.pop("updates", [])
subseries = validated_data.pop("subseries", [])
system_person = Person.objects.get(name="(System)")
# If specified, retrieve draft and extract RFC default values from it
if draft_name is None:
draft = None
else:
# validation enforces that draft_name and draft_rev are both present
draft = Document.objects.filter(
type_id="draft",
name=draft_name,
rev=draft_rev,
).first()
if draft is None:
raise serializers.ValidationError(
{
"draft_name": "No such draft",
"draft_rev": "No such draft",
},
code="invalid-draft"
)
elif draft.get_state_slug() == "rfc":
raise serializers.ValidationError(
{
"draft_name": "Draft already published as RFC",
},
code="already-published-draft",
)
# Transaction to clean up if something fails
with transaction.atomic():
# create rfc, letting validated request data override draft defaults
rfc = self._create_rfc(validated_data)
DocEvent.objects.create(
doc=rfc,
rev=rfc.rev,
type="published_rfc",
time=published,
by=system_person,
desc="RFC published",
)
rfc.set_state(State.objects.get(used=True, type_id="rfc", slug="published"))
# create updates / obsoletes relations
for obsoleted_rfc_pk in obsoletes:
RelatedDocument.objects.get_or_create(
source=rfc, target=obsoleted_rfc_pk, relationship_id="obs"
)
for updated_rfc_pk in updates:
RelatedDocument.objects.get_or_create(
source=rfc, target=updated_rfc_pk, relationship_id="updates"
)
# create subseries relations
for subseries_doc_name in subseries:
ss_slug = subseries_doc_name[:3]
subseries_doc, ss_doc_created = Document.objects.get_or_create(
type_id=ss_slug, name=subseries_doc_name
)
if ss_doc_created:
subseries_doc.docevent_set.create(
type=f"{ss_slug}_doc_created",
by=system_person,
desc=f"Created {subseries_doc_name} via publication of {rfc.name}",
)
_, ss_rel_created = subseries_doc.relateddocument_set.get_or_create(
relationship_id="contains", target=rfc
)
if ss_rel_created:
subseries_doc.docevent_set.create(
type="sync_from_rfc_editor",
by=system_person,
desc=f"Added {rfc.name} to {subseries_doc.name}",
)
rfc.docevent_set.create(
type="sync_from_rfc_editor",
by=system_person,
desc=f"Added {rfc.name} to {subseries_doc.name}",
)
# create relation with draft and update draft state
if draft is not None:
draft_changes = []
draft_events = []
if draft.get_state_slug() != "rfc":
draft.set_state(
State.objects.get(used=True, type="draft", slug="rfc")
)
move_draft_files_to_archive(draft, draft.rev)
draft_changes.append(f"changed state to {draft.get_state()}")
r, created_relateddoc = RelatedDocument.objects.get_or_create(
source=draft, target=rfc, relationship_id="became_rfc",
)
if created_relateddoc:
change = "created {rel_name} relationship between {pretty_draft_name} and {pretty_rfc_name}".format(
rel_name=r.relationship.name.lower(),
pretty_draft_name=prettify_std_name(draft_name),
pretty_rfc_name=prettify_std_name(rfc.name),
)
draft_changes.append(change)
# Always set the "draft-iesg" state. This state should be set for all drafts, so
# log a warning if it is not set. What should happen here is that ietf stream
# RFCs come in as "rfcqueue" and are set to "pub" when they appear in the RFC index.
# Other stream documents should normally be "idexists" and be left that way. The
# code here *actually* leaves "draft-iesg" state alone if it is "idexists" or "pub",
# and changes any other state to "pub". If unset, it changes it to "idexists".
# This reflects historical behavior and should probably be updated, but a migration
# of existing drafts (and validation of the change) is needed before we change the
# handling.
prev_iesg_state = draft.get_state("draft-iesg")
if prev_iesg_state is None:
log.log(f'Warning while processing {rfc.name}: {draft.name} has no "draft-iesg" state')
new_iesg_state = State.objects.get(type_id="draft-iesg", slug="idexists")
elif prev_iesg_state.slug not in ("pub", "idexists"):
if prev_iesg_state.slug != "rfcqueue":
log.log(
'Warning while processing {}: {} is in "draft-iesg" state {} (expected "rfcqueue")'.format(
rfc.name, draft.name, prev_iesg_state.slug
)
)
new_iesg_state = State.objects.get(type_id="draft-iesg", slug="pub")
else:
new_iesg_state = prev_iesg_state
if new_iesg_state != prev_iesg_state:
draft.set_state(new_iesg_state)
draft_changes.append(f"changed {new_iesg_state.type.label} to {new_iesg_state}")
e = update_action_holders(draft, prev_iesg_state, new_iesg_state)
if e:
draft_events.append(e)
# If the draft and RFC streams agree, move draft to "pub" stream state. If not, complain.
if draft.stream != rfc.stream:
log.log("Warning while processing {}: draft {} stream is {} but RFC stream is {}".format(
rfc.name, draft.name, draft.stream, rfc.stream
))
elif draft.stream.slug in ["iab", "irtf", "ise", "editorial"]:
stream_slug = f"draft-stream-{draft.stream.slug}"
prev_state = draft.get_state(stream_slug)
if prev_state is not None and prev_state.slug != "pub":
new_state = State.objects.select_related("type").get(used=True, type__slug=stream_slug, slug="pub")
draft.set_state(new_state)
draft_changes.append(
f"changed {new_state.type.label} to {new_state}"
)
e = update_action_holders(draft, prev_state, new_state)
if e:
draft_events.append(e)
if draft_changes:
draft_events.append(
DocEvent.objects.create(
doc=draft,
rev=draft.rev,
by=system_person,
type="sync_from_rfc_editor",
desc=f"Updated while publishing {rfc.name} ({', '.join(draft_changes)})",
)
)
draft.save_with_history(draft_events)
return rfc
def _create_rfc(self, validated_data):
authors_data = validated_data.pop("authors")
rfc = Document.objects.create(
type_id="rfc",
name=f"rfc{validated_data['rfc_number']}",
**validated_data,
)
for order, author_data in enumerate(authors_data):
rfc.rfcauthor_set.create(
order=order,
**author_data,
)
return rfc
class EditableRfcSerializer(serializers.ModelSerializer):
# Would be nice to reconcile this with ietf.doc.serializers.RfcSerializer.
# The purposes of that serializer (representing data for Red) and this one
# (accepting updates from Purple) are different enough that separate formats
# may be needed, but if not it'd be nice to have a single RfcSerializer that
# can serve both.
#
# Should also consider whether this and RfcPubSerializer should merge.
#
# Treats published and subseries fields as write-only. This isn't quite correct,
# but makes it easier and we don't currently use the serialized value except for
# debugging.
published = serializers.DateTimeField(
default_timezone=datetime.timezone.utc,
write_only=True,
)
authors = RfcAuthorSerializer(many=True, min_length=1, source="rfcauthor_set")
subseries = serializers.ListField(
child=SubseriesNameField(required=False),
write_only=True,
)
class Meta:
model = Document
fields = [
"published",
"title",
"authors",
"stream",
"abstract",
"pages",
"std_level",
"subseries",
"keywords",
]
def create(self, validated_data):
raise RuntimeError("Cannot create with this serializer")
def update(self, instance, validated_data):
assert isinstance(instance, Document)
assert instance.type_id == "rfc"
rfc = instance # get better name
system_person = Person.objects.get(name="(System)")
# Remove data that needs special handling. Use a singleton object to detect
# missing values in case we ever support a value that needs None as an option.
omitted = object()
published = validated_data.pop("published", omitted)
subseries = validated_data.pop("subseries", omitted)
authors_data = validated_data.pop("rfcauthor_set", omitted)
# Transaction to clean up if something fails
with transaction.atomic():
# update the rfc Document itself
rfc_changes = []
rfc_events = []
for attr, new_value in validated_data.items():
old_value = getattr(rfc, attr)
if new_value != old_value:
rfc_changes.append(
f"changed {attr} to '{new_value}' from '{old_value}'"
)
setattr(rfc, attr, new_value)
if len(rfc_changes) > 0:
rfc_change_summary = f"{', '.join(rfc_changes)}"
rfc_events.append(
DocEvent.objects.create(
doc=rfc,
rev=rfc.rev,
by=system_person,
type="sync_from_rfc_editor",
desc=f"Changed metadata: {rfc_change_summary}",
)
)
if authors_data is not omitted:
rfc_events.extend(_update_authors(instance, authors_data))
if published is not omitted:
published_event = rfc.latest_event(type="published_rfc")
if published_event is None:
# unexpected, but possible in theory
rfc_events.append(
DocEvent.objects.create(
doc=rfc,
rev=rfc.rev,
type="published_rfc",
time=published,
by=system_person,
desc="RFC published",
)
)
rfc_events.append(
DocEvent.objects.create(
doc=rfc,
rev=rfc.rev,
type="sync_from_rfc_editor",
by=system_person,
desc=(
f"Set publication timestamp to {published.isoformat()}"
),
)
)
else:
original_pub_time = published_event.time
if published != original_pub_time:
published_event.time = published
published_event.save()
rfc_events.append(
DocEvent.objects.create(
doc=rfc,
rev=rfc.rev,
type="sync_from_rfc_editor",
by=system_person,
desc=(
f"Changed publication time to "
f"{published.isoformat()} from "
f"{original_pub_time.isoformat()}"
)
)
)
# update subseries relations
if subseries is not omitted:
for subseries_doc_name in subseries:
ss_slug = subseries_doc_name[:3]
subseries_doc, ss_doc_created = Document.objects.get_or_create(
type_id=ss_slug, name=subseries_doc_name
)
if ss_doc_created:
subseries_doc.docevent_set.create(
type=f"{ss_slug}_doc_created",
by=system_person,
desc=f"Created {subseries_doc_name} via update of {rfc.name}",
)
_, ss_rel_created = subseries_doc.relateddocument_set.get_or_create(
relationship_id="contains", target=rfc
)
if ss_rel_created:
subseries_doc.docevent_set.create(
type="sync_from_rfc_editor",
by=system_person,
desc=f"Added {rfc.name} to {subseries_doc.name}",
)
rfc_events.append(
rfc.docevent_set.create(
type="sync_from_rfc_editor",
by=system_person,
desc=f"Added {rfc.name} to {subseries_doc.name}",
)
)
# Delete subseries relations that are no longer current
stale_subseries_relations = rfc.relations_that("contains").exclude(
source__name__in=subseries
)
for stale_relation in stale_subseries_relations:
stale_subseries_doc = stale_relation.source
rfc_events.append(
rfc.docevent_set.create(
type="sync_from_rfc_editor",
by=system_person,
desc=f"Removed {rfc.name} from {stale_subseries_doc.name}",
)
)
stale_subseries_doc.docevent_set.create(
type="sync_from_rfc_editor",
by=system_person,
desc=f"Removed {rfc.name} from {stale_subseries_doc.name}",
)
stale_subseries_relations.delete()
if len(rfc_events) > 0:
rfc.save_with_history(rfc_events)
# Gather obs and updates in both directions as a title/author change to
# this doc affects the info rendering of all of the other RFCs
needs_updating = sorted(
[
d.rfc_number
for d in [rfc]
+ rfc.related_that_doc(("obs", "updates"))
+ rfc.related_that(("obs", "updates"))
]
)
trigger_red_precomputer_task.delay(rfc_number_list=needs_updating)
# Update the search index also
update_rfc_searchindex_task.delay(rfc.rfc_number)
return rfc
class RfcFileSerializer(serializers.Serializer):
# The structure of this serializer is constrained by what openapi-generator-cli's
# python generator can correctly serialize as multipart/form-data. It does not
# handle nested serializers well (or perhaps at all). ListFields with child
# ChoiceField or RegexField do not serialize correctly. DictFields don't seem
# to work.
#
# It does seem to correctly send filenames along with FileFields, even as a child
# in a ListField, so we use that to convey the file format of each item. There
# are other options we could consider (e.g., a structured CharField) but this
# works.
allowed_extensions = (
".html",
".json",
".notprepped.xml",
".pdf",
".txt",
".xml",
)
rfc = serializers.SlugRelatedField(
slug_field="rfc_number",
queryset=Document.objects.filter(type_id="rfc"),
help_text="RFC number to which the contents belong",
)
contents = serializers.ListField(
child=serializers.FileField(
allow_empty_file=False,
use_url=False,
),
help_text=(
"List of content files. Filename extensions are used to identify "
"file types, but filenames are otherwise ignored."
),
)
mtime = serializers.DateTimeField(
required=False,
default=timezone.now,
default_timezone=datetime.UTC,
help_text="Modification timestamp to apply to uploaded files",
)
replace = serializers.BooleanField(
required=False,
default=False,
help_text=(
"Replace existing files for this RFC. Defaults to false. When false, "
"if _any_ files already exist for the specified RFC the upload will be "
"rejected regardless of which files are being uploaded. When true,"
"existing files will be removed and new ones will be put in place. BE"
"VERY CAREFUL WITH THIS OPTION IN PRODUCTION."
),
)
def validate_contents(self, data):
found_extensions = []
for uploaded_file in data:
if not hasattr(uploaded_file, "name"):
raise serializers.ValidationError(
"filename not specified for uploaded file",
code="missing-filename",
)
ext = "".join(Path(uploaded_file.name).suffixes)
if ext not in self.allowed_extensions:
raise serializers.ValidationError(
f"File uploaded with invalid extension '{ext}'",
code="invalid-filename-ext",
)
if ext in found_extensions:
raise serializers.ValidationError(
f"More than one file uploaded with extension '{ext}'",
code="duplicate-filename-ext",
)
return data
class NotificationAckSerializer(serializers.Serializer):
message = serializers.CharField(default="ack")