-
-
Notifications
You must be signed in to change notification settings - Fork 135
/
tasks.py
1842 lines (1677 loc) · 61.6 KB
/
tasks.py
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
import copy
import logging
import os
import shutil
from datetime import date
from io import BytesIO
from tempfile import NamedTemporaryFile
from typing import Any, Dict, List, Optional, Pattern, Tuple, Union
import internetarchive as ia
import requests
from celery import Task
from celery.exceptions import SoftTimeLimitExceeded
from django.conf import settings
from django.contrib.auth.models import User
from django.core.files.base import ContentFile
from django.db import DatabaseError, IntegrityError, transaction
from django.db.models import Prefetch
from django.db.models.query import prefetch_related_objects
from django.utils.encoding import force_bytes
from django.utils.timezone import now
from juriscraper.lib.exceptions import PacerLoginException, ParsingException
from juriscraper.lib.string_utils import CaseNameTweaker, harmonize
from juriscraper.pacer import (
AppellateDocketReport,
AttachmentPage,
CaseQuery,
ClaimsRegister,
DocketReport,
FreeOpinionReport,
PacerSession,
PossibleCaseNumberApi,
ShowCaseDocApi,
)
from pyexpat import ExpatError
from requests import Response
from requests.cookies import RequestsCookieJar
from requests.exceptions import HTTPError, RequestException
from requests.packages.urllib3.exceptions import ReadTimeoutError
from rest_framework.renderers import JSONRenderer
from rest_framework.status import (
HTTP_400_BAD_REQUEST,
HTTP_403_FORBIDDEN,
HTTP_500_INTERNAL_SERVER_ERROR,
HTTP_504_GATEWAY_TIMEOUT,
)
from cl.alerts.tasks import enqueue_docket_alert, send_docket_alert
from cl.audio.models import Audio
from cl.celery_init import app
from cl.corpus_importer.api_serializers import IADocketSerializer
from cl.corpus_importer.utils import mark_ia_upload_needed
from cl.custom_filters.templatetags.text_filters import best_case_name
from cl.lib.celery_utils import throttle_task
from cl.lib.crypto import sha1
from cl.lib.microservice_utils import microservice
from cl.lib.pacer import (
get_blocked_status,
get_first_missing_de_date,
lookup_and_save,
map_cl_to_pacer_id,
map_pacer_to_cl_id,
)
from cl.lib.pacer_session import (
get_or_cache_pacer_cookies,
get_pacer_cookie_from_cache,
)
from cl.lib.recap_utils import (
get_bucket_name,
get_docket_filename,
get_document_filename,
)
from cl.lib.types import TaskData
from cl.people_db.models import Attorney, Role
from cl.recap.constants import CR_2017, CR_OLD, CV_2017, CV_2020, CV_OLD
from cl.recap.mergers import (
add_bankruptcy_data_to_docket,
add_claims_to_docket,
add_tags_to_objs,
find_docket_object,
make_recap_sequence_number,
merge_pacer_docket_into_cl_docket,
save_iquery_to_docket,
update_docket_metadata,
)
from cl.recap.models import (
UPLOAD_TYPE,
FjcIntegratedDatabase,
PacerHtmlFiles,
ProcessingQueue,
)
from cl.scrapers.models import PACERFreeDocumentLog, PACERFreeDocumentRow
from cl.scrapers.tasks import extract_recap_pdf
from cl.search.models import (
ClaimHistory,
Court,
Docket,
DocketEntry,
RECAPDocument,
Tag,
)
from cl.search.tasks import add_items_to_solr
logger = logging.getLogger(__name__)
def increment_failure_count(obj: Union[Audio, Docket, RECAPDocument]) -> None:
if obj.ia_upload_failure_count is None:
obj.ia_upload_failure_count = 1
else:
obj.ia_upload_failure_count += 1
obj.save()
def generate_ia_json(
d_pk: int,
database: str = "default",
) -> Tuple[Docket, str]:
"""Generate JSON for upload to Internet Archive
:param d_pk: The PK of the docket to generate JSON for
:param database: The name of the database to use for the queries
:return: A tuple of the docket object requested and a string of json data
to upload.
"""
# This is a pretty highly optimized query that minimizes the hits to the DB
# when generating a docket JSON rendering, regardless of how many related
# objects the docket has such as docket entries, parties, etc.
ds = (
Docket.objects.filter(pk=d_pk)
.select_related(
"originating_court_information",
"bankruptcy_information",
"idb_data",
)
.prefetch_related(
"panel",
"parties",
# Django appears to have a bug where you can't defer a field on a
# queryset where you prefetch the values. If you try to, it
# crashes. We should be able to just do the prefetch below like
# the ones above and then do the defer statement at the end, but
# that throws an error.
Prefetch(
"docket_entries__recap_documents",
queryset=RECAPDocument.objects.all().defer("plain_text"),
),
Prefetch(
"claims__claim_history_entries",
queryset=ClaimHistory.objects.all().defer("plain_text"),
),
)
.using(database)
)
d = ds[0]
# Prefetching attorneys needs to be done in a second pass where we can
# access the party IDs identified above. If we don't do it this way, Django
# generates a bad query that double-joins the attorney table to the role
# table. See notes in #901. Doing this way makes for a very large query,
# but one that is fairly efficient since the double-join, while still
# there, appears to be ignored by the query planner.
# Do not add a `using` method here, it causes an additional (unnecessary)
# query to be run. I think this is a Django bug.
party_ids = [p.pk for p in d.parties.all()]
attorney_prefetch = Prefetch(
"parties__attorneys",
queryset=Attorney.objects.filter(
roles__docket_id=d_pk, parties__id__in=party_ids
)
.distinct()
.prefetch_related(
Prefetch(
# Only roles for those attorneys in the docket.
"roles",
queryset=Role.objects.filter(docket_id=d_pk),
)
),
)
prefetch_related_objects(
[d],
*[
"parties__party_types__criminal_complaints",
"parties__party_types__criminal_counts",
attorney_prefetch, # type: ignore
],
)
renderer = JSONRenderer()
json_str = renderer.render(
IADocketSerializer(d).data,
accepted_media_type="application/json; indent=2",
).decode()
return d, json_str
@app.task(bind=True, ignore_result=True)
def save_ia_docket_to_disk(self, d_pk: int, output_directory: str) -> None:
"""For each docket given, save it to disk.
:param self: The celery task
:param d_pk: The PK of the docket to serialize to disk
:param output_directory: The location to save the docket's JSON
"""
_, j = generate_ia_json(d_pk)
with open(os.path.join(output_directory, f"{d_pk}.json"), "w") as f:
f.write(j)
@app.task(bind=True, ignore_result=True)
def upload_recap_json(self, pk: int, database: str = "default") -> None:
"""Make a JSON object for a RECAP docket and upload it to IA"""
d, json_str = generate_ia_json(pk, database=database)
file_name = get_docket_filename(d.court_id, d.pacer_case_id, "json")
bucket_name = get_bucket_name(d.court_id, d.pacer_case_id)
responses = upload_to_ia(
self,
identifier=bucket_name,
files={file_name: BytesIO(json_str.encode())},
title=best_case_name(d),
collection=settings.IA_COLLECTIONS,
court_id=d.court_id,
source_url=f"https://www.courtlistener.com{d.get_absolute_url()}",
media_type="texts",
description="This item represents a case in PACER, the U.S. "
"Government's website for federal case data. This "
"information is uploaded quarterly. To see our most "
"recent version please use the source url parameter, "
"linked below. To see the canonical source for this data, "
"please consult PACER directly.",
)
if responses is None:
increment_failure_count(d)
return
if all(r.ok for r in responses):
d.ia_upload_failure_count = None
d.ia_date_first_changed = None
d.ia_needs_upload = False
d.filepath_ia_json = (
f"https://archive.org/download/{bucket_name}/{file_name}"
)
d.save()
else:
increment_failure_count(d)
@app.task(bind=True, max_retries=5)
def download_recap_item(
self,
url: str,
filename: str,
clobber: bool = False,
) -> None:
logger.info(f" Getting item at: {url}")
location = os.path.join(settings.MEDIA_ROOT, "recap", filename)
try:
if os.path.isfile(location) and not clobber:
raise IOError(f" IOError: File already exists at {location}")
r = requests.get(
url,
stream=True,
timeout=60,
headers={"User-Agent": "Free Law Project"},
)
r.raise_for_status()
except requests.Timeout as e:
logger.warning(f" Timed out attempting to get: {url}\n")
raise self.retry(exc=e, countdown=2)
except requests.RequestException as e:
logger.warning(f" Unable to get {url}\nException was:\n{e}")
except IOError as e:
logger.warning(f" {e}")
else:
with NamedTemporaryFile(prefix="recap_download_") as tmp:
r.raw.decode_content = True
try:
shutil.copyfileobj(r.raw, tmp)
tmp.flush()
except ReadTimeoutError as exc:
# The download failed part way through.
raise self.retry(exc=exc)
else:
# Successful download. Copy from tmp to the right spot. Note
# that this will clobber.
shutil.copyfile(tmp.name, location)
@app.task(bind=True, max_retries=2, soft_time_limit=240)
def get_and_save_free_document_report(
self: Task,
court_id: str,
start: date,
end: date,
) -> int:
"""Download the Free document report and save it to the DB.
:param self: The Celery task.
:param court_id: A pacer court id.
:param start: a date object representing the first day to get results.
:param end: a date object representing the last day to get results.
:return: The status code of the scrape
"""
cookies = get_or_cache_pacer_cookies(
"pacer_scraper",
username=settings.PACER_USERNAME,
password=settings.PACER_PASSWORD,
)
s = PacerSession(
cookies=cookies,
username=settings.PACER_USERNAME,
password=settings.PACER_PASSWORD,
)
report = FreeOpinionReport(court_id, s)
msg = ""
try:
report.query(start, end, sort="case_number")
except (
TypeError,
RequestException,
ReadTimeoutError,
PacerLoginException,
ParsingException,
SoftTimeLimitExceeded,
ValueError,
) as exc:
if isinstance(exc, (TypeError, ValueError)):
msg = (
"TypeError getting free document report results, likely due "
"to failure to get Nonce."
)
elif isinstance(exc, (RequestException, ReadTimeoutError)):
msg = "Unable to get free document report results"
elif isinstance(exc, PacerLoginException):
msg = "PacerLoginException while getting free docs"
elif isinstance(exc, ParsingException):
if "nonce" in f"{exc}":
msg = "Didn't get Nonce"
elif "XML" in f"{exc}":
msg = (
"Written opinion reports are blocked. Please "
"contact the court director"
)
else:
msg = "Unknown parsing error in written opinion report"
elif isinstance(exc, SoftTimeLimitExceeded):
msg = "Soft time limit exceeded"
else:
msg = "An unknown error ocurred while getting an opinion report"
if self.request.retries == self.max_retries:
logger.error(f"{msg} at %s (%s to %s).", court_id, start, end)
return PACERFreeDocumentLog.SCRAPE_FAILED
logger.info(f"{msg} Retrying.", court_id, start, end)
raise self.retry(exc=exc, countdown=5)
try:
results = report.data
except (IndexError, HTTPError) as exc:
# IndexError: When the page isn't downloaded properly.
# HTTPError: raise_for_status in parse hit bad status.
if self.request.retries == self.max_retries:
return PACERFreeDocumentLog.SCRAPE_FAILED
raise self.retry(exc=exc, countdown=5)
for row in results:
PACERFreeDocumentRow.objects.create(
court_id=row.court_id,
pacer_case_id=row.pacer_case_id,
docket_number=row.docket_number,
case_name=row.case_name,
date_filed=row.date_filed,
pacer_doc_id=row.pacer_doc_id,
pacer_seq_no=row.pacer_seq_no,
document_number=row.document_number,
description=row.description,
nature_of_suit=row.nature_of_suit,
cause=row.cause,
)
return PACERFreeDocumentLog.SCRAPE_SUCCESSFUL
@app.task(bind=True, max_retries=5, ignore_result=True)
@throttle_task("2/s", key="court_id")
def process_free_opinion_result(
self,
row_pk: int,
court_id: str,
cnt: CaseNameTweaker,
) -> Optional[TaskData]:
"""Add data from a free opinion report to our DB
:param self: The celery task
:param row_pk: The pk of the PACERFreeDocumentRow to get
:param court_id: The court where the item was found, used for throttling
:param cnt: A case name tweaker, since they're expensive to initialize
:return a dict containing the free document row, the court id, etc.
"""
try:
result = PACERFreeDocumentRow.objects.get(pk=row_pk)
except PACERFreeDocumentRow.DoesNotExist:
logger.warning(f"Unable to find PACERFreeDocumentRow: {row_pk}")
self.request.chain = None
return None
result.court = Court.objects.get(pk=map_pacer_to_cl_id(result.court_id))
result.case_name = harmonize(result.case_name)
result.case_name_short = cnt.make_case_name_short(result.case_name)
row_copy = copy.copy(result)
# If we don't do this, the doc's date_filed becomes the docket's
# date_filed. Bad.
delattr(row_copy, "date_filed")
# If we don't do this, we get the PACER court id and it crashes
delattr(row_copy, "court_id")
# If we don't do this, the id of result tries to smash that of the docket.
delattr(row_copy, "id")
start_time = now()
try:
with transaction.atomic():
d = lookup_and_save(row_copy)
if not d:
msg = f"Unable to create docket for {result}"
logger.error(msg)
result.error_msg = msg
result.save()
self.request.chain = None
return None
d.blocked, d.date_blocked = get_blocked_status(d)
mark_ia_upload_needed(d, save_docket=False)
d.save()
try:
de, _ = DocketEntry.objects.update_or_create(
docket=d,
entry_number=result.document_number,
defaults={
"date_filed": result.date_filed,
"description": result.description,
},
)
except DocketEntry.MultipleObjectsReturned:
# This shouldn't happen, but sometimes it does. Handle it.
de = DocketEntry.objects.filter(
docket=d, entry_number=result.document_number
).earliest("pk")
de.date_filed = result.date_filed
de.description = result.description
# Update the psn if we have a new value
de.pacer_sequence_number = (
result.pacer_seq_no or de.pacer_sequence_number
)
# When rsn is generated by the free opinion report, it's poor
# quality (these entries come in isolation). When it is generated
# by a docket or other source, it tends to be better. Prefer an
# existing rsn if we have it.
recap_sequence_number = make_recap_sequence_number(
{"date_filed": result.date_filed, "recap_sequence_index": 1}
)
de.recap_sequence_number = (
de.recap_sequence_number or recap_sequence_number
)
de.save()
rds = RECAPDocument.objects.filter(
docket_entry=de,
document_number=result.document_number,
attachment_number=None,
)
rd_count = rds.count()
if rd_count == 0:
rd = RECAPDocument.objects.create(
docket_entry=de,
document_number=result.document_number,
attachment_number=None,
pacer_doc_id=result.pacer_doc_id,
document_type=RECAPDocument.PACER_DOCUMENT,
is_free_on_pacer=True,
)
rd_created = True
elif rd_count > 0:
# Could be one item (great!) or more than one (not great).
# Choose the earliest item and upgrade it.
rd = rds.earliest("date_created")
rd.pacer_doc_id = result.pacer_doc_id
rd.document_type = RECAPDocument.PACER_DOCUMENT
rd.is_free_on_pacer = True
rd.save()
rd_created = False
except IntegrityError as e:
msg = f"Raised IntegrityError: {e}"
logger.error(msg)
if self.request.retries == self.max_retries:
result.error_msg = msg
result.save()
return None
raise self.retry(exc=e)
except DatabaseError as e:
msg = f"Unable to complete database transaction:\n{e}"
logger.error(msg)
result.error_msg = msg
result.save()
self.request.chain = None
return None
if not rd_created and rd.is_available:
# The item already exists and is available. Fantastic. Call it a day.
result.delete()
self.request.chain = None
return None
if rd_created:
newly_enqueued = enqueue_docket_alert(d.pk)
if newly_enqueued:
send_docket_alert(d.pk, start_time)
return {
"result": result,
"rd_pk": rd.pk,
"pacer_court_id": result.court_id,
}
@app.task(
bind=True,
max_retries=15,
interval_start=5,
interval_step=5,
ignore_result=True,
)
@throttle_task("1/s", key="court_id")
def get_and_process_free_pdf(
self: Task,
data: TaskData,
row_pk: int,
court_id: str,
) -> Optional[TaskData]:
"""Get a PDF from a PACERFreeDocumentRow object
:param self: The celery task
:param data: The returned results from the previous task, takes the form
of:
{'result': <PACERFreeDocumentRow> object,
'rd_pk': rd.pk,
'pacer_court_id': result.court_id}
:param row_pk: The PACERFreeDocumentRow operate on
:param court_id: The court_id (used for throttling).
"""
if data is None:
return None
result = data["result"]
rd = RECAPDocument.objects.get(pk=data["rd_pk"])
cookies = get_or_cache_pacer_cookies(
"pacer_scraper",
username=settings.PACER_USERNAME,
password=settings.PACER_PASSWORD,
)
try:
r = download_pacer_pdf_by_rd(
rd.pk, result.pacer_case_id, result.pacer_doc_id, cookies
)
except PacerLoginException as exc:
msg = "PacerLoginException while getting free docs."
if self.request.retries == self.max_retries:
logger.warning(msg)
self.request.chain = None
return None
logger.info(f"{msg} Retrying.")
raise self.retry(exc=exc)
except (ReadTimeoutError, requests.RequestException) as exc:
msg = "Request exception getting free PDF"
if self.request.retries == self.max_retries:
logger.warning(msg)
self.request.chain = None
return None
logger.info(f"{msg} Retrying.")
raise self.retry(exc=exc)
attachment_number = 0 # Always zero for free opinions
success, msg = update_rd_metadata(
self,
rd.pk,
r,
result.court_id,
result.pacer_case_id,
result.pacer_doc_id,
result.document_number,
attachment_number,
)
if success is False:
PACERFreeDocumentRow.objects.filter(pk=row_pk).update(error_msg=msg)
return None
rd.refresh_from_db()
rd.is_free_on_pacer = True
rd.save()
# Get the data temporarily. OCR is done for all nightly free
# docs in a separate batch, but may as well do the easy ones.
extract_recap_pdf(rd.pk, skip_ocr=True, check_if_needed=False)
return {"result": result, "rd_pk": rd.pk}
class OverloadedException(Exception):
pass
@app.task(bind=True, max_retries=15, interval_start=5, interval_step=5)
def upload_pdf_to_ia(self: Task, rd_pk: int) -> None:
rd = RECAPDocument.objects.get(pk=rd_pk)
d = rd.docket_entry.docket
file_name = get_document_filename(
d.court_id,
d.pacer_case_id,
rd.document_number,
rd.attachment_number or 0,
)
bucket_name = get_bucket_name(d.court_id, d.pacer_case_id)
responses = upload_to_ia(
self,
identifier=bucket_name,
files={file_name: rd.filepath_local},
title=best_case_name(d),
collection=settings.IA_COLLECTIONS,
court_id=d.court_id,
source_url=f"https://www.courtlistener.com{rd.get_absolute_url()}",
media_type="texts",
description="This item represents a case in PACER, the U.S. "
"Government's website for federal case data. If you wish "
"to see the entire case, please consult PACER directly.",
)
if responses is None:
increment_failure_count(rd)
return
if all(r.ok for r in responses):
rd.ia_upload_failure_count = None
rd.filepath_ia = (
f"https://archive.org/download/{bucket_name}/{file_name}"
)
rd.save()
else:
increment_failure_count(rd)
access_key = settings.IA_ACCESS_KEY
secret_key = settings.IA_SECRET_KEY
ia_session = ia.get_session(
{"s3": {"access": access_key, "secret": secret_key}}
)
def upload_to_ia(
self: Task,
identifier: str,
files: Union[str, List[str], List[BytesIO], Dict[str, BytesIO]],
title: str,
collection: List[str],
court_id: str,
source_url: str,
media_type: str,
description: str,
) -> Optional[List[Response]]:
"""Upload an item and its files to the Internet Archive
On the Internet Archive there are Items and files. Items have a global
identifier, and files go inside the item:
https://internetarchive.readthedocs.io/en/latest/items.html
This function mirrors the IA library's similar upload function,
but builds in retries and various assumptions that make
sense. Note that according to emails with IA staff, it is best to
maximize the number of files uploaded to an Item at a time, rather
than uploading each file in a separate go.
:param self: The celery task
:param identifier: The global identifier within IA for the item you wish to
work with.
:param files: This is a weird parameter from the IA library. It can accept:
- str: A path to the file to upload
- list: A list of paths to files or of file objects
- dict: A filename to file object/path mapping. It's unclear if a list of
these can be provided as an argument!
:param title: The title of the item in IA
:param collection: The collection to add the item to in IA
:param court_id: The court ID info for the item
:param source_url: A URL link where the item can found
:param media_type: The IA mediatype value for the item
:param description: A description of the item
:rtype: list or None
:returns: List of response objects, one per file, or None if an error
occurred.
"""
try:
# Before pushing files, check if the endpoint is overloaded. This is
# lighter-weight than attempting a document upload off the bat.
if ia_session.s3_is_overloaded(identifier, access_key):
raise OverloadedException("S3 is currently overloaded.")
except OverloadedException as exc:
# Overloaded: IA wants us to slow down.
if self.request.retries == self.max_retries:
# Give up for now. It'll get done next time cron is run.
return None
raise self.retry(exc=exc)
logger.info(
"Uploading file to Internet Archive with identifier: %s and "
"files %s",
identifier,
files,
)
try:
item = ia_session.get_item(identifier)
responses = item.upload(
files=files,
metadata={
"title": title,
"collection": collection,
"contributor": '<a href="https://free.law">Free Law Project</a>',
"court": court_id,
"source_url": source_url,
"language": "eng",
"mediatype": media_type,
"description": description,
"licenseurl": "https://www.usa.gov/government-works",
},
queue_derive=False,
verify=True,
)
except ExpatError as exc:
# ExpatError: The syntax of the XML file that's supposed to be returned
# by IA is bad (or something).
if self.request.retries == self.max_retries:
# Give up for now. It'll get done next time cron is run.
return None
raise self.retry(exc=exc)
except HTTPError as exc:
if exc.response.status_code in [
HTTP_403_FORBIDDEN, # Can't access bucket, typically.
HTTP_400_BAD_REQUEST, # Corrupt PDF, typically.
]:
return [exc.response]
if self.request.retries == self.max_retries:
# This exception is also raised when the endpoint is
# overloaded, but doesn't get caught in the
# OverloadedException below due to multiple processes
# running at the same time. Just give up for now.
return None
raise self.retry(exc=exc)
except (requests.Timeout, requests.RequestException) as exc:
logger.warning(
"Timeout or unknown RequestException. Unable to upload "
"to IA. Trying again if retries not exceeded: %s",
identifier,
)
if self.request.retries == self.max_retries:
# Give up for now. It'll get done next time cron is run.
return None
raise self.retry(exc=exc)
except FileNotFoundError as exc:
# For some reason the file path is populated but no good. No point in
# retrying. Just abort.
return None
logger.info(
"Item uploaded to IA with responses %s"
% [r.status_code for r in responses]
)
return responses
@app.task
def mark_court_done_on_date(
status: int, court_id: str, d: date
) -> Optional[int]:
court_id = map_pacer_to_cl_id(court_id)
try:
doc_log = PACERFreeDocumentLog.objects.filter(
status=PACERFreeDocumentLog.SCRAPE_IN_PROGRESS, court_id=court_id
).latest("date_queried")
except PACERFreeDocumentLog.DoesNotExist:
return None
else:
doc_log.date_queried = d
doc_log.status = status
doc_log.date_completed = now()
doc_log.save()
return status
@app.task(ignore_result=True)
def delete_pacer_row(data: TaskData, pk: int) -> List[int]:
try:
PACERFreeDocumentRow.objects.get(pk=pk).delete()
except PACERFreeDocumentRow.DoesNotExist:
pass
return [data["rd_pk"]]
def make_fjc_idb_lookup_params(
item: FjcIntegratedDatabase,
) -> Dict[str, Optional[str]]:
"""Given an IDB row, generate good params for looking up that item in the
PossibleCaseNumberApi.
:param item: The FjcIntegratedDatabase row you wish to work with.
:returns: A dict with params you can pass to get_pacer_case_id_and_title.
"""
params = {
"office_number": item.office if item.office else None,
}
if item.plaintiff or item.defendant:
# Note that criminal data lacks plaintiff or defendant info in IDB. We
# could try using "United States" as the plaintiff, but in many cases
# the plaintiff takes the form of a state. E.g. "Arizona, State of v.
# Luenig". For a random sample, see:
# https://www.courtlistener.com/?q=docketNumber%3Acr+AND+-case_name%3Aunited&type=r&order_by=random_123+desc.
# ∴ not much we can do here for criminal cases
params["case_name"] = f"{item.plaintiff} v. {item.defendant}"
if item.dataset_source in [CR_2017, CR_OLD]:
if item.multidistrict_litigation_docket_number:
params["docket_number_letters"] = "md"
else:
params["docket_number_letters"] = "cr"
elif item.dataset_source in [CV_2017, CV_2020, CV_OLD]:
params["docket_number_letters"] = "cv"
return params
@app.task(
bind=True,
max_retries=5,
interval_start=5 * 60,
interval_step=10 * 60,
ignore_results=True,
)
def get_pacer_case_id_and_title(
self: Task,
pass_through: Any,
docket_number: str,
court_id: str,
cookies: Optional[RequestsCookieJar] = None,
user_pk: Optional[int] = None,
case_name: Optional[str] = None,
office_number: Optional[str] = None,
docket_number_letters: Optional[str] = None,
) -> Optional[TaskData]:
"""Get the pacer_case_id and title values for a district court docket. Use
heuristics to disambiguate the results.
office_number and docket_number_letters are only needed when they are not
already part of the docket_number passed in. Multiple parameters are needed
here to allow flexibility when using this API. Some sources, like the IDB,
have this data all separated out, so it helps not to try to recreate docket
numbers from data that comes all pulled apart.
:param self: The celery task
:param pass_through: This data will be passed through as a key to the
returned dict for downstream tasks to receive.
:param docket_number: The docket number to look up. This is a flexible
field that accepts a variety of docket number styles.
:param court_id: The CourtListener court ID for the docket number
:param cookies: A requests.cookies.RequestsCookieJar with the cookies of a
logged-in PACER user.
:param user_pk: The PK of a user making the request. This can be provided
instead of the cookies parameter. If so, this will get the user's cookies
from redis instead of passing them in as an argument.
:param case_name: The case name to use for disambiguation. Disambiguation
is done in Juriscraper using edit distance.
:param office_number: The number (or letter) where the case took place.
Typically, this is in the beginning of the docket number before the colon.
This will be used for disambiguation. If you passed it as part of the
docket number, it is not needed here.
:param docket_number_letters: These are the letters, (cv, cr, md, etc.)
that may appear in a docket number. This is used for disambiguation. If
you passed these letters in the docket number, you do not need to pass
these letters again here.
:return: The dict formed by the PossibleCaseNumberApi lookup if a good
value is identified, else None. The dict takes the form of:
{
'docket_number': force_unicode(node.xpath('./@number')[0]),
'pacer_case_id': force_unicode(node.xpath('./@id')[0]),
'title': force_unicode(node.xpath('./@title')[0]),
'pass_through': pass_through,
}
"""
logger.info(
"Getting pacer_case_id for docket_number %s in court %s",
docket_number,
court_id,
)
if not cookies:
# Get cookies from Redis if not provided
cookies = get_pacer_cookie_from_cache(user_pk) # type: ignore
s = PacerSession(cookies=cookies)
report = PossibleCaseNumberApi(map_cl_to_pacer_id(court_id), s)
msg = ""
try:
report.query(docket_number)
except (RequestException, ReadTimeoutError, PacerLoginException) as exc:
if isinstance(exc, (RequestException, ReadTimeoutError)):
msg = (
"Network error while running possible case number query on: "
"%s.%s"
)
elif isinstance(exc, PacerLoginException):
msg = (
"PacerLoginException while running possible case number query "
"on: %s.%s"
)
if self.request.retries == self.max_retries:
logger.warning(msg, court_id, docket_number)
self.request.chain = None
return None
logger.info(f"{msg} Retrying.", court_id, docket_number)
raise self.retry(exc=exc)
try:
result = report.data(
case_name=case_name,
office_number=office_number,
docket_number_letters=docket_number_letters,
)
if result is not None:
result["pass_through"] = pass_through
return result
except ParsingException:
return None
@app.task(
bind=True,
max_retries=5,
interval_start=5 * 60,
interval_step=10 * 60,
ignore_result=True,
)
def do_case_query_by_pacer_case_id(
self: Task,
data: TaskData,
court_id: str,
cookies: RequestsCookieJar,
tag_names: List[str] = None,
) -> Optional[TaskData]:
"""Run a case query (iquery.pl) query on a case and save the data
:param self: The celery task
:param data: A dict containing at least the following: {
'pacer_case_id': The internal pacer case ID for the item.
}
:param court_id: A courtlistener court ID
:param cookies: A requests.cookies.RequestsCookieJar with the cookies of a
logged-in PACER user.
:param tag_names: A list of tag names to associate with the docket when
saving it in the DB.
:return: A dict with the pacer_case_id and docket_pk values.
"""
s = PacerSession(cookies=cookies)
if data is None:
logger.info("Empty data argument. Terminating chains and exiting.")
self.request.chain = None
return None
pacer_case_id = data.get("pacer_case_id")
report = CaseQuery(map_cl_to_pacer_id(court_id), s)
logger.info(f"Querying docket report {court_id}.{pacer_case_id}")
try:
d = Docket.objects.get(pacer_case_id=pacer_case_id, court_id=court_id)
except Docket.DoesNotExist:
d = None
except Docket.MultipleObjectsReturned:
d = None
report.query(pacer_case_id)
docket_data = report.data
logger.info(
f"Querying and parsing complete for {court_id}.{pacer_case_id}"
)
if not docket_data:
logger.info("No valid docket data for %s.%s", court_id, pacer_case_id)
self.request.chain = None
return None
# Merge the contents into CL.
if d is None:
d = find_docket_object(
court_id, pacer_case_id, docket_data["docket_number"]
)
d.add_recap_source()
update_docket_metadata(d, docket_data)
d.save()
add_tags_to_objs(tag_names, [d])