-
Notifications
You must be signed in to change notification settings - Fork 719
Expand file tree
/
Copy pathutils.py
More file actions
1620 lines (1363 loc) · 65 KB
/
utils.py
File metadata and controls
1620 lines (1363 loc) · 65 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
# -*- coding: utf-8 -*-
# Copyright The IETF Trust 2011-2020, All Rights Reserved
import datetime
import io
import json
import os
import pathlib
import re
import subprocess
import sys
import time
import traceback
import xml2rfc
from pathlib import Path
from shutil import move
from typing import Optional, Union # pyflakes:ignore
from unidecode import unidecode
from xml2rfc import RfcWriterError
from xym import xym
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.validators import validate_email
from django.db import transaction
from django.http import HttpRequest # pyflakes:ignore
from django.utils.module_loading import import_string
from django.contrib.auth.models import AnonymousUser
from django.utils import timezone
import debug # pyflakes:ignore
from ietf.doc.models import ( Document, State, DocEvent, SubmissionDocEvent,
DocumentAuthor, AddedMessageEvent )
from ietf.doc.models import NewRevisionDocEvent
from ietf.doc.models import RelatedDocument, DocRelationshipName, DocExtResource
from ietf.doc.storage_utils import remove_from_storage, retrieve_bytes, store_bytes, store_file, store_str
from ietf.doc.utils import (add_state_change_event, rebuild_reference_relations,
set_replaces_for_document, prettify_std_name, update_doc_extresources,
can_edit_docextresources, update_documentauthors, update_action_holders,
bibxml_for_draft )
from ietf.doc.mails import send_review_possibly_replaces_request, send_external_resource_change_request
from ietf.group.models import Group
from ietf.ietfauth.utils import has_role
from ietf.name.models import StreamName, FormalLanguageName
from ietf.person.models import Person, Email
from ietf.community.utils import update_name_contains_indexes_with_new_doc
from ietf.submit.mail import ( announce_to_lists, announce_new_version, announce_to_authors,
send_approval_request, send_submission_confirmation, announce_new_wg_00, send_manual_post_request )
from ietf.submit.checkers import DraftYangChecker
from ietf.submit.models import ( Submission, SubmissionEvent, Preapproval, DraftSubmissionStateName,
SubmissionCheck, SubmissionExtResource )
from ietf.utils import log
from ietf.utils.accesstoken import generate_random_key
from ietf.utils.draft import PlaintextDraft
from ietf.utils.mail import is_valid_email
from ietf.utils.text import parse_unicode, normalize_text
from ietf.utils.timezone import date_today
from ietf.utils.xmldraft import InvalidMetadataError, XMLDraft, capture_xml2rfc_output
from ietf.person.name import unidecode_name
def validate_submission(submission):
errors = {}
if submission.state_id not in ("cancel", "posted"):
for ext in submission.file_types.split(','):
source = os.path.join(settings.IDSUBMIT_STAGING_PATH, '%s-%s%s' % (submission.name, submission.rev, ext))
if not os.path.exists(source):
errors['files'] = '"%s" was not found in the staging area. We recommend you that you cancel this submission and upload your files again.' % os.path.basename(source)
break
if not submission.title:
errors['title'] = 'Title is empty or was not found'
if submission.group and submission.group.state_id != "active":
errors['group'] = 'Group exists but is not an active group'
if not submission.abstract:
errors['abstract'] = 'Abstract is empty or was not found'
if not submission.authors:
errors['authors'] = 'No authors found'
# revision
if submission.state_id != "posted":
error = validate_submission_rev(submission.name, submission.rev)
if error:
errors['rev'] = error
# draft date
error = validate_submission_document_date(submission.submission_date, submission.document_date)
if error:
errors['document_date'] = error
# author email addresses
author_error_count = 0
seen = set()
for author in submission.authors:
email = author['email']
author['errors'] = []
if not email:
author['errors'].append("Found no email address. A valid email address is required.")
author_error_count += 1
else:
try:
validate_email(email)
except ValidationError:
author['errors'].append("Invalid email address. A valid email address is required.")
author_error_count += 1
if email in seen:
author['errors'].append("Duplicate email address. A unique email address is required.")
author_error_count += 1
else:
seen.add(email)
if author_error_count:
errors['authors'] = "Author email error (see below)" if author_error_count == 1 else "Author email errors (see below)"
return errors
def has_been_replaced_by(name):
docs=Document.objects.filter(name=name)
if docs:
doc=docs[0]
return doc.related_that("replaces")
return None
def validate_submission_name(name):
if not re.search(r'^draft-[a-z][-a-z0-9]{0,43}(-\d\d)?$', name):
if re.search(r'-\d\d$', name):
name = name[:-3]
if len(name) > 50:
return "Expected the Internet-Draft name to be at most 50 ascii characters long; found %d." % len(name)
else:
msg = "Expected name 'draft-...' using lowercase ascii letters, digits, and hyphen; found '%s'." % name
if '.' in name:
msg += " Did you include a filename extension in the name by mistake?"
return msg
components = name.split('-')
if '' in components:
return "Name contains adjacent dashes or the name ends with a dash."
if len(components) < 3:
return "Name has less than three dash-delimited components in the name."
return None
def validate_submission_rev(name, rev):
if not rev:
return 'Revision not found'
if len(rev) != 2:
return 'Revision must be a exactly two digits'
try:
rev = int(rev)
except ValueError:
return 'Revision must be a number'
else:
if not (0 <= rev <= 99):
return 'Revision must be between 00 and 99'
expected = 0
existing_revs = [int(i.rev) for i in Document.objects.filter(name=name) if i.rev and i.rev.isdigit() ]
unexpected_revs = [ i.rev for i in Document.objects.filter(name=name) if i.rev and not i.rev.isdigit() ] # pyflakes:ignore
log.assertion('unexpected_revs', [])
if existing_revs:
expected = max(existing_revs) + 1
if rev != expected:
return 'Invalid revision (revision %02d is expected)' % expected
# This is not really correct, though the edges that it doesn't cover are not likely.
# It might be better just to look in the combined archive to make sure we're not colliding with
# a thing that exists there already because it was included from an approved personal collection.
for dirname in [settings.INTERNET_DRAFT_PATH, settings.INTERNET_DRAFT_ARCHIVE_DIR, ]:
dir = pathlib.Path(dirname)
pattern = '%s-%02d.*' % (name, rev)
existing = list(dir.glob(pattern))
if existing:
plural = '' if len(existing) == 1 else 's'
files = ', '.join([ f.name for f in existing ])
return 'Unexpected file%s already in the archive: %s' % (plural, files)
replaced_by=has_been_replaced_by(name)
if replaced_by:
return 'This document has been replaced by %s' % ",".join(rd.name for rd in replaced_by)
return None
def validate_submission_document_date(submission_date, document_date):
if not document_date:
return 'Document date is empty or not in a proper format'
elif abs(submission_date - document_date) > datetime.timedelta(days=3):
return 'Document date must be within 3 days of submission date'
return None
def check_submission_revision_consistency(submission):
"""Test submission for data consistency
Returns None if revision is consistent or an error message describing the problem.
"""
unexpected_submissions = Submission.objects.filter(name=submission.name, rev__gte=submission.rev, state_id='posted').order_by('rev')
if len(unexpected_submissions) != 0:
conflicts = [sub.rev for sub in unexpected_submissions]
return "Rev %s conflicts with existing %s (%s). This indicates a database inconsistency that requires investigation." %(
submission.rev,
"submission" if len(conflicts) == 1 else "submissions",
", ".join(conflicts)
)
return None
def create_submission_event(request: Optional[HttpRequest], submission, desc):
by = None
if request and request.user.is_authenticated:
try:
by = request.user.person
except Person.DoesNotExist:
pass
SubmissionEvent.objects.create(submission=submission, by=by, desc=desc)
def docevent_from_submission(submission, desc, who=None):
# type: (Submission, str, Optional[Person]) -> Optional[DocEvent]
log.assertion('who is None or isinstance(who, Person)')
try:
draft = Document.objects.get(name=submission.name)
except Document.DoesNotExist:
# Assume this is revision 00 - we'll do this later
return None
if who:
by = who
else:
submitter_parsed = submission.submitter_parsed()
if submitter_parsed["name"] and submitter_parsed["email"]:
by, _ = ensure_person_email_info_exists(submitter_parsed["name"], submitter_parsed["email"], submission.name)
else:
by = Person.objects.get(name="(System)")
e = SubmissionDocEvent.objects.create(
doc=draft,
by = by,
type = "new_submission",
desc = desc,
submission = submission,
rev = submission.rev,
)
return e
def post_rev00_submission_events(draft, submission, submitter):
# Add previous submission events as docevents
# For now we'll filter based on the description
events = []
for subevent in submission.submissionevent_set.all().order_by('id'):
desc = subevent.desc
if desc.startswith("Uploaded submission"):
desc = "Uploaded new revision"
e = SubmissionDocEvent(type="new_submission", doc=draft, submission=submission, rev=submission.rev )
elif desc.startswith("Submission created"):
e = SubmissionDocEvent(type="new_submission", doc=draft, submission=submission, rev=submission.rev)
elif desc.startswith("Set submitter to"):
pos = subevent.desc.find("sent confirmation email")
e = SubmissionDocEvent(type="new_submission", doc=draft, submission=submission, rev=submission.rev)
if pos > 0:
desc = "Request for posting confirmation emailed %s" % (subevent.desc[pos + 23:])
else:
pos = subevent.desc.find("sent appproval email")
if pos > 0:
desc = "Request for posting approval emailed %s" % (subevent.desc[pos + 19:])
elif desc.startswith("Received message") or desc.startswith("Sent message"):
e = AddedMessageEvent(type="added_message", doc=draft)
e.message = subevent.submissionemailevent.message
e.msgtype = subevent.submissionemailevent.msgtype
e.in_reply_to = subevent.submissionemailevent.in_reply_to
else:
continue
e.time = subevent.time #submission.submission_date
e.by = submitter
e.desc = desc
e.save()
events.append(e)
return events
def find_submission_filenames(draft):
"""Find uploaded files corresponding to the draft
Returns a dict mapping file extension to the corresponding filename (including the full path).
"""
path = pathlib.Path(settings.IDSUBMIT_STAGING_PATH)
stem = f'{draft.name}-{draft.rev}'
allowed_types = settings.IDSUBMIT_FILE_TYPES
candidates = {ext: path / f'{stem}.{ext}' for ext in allowed_types}
return {ext: str(filename) for ext, filename in candidates.items() if filename.exists()}
@transaction.atomic
def post_submission(request, submission, approved_doc_desc, approved_subm_desc):
# This is very chatty into the logs, but these could still be useful for quick diagnostics
log.log(f"{submission.name}: start")
system = Person.objects.get(name="(System)")
submitter_parsed = submission.submitter_parsed()
if submitter_parsed["name"] and submitter_parsed["email"]:
submitter, _ = ensure_person_email_info_exists(submitter_parsed["name"], submitter_parsed["email"], submission.name)
submitter_info = '%s <%s>' % (submitter_parsed["name"], submitter_parsed["email"])
else:
submitter = system
submitter_info = system.name
log.log(f"{submission.name}: got submitter: {submitter.name}")
# update draft attributes
try:
draft = Document.objects.get(name=submission.name)
log.log(f"{submission.name}: retrieved Internet-Draft: {draft}")
except Document.DoesNotExist:
draft = Document.objects.create(name=submission.name, type_id="draft")
log.log(f"{submission.name}: created Internet-Draft: {draft}")
prev_rev = draft.rev
draft.type_id = "draft"
draft.title = submission.title
group = submission.group or Group.objects.get(type="individ")
if not (group.type_id == "individ" and draft.group and draft.group.type_id == "area"):
# don't overwrite an assigned area if it's still an individual
# submission
draft.group = group
draft.rev = submission.rev
draft.pages = submission.pages
draft.abstract = submission.abstract
was_rfc = draft.get_state_slug() == "rfc"
if not draft.stream:
stream_slug = None
if draft.name.startswith("draft-iab-"):
stream_slug = "iab"
elif draft.name.startswith("draft-irtf-"):
stream_slug = "irtf"
elif draft.name.startswith("draft-ietf-") and (draft.group.type_id != "individ" or was_rfc):
stream_slug = "ietf"
if stream_slug:
draft.stream = StreamName.objects.get(slug=stream_slug)
draft.expires = timezone.now() + datetime.timedelta(settings.INTERNET_DRAFT_DAYS_TO_EXPIRE)
log.log(f"{submission.name}: got Internet-Draft details")
events = []
if draft.rev == '00':
# Add all the previous submission events as docevents
events += post_rev00_submission_events(draft, submission, submitter)
if isinstance(request.user, AnonymousUser):
doer=system
else:
doer=request.user.person
# Add an approval docevent
e = SubmissionDocEvent.objects.create(
type="new_submission",
doc=draft,
by=doer,
desc=approved_doc_desc,
submission=submission,
rev=submission.rev,
)
events.append(e)
# new revision event
e = NewRevisionDocEvent.objects.create(
type="new_revision",
doc=draft,
rev=draft.rev,
by=submitter,
desc="New version available: <b>%s-%s.txt</b>" % (draft.name, draft.rev),
)
events.append(e)
log.log(f"{submission.name}: created doc events")
draft.set_state(State.objects.get(used=True, type="draft", slug="active"))
update_authors(draft, submission)
draft.formal_languages.set(submission.formal_languages.all())
log.log(f"{submission.name}: updated state and info")
trouble = rebuild_reference_relations(draft, find_submission_filenames(draft))
if trouble:
log.log('Rebuild_reference_relations trouble: %s'%trouble)
log.log(f"{submission.name}: rebuilt reference relations")
if draft.stream_id == "ietf" and draft.group.type_id == "wg" and draft.rev == "00":
# automatically set state "WG Document"
draft.set_state(State.objects.get(used=True, type="draft-stream-%s" % draft.stream_id, slug="wg-doc"))
# automatic state changes for IANA review
if (draft.get_state_slug("draft-iana-review") in ("ok-act", "ok-noact", "not-ok")
and not draft.get_state_slug("draft-iesg") in ("approved", "ann", "rfcqueue", "pub", "nopubadw", "nopubanw", "dead") ):
prev_state = draft.get_state("draft-iana-review")
next_state = State.objects.get(used=True, type="draft-iana-review", slug="changed")
draft.set_state(next_state)
e = add_state_change_event(draft, system, prev_state, next_state)
if e:
events.append(e)
state_change_msg = ""
if not was_rfc and draft.tags.filter(slug="need-rev"):
tags_before = list(draft.tags.all())
draft.tags.remove("need-rev")
if draft.stream_id == 'ietf':
draft.tags.add("ad-f-up")
e = DocEvent(type="changed_document", doc=draft, rev=draft.rev)
if draft.stream_id == 'ietf':
e.desc = "Sub state has been changed to <b>AD Followup</b> from <b>Revised I-D Needed</b>"
else:
e.desc = "<b>Revised I-D Needed</b> tag cleared"
e.by = system
e.save()
events.append(e)
state_change_msg = e.desc
# Changed tags - update action holders if necessary
e = update_action_holders(draft, prev_tags=tags_before, new_tags=draft.tags.all())
if e is not None:
events.append(e)
if draft.stream_id == "ietf" and draft.group.type_id == "wg" and draft.rev == "00":
# automatically set state "WG Document"
draft.set_state(State.objects.get(used=True, type="draft-stream-%s" % draft.stream_id, slug="wg-doc"))
log.log(f"{submission.name}: handled state changes")
if not draft.get_state('draft-iesg'):
draft.states.add(State.objects.get(type_id='draft-iesg', slug='idexists'))
# save history now that we're done with changes to the draft itself
draft.save_with_history(events)
log.log(f"{submission.name}: saved history")
# clean up old files
if prev_rev != draft.rev:
from ietf.doc.expire import move_draft_files_to_archive
move_draft_files_to_archive(draft, prev_rev)
submission.draft = draft
move_files_to_repository(submission)
submission.state = DraftSubmissionStateName.objects.get(slug="posted")
log.log(f"{submission.name}: moved files")
new_replaces, new_possibly_replaces = update_replaces_from_submission(request, submission, draft)
update_name_contains_indexes_with_new_doc(draft)
log.log(f"{submission.name}: updated replaces and indexes")
# See whether a change to external resources is requested. Test for equality of sets is ugly,
# but works.
draft_resources = '\n'.join(sorted(str(r) for r in draft.docextresource_set.all()))
submission_resources = '\n'.join(sorted(str(r) for r in submission.external_resources.all()))
if draft_resources != submission_resources:
if can_edit_docextresources(request.user, draft):
update_docextresources_from_submission(request, submission, draft)
log.log(f"{submission.name}: updated external resources")
else:
send_external_resource_change_request(request,
draft,
submitter_info,
submission.external_resources.all())
log.log(f"{submission.name}: sent email suggesting external resources")
announce_to_lists(request, submission)
if submission.group and submission.group.type_id == 'wg' and draft.rev == '00':
announce_new_wg_00(request, submission)
announce_new_version(request, submission, draft, state_change_msg)
announce_to_authors(request, submission)
log.log(f"{submission.name}: sent announcements")
if new_possibly_replaces:
send_review_possibly_replaces_request(request, draft, submitter_info)
submission.save()
create_submission_event(request, submission, approved_subm_desc)
# Create bibxml-ids entry
ref_text = bibxml_for_draft(draft, draft.rev)
ref_rev_file_name = os.path.join(os.path.join(settings.BIBXML_BASE_PATH, 'bibxml-ids'), 'reference.I-D.%s-%s.xml' % (draft.name, draft.rev ))
with io.open(ref_rev_file_name, "w", encoding='utf-8') as f:
f.write(ref_text)
store_str("bibxml-ids", f"reference.I-D.{draft.name}-{draft.rev}.txt", ref_text) # TODO-BLOBSTORE verify with test
log.log(f"{submission.name}: done")
def update_replaces_from_submission(request, submission, draft):
if not submission.replaces:
return [], []
is_secretariat = has_role(request.user, "Secretariat")
is_chair_of = []
if request.user.is_authenticated:
is_chair_of = list(Group.objects.filter(role__person__user=request.user, role__name="chair"))
replaces = Document.objects.filter(name__in=submission.replaces.split(",")).prefetch_related("group")
existing_replaces = list(draft.related_that_doc("replaces"))
existing_suggested = set(draft.related_that_doc("possibly-replaces"))
submitter_email = submission.submitter_parsed()["email"]
approved = []
suggested = []
for r in replaces:
if r in existing_replaces:
continue
if r == draft:
continue
if (is_secretariat
or (draft.group in is_chair_of and (r.group.type_id == "individ" or r.group in is_chair_of))
or (submitter_email and r.documentauthor_set.filter(email__address__iexact=submitter_email).exists())):
approved.append(r)
else:
if r not in existing_suggested:
suggested.append(r)
try:
by = request.user.person if request.user.is_authenticated else Person.objects.get(name="(System)")
except Person.DoesNotExist:
by = Person.objects.get(name="(System)")
set_replaces_for_document(request, draft, existing_replaces + approved, by,
email_subject="%s replacement status set during submit by %s" % (draft.name, submission.submitter_parsed()["name"]))
if suggested:
possibly_replaces = DocRelationshipName.objects.get(slug="possibly-replaces")
for r in suggested:
RelatedDocument.objects.create(source=draft, target=r, relationship=possibly_replaces)
DocEvent.objects.create(doc=draft, rev=draft.rev, by=by, type="added_suggested_replaces",
desc="Added suggested replacement relationships: %s" % ", ".join(d.name for d in suggested))
return approved, suggested
def update_docextresources_from_submission(request, submission, draft):
doc_resources = [DocExtResource.from_sibling_class(res)
for res in submission.external_resources.all()]
by = request.user.person if request.user.is_authenticated else Person.objects.get(name='(System)')
update_doc_extresources(draft, doc_resources, by)
def get_person_from_name_email(name, email):
# try email
if email and (email.startswith('unknown-email-') or is_valid_email(email)):
persons = Person.objects.filter(email__address__iexact=email).distinct()
if len(persons) == 1:
return persons[0]
else:
persons = Person.objects.none()
if not persons.exists():
persons = Person.objects.all()
# try full name
p = persons.filter(alias__name=name).distinct()
if p.exists():
return p.first()
return None
def ensure_person_email_info_exists(name, email, docname):
addr = email
email = None
person = get_person_from_name_email(name, addr)
# make sure we have a person
if not person:
person = Person()
person.name = name
person.name_from_draft = name
log.assertion('isinstance(person.name, str)')
person.ascii = unidecode_name(person.name)
person.save()
else:
person.name_from_draft = name
active = True
addr = addr.lower()
try:
email = person.email_set.get(address=addr)
email.origin = "author: %s" % docname # overwrite earlier origin
email.save()
except Email.DoesNotExist:
try:
# An Email object pointing to some other person will not exist
# at this point, because get_person_from_name_email would have
# returned that person, but it's possible that an Email record
# not associated with any Person exists
email = Email.objects.get(address=addr,person__isnull=True)
except Email.DoesNotExist:
# most likely we just need to create it
email = Email(address=addr)
email.active = active
email.person = person
if email.time is None:
email.time = timezone.now()
email.origin = "author: %s" % docname
email.save()
return person, email
def update_authors(draft, submission):
docauthors = []
for author in submission.authors:
person, email = ensure_person_email_info_exists(author["name"], author.get("email"), submission.name)
docauthors.append(
DocumentAuthor(
# update_documentauthors() will fill in document and order for us
person=person,
email=email,
affiliation=author.get("affiliation", ""),
country=author.get("country", "")
)
)
# The update_documentauthors() method returns a list of unsaved author edit events for the draft.
# Discard these because the existing logging is already adequate.
update_documentauthors(draft, docauthors)
def cancel_submission(submission):
submission.state = DraftSubmissionStateName.objects.get(slug="cancel")
submission.save()
remove_submission_files(submission)
def rename_submission_files(submission, prev_rev, new_rev):
log.unreachable("2025-2-19")
for ext in settings.IDSUBMIT_FILE_TYPES:
staging_path = Path(settings.IDSUBMIT_STAGING_PATH)
source = staging_path / f"{submission.name}-{prev_rev}.{ext}"
dest = staging_path / f"{submission.name}-{new_rev}.{ext}"
if source.exists():
move(source, dest)
def move_files_to_repository(submission):
for ext in settings.IDSUBMIT_FILE_TYPES:
fname = f"{submission.name}-{submission.rev}.{ext}"
source = Path(settings.IDSUBMIT_STAGING_PATH) / fname
dest = Path(settings.IDSUBMIT_REPOSITORY_PATH) / fname
if source.exists():
move(source, dest)
all_archive_dest = Path(settings.INTERNET_ALL_DRAFTS_ARCHIVE_DIR) / dest.name
ftp_dest = Path(settings.FTP_DIR) / "internet-drafts" / dest.name
os.link(dest, all_archive_dest)
os.link(dest, ftp_dest)
# Shadow what's happening to the fs in the blobstores. When the stores become
# authoritative, the source and dest checks will need to apply to the stores instead.
content_bytes = retrieve_bytes("staging", fname)
store_bytes("active-draft", f"{ext}/{fname}", content_bytes)
submission.draft.store_bytes(f"{ext}/{fname}", content_bytes)
remove_from_storage("staging", fname)
elif dest.exists():
log.log("Intended to move '%s' to '%s', but found source missing while destination exists.")
elif f".{ext}" in submission.file_types.split(','):
raise ValueError("Intended to move '%s' to '%s', but found source and destination missing.")
def remove_staging_files(name, rev):
"""Remove staging files corresponding to a submission"""
basename = pathlib.Path(settings.IDSUBMIT_STAGING_PATH) / f'{name}-{rev}'
exts = [f'.{ext}' for ext in settings.IDSUBMIT_FILE_TYPES]
for ext in exts:
basename.with_suffix(ext).unlink(missing_ok=True)
remove_from_storage("staging", basename.with_suffix(ext).name, warn_if_missing=False)
def remove_submission_files(submission):
remove_staging_files(submission.name, submission.rev)
def approvable_submissions_for_user(user):
if not user.is_authenticated:
return []
# Submissions that are group / AD approvable by someone
group_approvable = Submission.objects.filter(state="grp-appr")
ad_approvable = Submission.objects.filter(state="ad-appr")
if has_role(user, "Secretariat"):
return (group_approvable | ad_approvable).order_by('-submission_date')
# group-approvable that we can reach as chair plus group-approvable that we can reach as AD
# plus AD-approvable that we can reach as ad
return (
group_approvable.filter(group__role__name="chair", group__role__person__user=user)
| group_approvable.filter(group__parent__role__name="ad", group__parent__role__person__user=user)
| ad_approvable.filter(group__parent__role__name="ad", group__parent__role__person__user=user)
).order_by('-submission_date')
def preapprovals_for_user(user):
if not user.is_authenticated:
return []
posted = Submission.objects.distinct().filter(state="posted").values_list('name', flat=True)
res = Preapproval.objects.exclude(name__in=posted).order_by("-time").select_related('by')
if has_role(user, "Secretariat"):
return res
accessible_groups = (
Group.objects.filter(role__person__user=user, type__features__req_subm_approval=True)
| Group.objects.filter(parent__role__name='ad', parent__role__person__user=user, type__features__req_subm_approval=True)
)
acronyms = [g.acronym for g in accessible_groups]
res = res.filter(name__regex="draft-[^-]+-(%s)-.*" % "|".join(acronyms))
return res
def recently_approved_by_user(user, since):
if not user.is_authenticated:
return []
res = Submission.objects.distinct().filter(state="posted", submission_date__gte=since, rev="00").order_by('-submission_date')
if has_role(user, "Secretariat"):
return res
# those we can reach as chair or ad
return (
res.filter(group__role__name="chair", group__role__person__user=user)
| res.filter(group__parent__role__name="ad", group__parent__role__person__user=user)
)
def expirable_submissions(older_than_days):
cutoff = date_today() - datetime.timedelta(days=older_than_days)
return Submission.objects.exclude(state__in=("cancel", "posted")).filter(submission_date__lt=cutoff)
def expire_submission(submission, by):
submission.state_id = "cancel"
submission.save()
SubmissionEvent.objects.create(submission=submission, by=by, desc="Cancelled expired submission")
def clear_existing_files(form):
"""Make sure there are no leftover files from a previous submission"""
remove_staging_files(form.filename, form.revision)
def save_files(form):
file_name = {}
for ext in list(form.fields.keys()):
if not ext in form.formats:
continue
f = form.cleaned_data[ext]
if not f:
continue
name = os.path.join(settings.IDSUBMIT_STAGING_PATH, '%s-%s.%s' % (form.filename, form.revision, ext))
file_name[ext] = name
with io.open(name, 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
log.log("saved file %s" % name)
f.seek(0)
store_file("staging", f"{form.filename}-{form.revision}.{ext}", f)
return file_name
def get_submission(form):
# See if there is a Submission in state waiting-for-draft
# for this revision.
# If so - we're going to update it otherwise we create a new object
submissions = Submission.objects.filter(name=form.filename,
rev=form.revision,
state_id = "waiting-for-draft").distinct()
if not submissions:
submission = Submission(name=form.filename, rev=form.revision, group=form.group)
elif len(submissions) == 1:
submission = submissions.first()
else:
raise Exception("Multiple submissions found waiting for upload")
return submission
def fill_in_submission(form, submission, authors, abstract, file_size):
submission.state = DraftSubmissionStateName.objects.get(slug="uploaded")
submission.remote_ip = form.remote_ip
submission.title = form.title
submission.abstract = abstract
submission.authors = authors
submission.file_size = file_size
submission.file_types = ','.join(form.file_types)
submission.xml_version = form.xml_version
submission.submission_date = date_today()
submission.replaces = ""
if form.parsed_draft is not None:
submission.pages = form.parsed_draft.get_pagecount()
submission.words = form.parsed_draft.get_wordcount()
submission.first_two_pages = ''.join(form.parsed_draft.pages[:2])
submission.document_date = form.parsed_draft.get_creation_date()
submission.save()
if form.parsed_draft is not None:
submission.formal_languages.set(FormalLanguageName.objects.filter(slug__in=form.parsed_draft.get_formal_languages()))
set_extresources_from_existing_draft(submission)
def apply_checker(checker, submission, file_name):
def apply_check(submission, checker, method, fn):
func = getattr(checker, method)
passed, message, errors, warnings, info = func(fn)
check = SubmissionCheck(submission=submission, checker=checker.name, passed=passed,
message=message, errors=errors, warnings=warnings, items=info,
symbol=checker.symbol)
check.save()
# ordered list of methods to try
for method in ("check_fragment_xml", "check_file_xml", "check_fragment_txt", "check_file_txt", ):
ext = method[-3:]
if hasattr(checker, method) and ext in file_name:
apply_check(submission, checker, method, file_name[ext])
break
def apply_checkers(submission, file_name):
# run submission checkers
mark = time.time()
for checker_path in settings.IDSUBMIT_CHECKER_CLASSES:
lap = time.time()
checker_class = import_string(checker_path)
checker = checker_class()
apply_checker(checker, submission, file_name)
tau = time.time() - lap
log.log(f"ran {checker.__class__.__name__} ({tau:.3}s) for {file_name}")
tau = time.time() - mark
log.log(f"ran submission checks ({tau:.3}s) for {file_name}")
def accept_submission_requires_prev_auth_approval(submission):
"""Does acceptance process require approval of previous authors?"""
return Document.objects.filter(name=submission.name).exists()
def accept_submission_requires_group_approval(submission):
"""Does acceptance process require group approval?
Depending on the state of the group, this approval may come from group chair or area director.
"""
return (
submission.rev == '00'
and submission.group and submission.group.features.req_subm_approval
and not Preapproval.objects.filter(name=submission.name).exists()
)
class SubmissionError(Exception):
"""Exception for errors during submission processing
Sanitizes paths appearing in exception messages.
"""
def __init__(self, *args):
if len(args) > 0:
args = (self.sanitize_message(arg) for arg in args)
super().__init__(*args)
@staticmethod
def sanitize_message(msg):
# Paths likely to appear in submission-related errors
paths = [
p for p in (
getattr(settings, "ALL_ID_DOWNLOAD_DIR", None),
getattr(settings, "BIBXML_BASE_PATH", None),
getattr(settings, "DERIVED_DIR", None),
getattr(settings, "FTP_DIR", None),
getattr(settings, "IDSUBMIT_REPOSITORY_PATH", None),
getattr(settings, "IDSUBMIT_STAGING_PATH", None),
getattr(settings, "INTERNET_ALL_DRAFTS_ARCHIVE_DIR", None),
getattr(settings, "INTERNET_DRAFT_PATH", None),
getattr(settings, "INTERNET_DRAFT_ARCHIVE_DIR", None),
getattr(settings, "INTERNET_DRAFT_PDF_PATH", None),
getattr(settings, "RFC_PATH", None),
getattr(settings, "SUBMIT_YANG_CATALOG_MODEL_DIR", None),
getattr(settings, "SUBMIT_YANG_DRAFT_MODEL_DIR", None),
getattr(settings, "SUBMIT_YANG_IANA_MODEL_DIR", None),
getattr(settings, "SUBMIT_YANG_RFC_MODEL_DIR", None),
"/tmp/",
) if p is not None
]
return re.sub(fr"({'|'.join(paths)})/*", "**/", msg)
class XmlRfcError(SubmissionError):
"""SubmissionError caused by xml2rfc
Includes the output from xml2rfc, if any, in xml2rfc_stdout / xml2rfc_stderr
"""
def __init__(self, *args, xml2rfc_stdout: str, xml2rfc_stderr: str):
super().__init__(*args)
self.xml2rfc_stderr = xml2rfc_stderr
self.xml2rfc_stdout = xml2rfc_stdout
class InconsistentRevisionError(SubmissionError):
"""SubmissionError caused by an inconsistent revision"""
def staging_path(filename, revision, ext):
if len(ext) > 0 and ext[0] != '.':
ext = f'.{ext}'
return pathlib.Path(settings.IDSUBMIT_STAGING_PATH) / f'{filename}-{revision}{ext}'
def render_missing_formats(submission):
"""Generate txt and html formats from xml draft
If a txt file already exists, leaves it in place. Overwrites an existing html file
if there is one.
"""
with capture_xml2rfc_output() as xml2rfc_logs:
xml_path = staging_path(submission.name, submission.rev, '.xml')
parser = xml2rfc.XmlRfcParser(str(xml_path), quiet=True)
try:
# --- Parse the xml ---
xmltree = parser.parse(remove_comments=False)
except Exception as err:
raise XmlRfcError(
"Error parsing XML",
xml2rfc_stdout=xml2rfc_logs["stdout"].getvalue(),
xml2rfc_stderr=xml2rfc_logs["stderr"].getvalue(),
) from err
# If we have v2, run it through v2v3. Keep track of the submitted version, though.
xmlroot = xmltree.getroot()
xml_version = xmlroot.get('version', '2')
if xml_version == '2':
v2v3 = xml2rfc.V2v3XmlWriter(xmltree)
try:
xmltree.tree = v2v3.convert2to3()
except Exception as err:
raise XmlRfcError(
"Error converting v2 XML to v3",
xml2rfc_stdout=xml2rfc_logs["stdout"].getvalue(),
xml2rfc_stderr=xml2rfc_logs["stderr"].getvalue(),
) from err
# --- Prep the xml ---
today = date_today()
prep = xml2rfc.PrepToolWriter(xmltree, quiet=True, liberal=True, keep_pis=[xml2rfc.V3_PI_TARGET])
prep.options.accept_prepped = True
prep.options.date = today
try:
xmltree.tree = prep.prep()
except RfcWriterError:
raise XmlRfcError(
f"Error during xml2rfc prep: {prep.errors}",
xml2rfc_stdout=xml2rfc_logs["stdout"].getvalue(),
xml2rfc_stderr=xml2rfc_logs["stderr"].getvalue(),
)
except Exception as err:
raise XmlRfcError(
"Unexpected error during xml2rfc prep",
xml2rfc_stdout=xml2rfc_logs["stdout"].getvalue(),
xml2rfc_stderr=xml2rfc_logs["stderr"].getvalue(),
) from err
# --- Convert to txt ---
txt_path = staging_path(submission.name, submission.rev, '.txt')
if not txt_path.exists():
writer = xml2rfc.TextWriter(xmltree, quiet=True)
writer.options.accept_prepped = True
writer.options.date = today
try:
writer.write(txt_path)
except Exception as err:
raise XmlRfcError(
"Error generating text format from XML",
xml2rfc_stdout=xml2rfc_logs["stdout"].getvalue(),
xml2rfc_stderr=xml2rfc_logs["stderr"].getvalue(),
) from err
log.log(
'In %s: xml2rfc %s generated %s from %s (version %s)' % (
str(xml_path.parent),
xml2rfc.__version__,
txt_path.name,
xml_path.name,
xml_version,
)
)
# When the blobstores become autoritative - the guard at the
# containing if statement needs to be based on the store
with Path(txt_path).open("rb") as f: