-
-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathappellate.js
More file actions
1326 lines (1181 loc) · 46.7 KB
/
Copy pathappellate.js
File metadata and controls
1326 lines (1181 loc) · 46.7 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
let acmsPageObserver = null;
// Abstraction of scripts related to Appellate PACER to make them modular and
// testable.
let AppellateDelegate = function (tabId, court, url, path, links) {
this.tabId = tabId;
this.court = court;
this.url = url;
this.path = path;
this.links = links || [];
this.queryParameters = APPELLATE.getQueryParameters(this.url);
this.docId = APPELLATE.getDocIdFromURL(this.queryParameters);
this.docketNumber = APPELLATE.getDocketNumber(this.queryParameters);
};
// Identify regular Appellate pages using the URL and the query string,
AppellateDelegate.prototype.regularAppellatePageHandler = function () {
let targetPage =
this.queryParameters.get('servlet') || APPELLATE.getServletFromInputs();
switch (targetPage) {
case 'CaseSummary.jsp':
this.handleDocketDisplayPage();
this.attachRecapLinksToEligibleDocs();
break;
case 'CaseSelectionTable.jsp':
this.handleCaseSelectionPage();
break;
case 'CaseSearch.jsp':
this.handleCaseSearchPage();
break;
case 'DocketReportFilter.jsp':
this.handleDocketReportFilter();
break;
case 'CaseQuery.jsp':
this.handleCaseQueryPage();
break;
case 'ShowDocMulti':
this.handleCombinedPdfPageView();
break;
default:
if (APPELLATE.isAttachmentPage()) {
this.handleAttachmentPage();
this.attachRecapLinksToEligibleDocs();
} else if (APPELLATE.isSingleDocumentPage()) {
this.handleSingleDocumentPageView();
} else {
console.info('No identified appellate page found');
}
break;
}
};
AppellateDelegate.prototype.ACMSPageHandler = function () {
// ACMS pages use HTMX for partial page updates, which means content loads
// asynchronously and replaces sections of the DOM without reloading the full
// page. Because of this, we use a MutationObserver to detect when specific
// ACMS components are injected into the DOM and trigger the appropriate
// handlers at the right time.
//
// The observer watches for additions to the DOM and runs the correct handler
// whenever a known ACMS page structure appears.
const pageObserver = async (mutationList, observer) => {
for (const r of mutationList) {
// We could restrict this to div#box, but that feels overspecific
for (const node of r.addedNodes) {
if (node.tagName !== 'DIV') continue;
if (node.id === 'indexContent' || node.id === 'fullDocketContent') {
this.handleAcmsDocket();
}
if (node.classList.contains('documents-list-wrapper')) {
this.handleAcmsAttachmentPage();
}
}
}
};
// If ACMS has already rendered the main content container (indexContent),
// we can immediately initialize the docket handler without waiting for
// HTMX updates. This handles cases where the page loads fully before
// the extension runs or when navigating back/forward.
if (
document.getElementById('indexContent') ||
document.getElementById('fullDocketContent')
) {
this.handleAcmsDocket();
}
if (acmsPageObserver) return;
// Always set up the observer to watch for HTMX updates, even if content
// is already present. HTMX can trigger partial page updates at any time,
// and we need to respond to those changes in both Chrome (node-by-node
// loading) and Firefox (full page already loaded).
const body = document.querySelector('body');
acmsPageObserver = new MutationObserver(pageObserver.bind(this));
acmsPageObserver.observe(body, { subtree: true, childList: true });
};
// Identify and handle pages from Appellate courts.
AppellateDelegate.prototype.dispatchPageHandler = function () {
if (PACER.isACMSWebsite(this.url)) {
this.ACMSPageHandler();
} else {
this.regularAppellatePageHandler();
}
};
AppellateDelegate.prototype.handleAcmsAttachmentPage = async function () {
const getDocketEntryId = async () => {
// Retrieves the docketEntryId associated with the currently
// displayed ACMS document viewer modal.
//
// This works by:
// 1. Reading the `docsToEntries` mapping stored in tab storage,
// which maps document IDs to docket entry IDs.
// 2. Locating the document viewer modal.
// 3. Extracting the `data-doc-id` from the first `.entry-link`
// element in the modal.
// 4. Returning the corresponding docketEntryId.
const tabStorage = await getItemsFromStorage(this.tabId);
const docsToEntries = tabStorage && tabStorage.docsToEntries;
const modal = document.getElementById('document-viewer-modal');
const links = modal.querySelectorAll('.entry-link');
return docsToEntries[links[0].dataset.docId];
};
const processAttachmentPage = async (entryId) => {
// Processes the ACMS attachment page by building a RECAP upload
// payload and sending it to the background for upload.
//
// Steps performed:
// 1. Reads the ACMS document view model from session storage.
// 2. Extracts the relevant case details and docket entry data.
// 3. Separates docket entry metadata from its documents to keep
// the payload structure consistent with existing RECAP uploads.
// 4. Sends the attachment page data to the background for upload.
// 5. Displays a success or failure notification to the user.
let caseData = JSON.parse(sessionStorage.recapDocViewModel);
const { caseDetails, docketEntries } = caseData;
const docketDetails = caseDetails[0];
this.pacer_case_id = docketDetails.caseId;
const options = await getItemsFromStorage('options');
if (!options['recap_enabled']) {
return console.info(
'RECAP: Not uploading docket json. RECAP is disabled.'
);
}
const docketEntryData = docketEntries.find(
(entry) => entry.docketEntryId == entryId
);
// Remove documents from the docketEntry object and send them
// separately to avoid nesting document data twice.
const { docketEntryDocuments, ...docketEntry } = docketEntryData;
let requestBody = {
caseDetails: docketDetails,
docketEntry,
docketEntryDocuments,
};
const upload = await dispatchBackgroundFetch({
action: 'upload',
data: {
court: PACER.convertToCourtListenerCourt(this.court),
pacer_case_id: this.pacer_case_id,
upload_type: 'ACMS_ATTACHMENT_PAGE',
html: JSON.stringify(requestBody),
},
});
if (upload.error) {
await dispatchBackgroundNotifier({
action: 'showUpload',
title: 'Page Upload Failed',
message: 'Error: The Attachment page was not uploaded to the public' +
'RECAP Archive',
});
}else{
history.replaceState({ uploaded: true }, '');
await dispatchBackgroundNotifier({
action: 'showUpload',
title: 'Page Successfully Uploaded',
message: 'Attachment page uploaded to the public RECAP Archive.',
});
}
};
const attachLinkToDocs = async (entryId) => {
// This function attaches links to available RECAP documents for each entry
// on the current page. It performs the following steps:
//
// 1. Retrieves docket entry and document data from session storage.
// 2. Collects all document entry links within the document viewer modal.
// 3. Queries the RECAP backend to check which documents are available.
// 4. Matches available documents using the `data-doc-id` attribute.
// 5. Inserts a RECAP icon linking to the free document next to
// each corresponding entry link.
let caseData = JSON.parse(sessionStorage.recapDocViewModel);
const { docketEntries } = caseData;
const docketEntryData = docketEntries.find(
(entry) => entry.docketEntryId == entryId
);
// Scope all DOM queries to the document viewer modal to avoid
// accidentally matching links elsewhere on the page.
const modal = document.getElementById('document-viewer-modal');
// Get all the entry links on the page. We use the "entry-link"
// class as a selector because all rows on the page
// consistently use this class.
this.links = modal.querySelectorAll('.entry-link');
if (!this.links.length) return;
let docIds = [docketEntryData.docketEntryId];
let clCourt = PACER.convertToCourtListenerCourt(this.court);
// Ask the server which documents for this docket entry
// are available from the RECAP Archive.
const recapLinks = await dispatchBackgroundFetch({
action: 'getAvailabilityForDocuments',
data: {
docket_entry__docket__court: clCourt,
pacer_doc_id__in: docIds.join(','),
},
});
for (result of recapLinks.results) {
let doc_guid = result.acms_document_guid;
// Query the docket entry link using the
// `data-doc-id` attribute embedded by ACMS.
let anchor = document.querySelector(
`[data-doc-id="${doc_guid}"]`
);
// Create the RECAP icon and link to the document.
let href = `https://storage.courtlistener.com/${result.filepath_local}`;
let recap_link = $('<a/>', {
title: 'Available for free from the RECAP Archive.',
href: href,
});
recap_link.append(
$('<img/>').attr({
src: chrome.runtime.getURL('assets/images/icon-16.png'),
})
);
let recap_div = $('<div>', {
class: 'recap-inline-appellate',
});
recap_div.append(recap_link);
// Insert the RECAP icon immediately after the
// corresponding ACMS document link.
recap_div.insertAfter(anchor);
}
};
const wrapperMutationObserver = async (mutationList, observer) => {
// Observes the ACMS attachment page for DOM changes and detects
// when the attachments section becomes available.
//
// The observer looks for an H4 element containing the text
// "documents are attached to this filing". Once detected:
// 1. The active docketEntryId is resolved from the document modal.
// 2. The attachment page is processed and uploaded to RECAP.
// 3. RECAP availability icons are attached to document links.
// 4. The observer disconnects to prevent duplicate work.
for (const r of mutationList) {
for (const n of r.addedNodes) {
// Look for the H4 either on the node itself or inside it
let h4 = n.tagName === 'H4' ? n : n.querySelector('h4');
if (!h4) continue;
let isAttachmentsTitle = n.textContent
.toLowerCase()
.includes('documents are attached to this filing');
if (!isAttachmentsTitle) continue;
let entryId = await getDocketEntryId();
processAttachmentPage(entryId);
attachLinkToDocs(entryId);
// Disconnect after the first successful match to avoid
// repeated uploads or duplicate icon insertion.
observer.disconnect();
}
}
};
const wrapper = document.querySelector('.documents-list-wrapper');
const observer = new MutationObserver(wrapperMutationObserver);
observer.observe(wrapper, { subtree: true, childList: true });
};
AppellateDelegate.prototype.handleAcmsDocket = async function () {
const getACMSCaseIdFromSession = async () => {
// Retrieves the pacer_case_id from the ACMS metadata stored in
// sessionStorage
let caseData = JSON.parse(sessionStorage.recapDocViewModel);
const { caseDetails } = caseData;
const docketDetails = caseDetails[0];
return docketDetails.caseId;
};
const processDocket = async () => {
// Uploads the ACMS docket JSON metadata to the RECAP archive.
//
// Steps performed:
// 1. Reads `recapDocViewModel` from sessionStorage, which contains both
// caseDetails and docketInfo as provided by ACMS.
// 2. Extracts only the fields required for RECAP.
// 3. Skips upload if the page was already uploaded in this session
// 4. Respects user preferences by checking if RECAP uploads are disabled.
// 5. Sends the structured docket metadata to the background worker for
// upload.
// 6. Displays a success notification if the upload completes without error
const caseData = JSON.parse(sessionStorage.recapDocViewModel);
// Only keep what we need
const { caseDetails, docketInfo } = caseData;
const docketDetails = caseDetails[0];
if (history.state && history.state.uploaded) return;
const options = await getItemsFromStorage('options');
if (!options['recap_enabled']) {
console.info('RECAP: Not uploading docket json. RECAP is disabled.');
return;
}
const upload = await dispatchBackgroundFetch({
action: 'upload',
data: {
court: PACER.convertToCourtListenerCourt(this.court),
pacer_case_id: this.pacer_case_id,
upload_type: 'ACMS_DOCKET_JSON',
html: JSON.stringify({ caseDetails: docketDetails, docketInfo }),
},
});
if (upload.error) return;
history.replaceState({ uploaded: true }, '');
await dispatchBackgroundNotifier({
action: 'showUpload',
title: 'Page Successfully Uploaded',
message: 'Docket uploaded to the public RECAP Archive.',
});
};
const insertRecapButton = async () => {
// Inserts the "RECAP actions" button at the top of the docket view.
// This function performs the following steps:
// 1. Locates the primary case-information table rendered by ACMS.
// 2. Checks whether a RECAP action button is already present to
// avoid duplicates.
// 3. If not present, creates a new RECAP actions button using
// the `recapActionsButton` function.
// 4. Queries RECAP for docket availability information.
// 5. If a single docket record exists:
// - Adds an alert button to the buttons dropdown menu.
// - Adds a search-in-RECAP link using the CL docket ID.
let caseInformationTable = document.querySelector('table.case-information');
// Get a reference to the parent node
const parentDiv = caseInformationTable.parentNode;
const existingActionButton = document.getElementById('recap-action-button');
if (!existingActionButton) {
let button = recapActionsButton(this.court, this.pacer_case_id, false);
parentDiv.insertBefore(button, caseInformationTable);
}
let docketData = await dispatchBackgroundFetch({
action: 'getAvailabilityForDocket',
data: {
court: PACER.convertToCourtListenerCourt(this.court),
pacer_case_id: this.pacer_case_id,
},
});
let docketDataCount = docketData.results.length;
if (docketDataCount == 1){
addAlertButtonInRecapAction(this.court, this.pacer_case_id);
let cl_id = getClIdFromAbsoluteURL(docketData.results[0].absolute_url);
addSearchDocketInRecapAction(cl_id);
} else{
PACER.handleDocketAvailabilityMessages(docketDataCount);
}
};
const attachLinkToDocs = async () => {
// Adds RECAP availability indicators to each docket entry link displayed
// in the ACMS docket view. It perform the following steps:
//
// 1. Data Retrieval:
// - Reads the full `recapDocViewModel` from sessionStorage.
// - Extract the array of `docketEntries`, each containing documents.
// - Query all `.entry-link` anchor tags rendered by ACMS.
//
// 2. Docket Entry Mapping:
// - For each link, read its `data-docket-entry-id`.
// - Look up the matching docketEntry in the `docketEntries` array.
// - Collect all docketEntryIds to be checked for RECAP availability.
// - Build a `docsToEntries` map that associates each ACMS document ID
// (`docketDocumentDetailsId`) with its parent docketEntryId.
// This mapping is later used by attachment pages and related workflows
//
// 3. RECAP Availability Check:
// - Query RECAP via the background worker, requesting availability for
// all collected docketEntryIds.
// - The court information is also included in the request.
//
// 4. Enriching Links with RECAP Information:
// For each available document:
// - Finds the matching anchor via its data attribute.
// - Creates a RECAP link pointing to the stored PDF.
// - Wraps the icon and link in a `.recap-inline-appellate` div.
// - Appends the div next to the docket entry’s link.
// Get the docket info from the sessionStorage obj
const recapDocViewModel = JSON.parse(sessionStorage.recapDocViewModel);
const docketEntries = recapDocViewModel.docketEntries;
// Get all the entry links on the page. We use the "entry-link"
// class as a selector because we observed that all non-restricted
// entries consistently use this class.
this.links = document.body.querySelectorAll('.entry-link');
if (!this.links.length) return;
// Go through the array of links and collect the doc IDs of
// the entries that are not restricted.
let docIds = [];
let docsToEntries = {};
for (link of this.links) {
const docketEntryId = link.dataset.docketEntryId;
const docketEntryData = docketEntries.find(
(entry) => entry.docketEntryId == docketEntryId
);
// add the id to the array of doc ids
docIds.push(docketEntryId);
for (const doc of docketEntryData.docketEntryDocuments) {
docsToEntries[doc.docketDocumentDetailsId] = docketEntryId;
}
}
let clCourt = PACER.convertToCourtListenerCourt(this.court);
// submit fetch request through background worker
const recapLinks = await dispatchBackgroundFetch({
action: 'getAvailabilityForDocuments',
data: {
docket_entry__docket__court: clCourt,
pacer_doc_id__in: docIds.join(','),
},
});
for (result of recapLinks.results) {
let doc_id = result.pacer_doc_id;
// Query the docket entry link using the data attribute
// attached previously
let anchor = document.querySelector(`[data-docket-entry-id="${doc_id}"]`);
// Create the RECAP icon
let href = `https://storage.courtlistener.com/${result.filepath_local}`;
let recap_link = $('<a/>', {
title: 'Available for free from the RECAP Archive.',
href: href,
});
recap_link.append(
$('<img/>').attr({
src: chrome.runtime.getURL('assets/images/icon-16.png'),
})
);
let recap_div = $('<div>', {
class: 'recap-inline-appellate',
});
recap_div.append(recap_link);
// Target the table row (<tr>) corresponding to this docket entry
let parent_tr = anchor.closest(`tr[data-docket-entry-id="${doc_id}"]`);
// Within that row, locate the span that contains the document links
const parent_span = parent_tr.querySelector("span.document-controls");
// Append the generated RECAP element to the controls area
parent_span.appendChild(recap_div[0]);
}
let spinner = document.getElementById('recap-button-spinner');
if (spinner) spinner.classList.add('recap-btn-spinner-hidden');
await updateTabStorage({
[this.tabId]: {
docsToEntries: docsToEntries,
},
});
};
await APPELLATE.storeMetaDataInSession();
this.pacer_case_id = await getACMSCaseIdFromSession();
processDocket();
await insertRecapButton();
await attachLinkToDocs();
};
AppellateDelegate.prototype.handleAcmsDownloadPage = async function () {
async function startUploadProcess() {
// This function initiates the upload process for a PDF document.
// It performs the following steps:
//
// 1. Prepares data for upload:
// - Parses download data from session storage and creates a request
// body for the PDF URL document.
//
// 2. Retrieves configuration and tokens:
// - Extracts API URL and token from session storage stored in
// the 'recapACMSConfiguration' key.
//
// 3. Extracts document information:
// - Extracts title from the element with class 'p.font-weight-bold'.
// - Parses relevant details (att_number) from the title.
// - Builds a documentData object containing docket number, document
// number, and attachment number.
//
// 4. Adds a loading message:
// - Creates a loading message using APPELLATE.createsLoadingMessage.
//
// 5. Stores case ID and document GUID (assumed for later use):
// - Saves case ID from download data.
// - Saves document GUID from download data.
//
// 6. Gets PDF download URL and initiates download:
// - Stores the current page HTML content.
// - Calls acms.getDocumentURL to get the PDF download URL.
// - Once the URL is retrieved, initiates an HTTP request to download
// the PDF.
// - Binds the handleDocFormResponse function to handle the downloaded
// data and document information after download completes.
let downloadData = JSON.parse(
sessionStorage.getItem('recapVueData')
);
const pdfFileRequestBody =
APPELLATE.createAcmsDocumentRequestBody(downloadData);
// Get the ACMS API URL and token from the sessionStorage object
let appConfiguration = JSON.parse(
sessionStorage.getItem('recapACMSConfiguration')
);
let { ApiUrl } = appConfiguration.AppSettings;
let { Token } = appConfiguration.AuthToken;
// Collect relevant document information to upload PDF to CL
let title = document.querySelector('p.font-weight-bold').innerHTML.trim();
let dataFromTitle = APPELLATE.parseReceiptPageTitle(title);
let documentData = {
docket_number: downloadData.caseSummary.caseDetails.caseNumber,
doc_number: downloadData.docketEntry.entryNumber,
att_number:
downloadData.docketEntry.documentCount > 1
? dataFromTitle.att_number
: null,
};
// Remove element from the page to show loading message
let mainDiv = document.querySelector('.download-confirmation-wrapper');
mainDiv.innerHTML = '';
loadingTextMessage = APPELLATE.createsLoadingMessage(downloadData);
mainDiv.append(loadingTextMessage);
// Get the pacer_case_id and document GUID from the sessionStorage object
this.pacer_case_id = downloadData.caseSummary.caseDetails.caseId;
this.acmsDocumentGuid =
downloadData.docketEntryDocuments[0].docketDocumentDetailsId;
let previousPageHtml = document.documentElement.innerHTML;
let pdf_url = await APPELLATE.fetchAcmsDocumentUrl({
apiUrl: ApiUrl,
token: Token,
mergePdfFilesRequest: pdfFileRequestBody,
});
const resp = await window.fetch(pdf_url, { method: 'GET' });
let requestHandler = handleDocFormResponse.bind(this);
requestHandler(
resp.headers.get('Content-Type'),
await resp.blob(),
null,
previousPageHtml,
documentData
);
}
const wrapperMutationObserver = async (mutationList, observer) => {
for (const r of mutationList) {
for (const n of r.addedNodes) {
let hasReceipt = n.textContent
.toLowerCase()
.includes('transaction receipt');
let hasAcceptChargesButton = n.textContent
.toLowerCase()
.includes('accept charges and retrieve');
// The `selectedDocuments` key in sessionStorage is only available when
// the download page is loaded from an attachment page. It is not
// available when loaded from a case summary entry. This check ensures
// the extension can handle both scenarios gracefully.
let hasOneDocument = true;
if (sessionStorage.getItem('selectedDocuments')) {
hasOneDocument =
JSON.parse(sessionStorage.selectedDocuments).length == 1;
}
if (
n.localName === 'div' &&
hasReceipt &&
hasAcceptChargesButton
) {
if (!hasOneDocument) {
pdfWarning = combinedPdfWarning();
n.append(pdfWarning);
return;
}
// Insert script to retrieve and store Vue data in the storage
await APPELLATE.storeVueDataInSession();
// Get doc_id from the sessionStorage
let downloadData = JSON.parse(sessionStorage.getItem('recapVueData'));
this.docId = downloadData.docketEntry.docketEntryId;
// Check if the accept charges button is already created on the page
let acceptChargesButton = document.querySelector('button');
if (!acceptChargesButton) {
return;
}
// Clone the "Accept charges" button to remove the onclick event.
// The default event handler retrieves an URL for the PDF and then
// navigate to this page, but if we wait until the handler finishes,
// we wont be able to use the same link to get the doc as a blob
// object because the URL seems to be a one-time-use link and
// attempting to access it after the handler has used it will result
// in an error message stating that the file retrieval attempt failed.
let clonedAcceptChargesButton = acceptChargesButton.cloneNode(true);
acceptChargesButton.replaceWith(clonedAcceptChargesButton);
// Add a custom onclick event to the Accept charges button.
// The handler of this new event performs an additional task before
// displaying the document. Upon clicking the button, the document
// retrieval process will remain unchanged, but the retrieved blob
// object will be uploaded to the RECAP archive before the document
// is rendered on the page.
clonedAcceptChargesButton.addEventListener(
'click',
startUploadProcess.bind(this)
);
// Query the server to check the availability of the document in the
// RECAP archive.
let clCourt = PACER.convertToCourtListenerCourt(this.court);
const recapLinks = await dispatchBackgroundFetch({
action: 'getAvailabilityForDocuments',
data: {
docket_entry__docket__court: clCourt,
pacer_doc_id__in: this.docId,
},
});
// return if there are no results
if (!recapLinks)
return console.error(
'RECAP: Failed getting availability for dockets.'
);
console.info(
'RECAP: Got results from API. Processing results to insert banner'
);
// To accurately identify ACMS documents, we should prioritize the
// `ACMS document details ID` stored in browser sessionStorage over
// the docket entry ID. This is because ACMS often uses the same URL
// for different attachments, making it ambiguous for identification
// purposes.
let acms_doc_id =
downloadData.docketEntryDocuments[0].docketDocumentDetailsId;
let result = recapLinks.results.filter(
(obj) => obj.acms_document_guid == acms_doc_id,
this
)[0];
if (!result) return;
insertAvailableDocBanner(result.filepath_local, 'div.box');
}
};
};
};
const wrapper = document.getElementsByClassName(
'download-confirmation-wrapper'
)[0];
const observer = new MutationObserver(wrapperMutationObserver);
observer.observe(wrapper, { subtree: true, childList: true });
};
AppellateDelegate.prototype.handleCaseSearchPage = () => {
if (!PACER.hasFilingCookie(document.cookie)) return;
form = document.querySelector('form');
if (!document.querySelector('.recap-email-banner-full')) {
form.appendChild(recapEmailBanner('recap-email-banner-full'));
}
};
AppellateDelegate.prototype.handleDocketReportFilter = async function () {
if (!this.docketNumber) return;
let docketNumberCore = PACER.makeDocketNumberCore(this.docketNumber);
this.pacer_case_id = await APPELLATE.getCaseId(
this.tabId,
this.queryParameters,
this.docId,
this.docketNumber
);
let docketData = await dispatchBackgroundFetch({
action: 'getAvailabilityForDocket',
data: {
court: PACER.convertToCourtListenerCourt(this.court),
docket_number_core: docketNumberCore,
},
});
let docketDataCount = docketData.results.length;
if (docketDataCount === 1) {
let form = document.getElementsByTagName('form')[0];
let banner = recapBanner(docketData.results[0]);
form.after(banner);
if (!this.pacer_case_id) return;
let recapAlert = document.createElement('div');
recapAlert.classList.add('recap-banner');
recapAlert.appendChild(
recapAlertButton(this.court, this.pacer_case_id, true)
);
form.after(recapAlert);
} else {
PACER.handleDocketAvailabilityMessages(docketDataCount);
}
};
AppellateDelegate.prototype.handleCaseSelectionPage = async function () {
if (document.querySelectorAll('input:not([type=hidden])').length) {
// When the users go back to the Case Selection Page from the Docket Report
// using the back button Appellate PACER loads the Case Search Page instead
// but in the HTML body has the servlet hidden input and shows
// 'CaseSelectionTable.jsp' as its value.
//
// This check avoids sending pages like the one previously described to the
// API.
if (!PACER.hasFilingCookie(document.cookie)) return;
form = document.querySelector('form');
if (!document.querySelector('.recap-email-banner-full')) {
form.appendChild(recapEmailBanner('recap-email-banner-full'));
}
return;
}
if (APPELLATE.caseSelectionPageHasOneRow()) {
// Retrieve pacer_case_id from the Case Query link
this.pacer_case_id = APPELLATE.getCaseIdFromCaseSelection();
let dataTable = APPELLATE.getTableWithDataFromCaseSelection();
let anchors = dataTable.querySelectorAll('a');
this.docketNumber = anchors[0].innerHTML;
await updateTabStorage({
[this.tabId]: {
caseId: this.pacer_case_id,
docketNumber: this.docketNumber,
},
});
let appellateData = await dispatchBackgroundFetch({
action: 'getAvailabilityForDocket',
data: {
court: PACER.convertToCourtListenerCourt(this.court),
pacer_case_id: this.pacer_case_id,
},
});
let appellateDataCount = appellateData.results.length;
if (appellateDataCount == 1) {
PACER.removeBanners();
const footer = document.querySelector('div.noprint:last-of-type');
const div = document.createElement('div');
div.classList.add('recap-banner');
div.appendChild(recapAlertButton(this.court, this.pacer_case_id, true));
footer.before(div);
const rIcon = APPELLATE.makeRButtonForCases(
appellateData.results[0].absolute_url
);
const appellateLink = anchors[0];
rIcon.insertAfter(appellateLink);
} else {
PACER.handleDocketAvailabilityMessages(appellateDataCount);
}
if (anchors.length == 3) {
let districtLink = anchors[anchors.length - 1];
let districtLinkData = APPELLATE.getDatafromDistrictLinkUrl(
districtLink.href
);
let districtData = await dispatchBackgroundFetch({
action: 'getAvailabilityForDocket',
data: {
court: PACER.convertToCourtListenerCourt(districtLinkData.court),
docket_number_core: districtLinkData.docket_number_core,
},
});
let districtDataCount = districtData.results.length;
if (districtDataCount == 1) {
const rIcon = APPELLATE.makeRButtonForCases(
districtData.results[0].absolute_url
);
rIcon.insertAfter(districtLink);
} else {
PACER.handleDocketAvailabilityMessages(districtDataCount);
}
}
} else {
// Add the pacer_case_id to each docket link to use it in the docket report
APPELLATE.addCaseIdToDocketSummaryLink();
}
const options = await getItemsFromStorage('options');
if (!options['recap_enabled']) {
console.info(
'RECAP: Not uploading case selection page. RECAP is disabled.'
);
return;
}
const upload = await dispatchBackgroundFetch({
action: 'upload',
data: {
court: PACER.convertToCourtListenerCourt(this.court),
pacer_case_id: this.pacer_case_id,
upload_type: 'APPELLATE_CASE_QUERY_RESULT_PAGE',
html: document.documentElement.innerHTML,
},
});
if (upload.error) return;
history.replaceState({ uploaded: true }, '');
await dispatchBackgroundNotifier({
action: 'showUpload',
title: 'Page Successfully Uploaded',
message: 'Case selection page uploaded to the public RECAP Archive.',
});
};
// Upload the case query page to RECAP
AppellateDelegate.prototype.handleCaseQueryPage = async function () {
this.pacer_case_id = await APPELLATE.getCaseId(
this.tabId,
this.queryParameters,
this.docId
);
if (!this.pacer_case_id) {
return;
}
await updateTabStorage({
[this.tabId]: {
caseId: this.pacer_case_id,
docketNumber: this.docketNumber,
},
});
const options = await getItemsFromStorage('options');
if (!options['recap_enabled']) return;
const upload = await dispatchBackgroundFetch({
action: 'upload',
data: {
court: PACER.convertToCourtListenerCourt(this.court),
pacer_case_id: this.pacer_case_id,
upload_type: 'APPELLATE_CASE_QUERY_PAGE',
html: document.documentElement.innerHTML,
}
});
if (upload.error) return;
history.replaceState({ uploaded: true }, '');
await dispatchBackgroundNotifier({
action: 'showUpload',
title: 'Page Successfully Uploaded',
message: 'Case query page uploaded to the public RECAP Archive.',
});
};
// check every link in the document to see if RECAP has it
AppellateDelegate.prototype.attachRecapLinksToEligibleDocs = async function () {
// When you click a document link, it runs JS that submits this form.
// Here, we override the target attribute of the form. If you don't do
// this, the form opens a new tab (target="_blank" by default), and
// we would be unable to link that tab back to the metadata we
// captured here. Thus, by overriding this form, we are able to
// maintain the context we need to upload docs to the archive.
let form = document.getElementsByName('doDocPostURLForm');
if (form.length) {
form[0].setAttribute('target', '_self');
}
// filter the links for the documents available on the page
let { links, docsToCases, docsToAttachmentNumbers } =
APPELLATE.findDocLinksFromAnchors(
this.links,
this.tabId,
this.queryParameters,
this.docketNumber
);
this.pacer_case_id = this.pacer_case_id
? this.pacer_case_id
: await APPELLATE.getCaseId(
this.tabId,
this.queryParameters,
this.docId,
this.docketNumber
);
if (this.pacer_case_id && this.docId) {
docsToCases[this.docId] = this.pacer_case_id;
}
updateTabStorage({
[this.tabId]: {
caseId: this.pacer_case_id,
docketNumber: this.docketNumber,
docsToCases: docsToCases,
docsToAttachmentNumbers: docsToAttachmentNumbers,
},
});
let linkCount = links.length;
console.info(
`RECAP: Attaching links to all eligible documents (${linkCount} found)`
);
if (linkCount === 0) return;
let clCourt = PACER.convertToCourtListenerCourt(this.court);
// submit fetch request through background worker
const recapLinks = await dispatchBackgroundFetch({
action: 'getAvailabilityForDocuments',
data: {
docket_entry__docket__court: clCourt,
pacer_doc_id__in: links.join(','),
},
});
// return if there are no results
if (!recapLinks)
return console.error('RECAP: Failed getting availability for dockets.');
console.info(
'RECAP: Got results from API. Processing results to attach links and ' +
'icons where appropriate.'
);
for (let i = 0; i < this.links.length; i++) {
let pacer_doc_id = this.links[i].dataset.pacerDocId;
if (!pacer_doc_id) continue;
let result = recapLinks.results.filter(function (obj) {
return obj.pacer_doc_id === pacer_doc_id;
})[0];
if (!result) continue;
let href = `https://storage.courtlistener.com/${result.filepath_local}`;
let recap_link = $('<a/>', {
title: 'Available for free from the RECAP Archive.',
href: href,
});
recap_link.append(
$('<img/>').attr({
src: chrome.runtime.getURL('assets/images/icon-16.png'),
})
);
let recap_div = $('<div>', {
class: 'recap-inline-appellate',
});
recap_div.append(recap_link);
recap_div.insertAfter(this.links[i]);
}
let spinner = document.getElementById('recap-button-spinner');
if (spinner)spinner.classList.add('recap-btn-spinner-hidden');
};
AppellateDelegate.prototype.handleDocketDisplayPage = async function () {
this.pacer_case_id = await APPELLATE.getCaseId(
this.tabId,
this.queryParameters,
this.docId,
this.docketNumber