-
-
Notifications
You must be signed in to change notification settings - Fork 28
/
pages.py
708 lines (608 loc) · 22.6 KB
/
pages.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
"""crawl pages"""
import asyncio
import traceback
from datetime import datetime
from typing import TYPE_CHECKING, Optional, Tuple, List, Dict, Any, Union
from uuid import UUID, uuid4
from fastapi import Depends, HTTPException
import pymongo
from .models import (
Page,
PageOut,
PageOutWithSingleQA,
PageReviewUpdate,
PageQACompare,
Organization,
PaginatedResponse,
User,
PageNote,
PageNoteIn,
PageNoteEdit,
PageNoteDelete,
)
from .pagination import DEFAULT_PAGE_SIZE, paginated_format
from .utils import from_k8s_date, str_list_to_bools
if TYPE_CHECKING:
from .crawls import CrawlOps
from .orgs import OrgOps
from .storages import StorageOps
else:
CrawlOps = StorageOps = OrgOps = object
# ============================================================================
# pylint: disable=too-many-instance-attributes, too-many-arguments
class PageOps:
"""crawl pages"""
crawl_ops: CrawlOps
org_ops: OrgOps
storage_ops: StorageOps
def __init__(self, mdb, crawl_ops, org_ops, storage_ops):
self.pages = mdb["pages"]
self.crawls = mdb["crawls"]
self.crawl_ops = crawl_ops
self.org_ops = org_ops
self.storage_ops = storage_ops
async def init_index(self):
"""init index for pages db collection"""
await self.pages.create_index([("crawl_id", pymongo.HASHED)])
async def add_crawl_pages_to_db_from_wacz(self, crawl_id: str, batch_size=100):
"""Add pages to database from WACZ files"""
pages_buffer: List[Page] = []
try:
crawl = await self.crawl_ops.get_crawl_out(crawl_id)
stream = await self.storage_ops.sync_stream_wacz_pages(
crawl.resources or []
)
for page_dict in stream:
if not page_dict.get("url"):
continue
if len(pages_buffer) > batch_size:
await self._add_pages_to_db(pages_buffer)
pages_buffer.append(
self._get_page_from_dict(page_dict, crawl_id, crawl.oid)
)
# Add any remaining pages in buffer to db
if pages_buffer:
await self._add_pages_to_db(pages_buffer)
print(f"Added pages for crawl {crawl_id} to db", flush=True)
# pylint: disable=broad-exception-caught, raise-missing-from
except Exception as err:
traceback.print_exc()
print(f"Error adding pages for crawl {crawl_id} to db: {err}", flush=True)
def _get_page_from_dict(self, page_dict: Dict[str, Any], crawl_id: str, oid: UUID):
"""Return Page object from dict"""
page_id = page_dict.get("id")
if not page_id:
print(f'Page {page_dict.get("url")} has no id - assigning UUID', flush=True)
status = page_dict.get("status")
if not status and page_dict.get("loadState"):
status = 200
return Page(
id=page_id,
oid=oid,
crawl_id=crawl_id,
url=page_dict.get("url"),
title=page_dict.get("title"),
loadState=page_dict.get("loadState"),
status=status,
ts=(
from_k8s_date(page_dict.get("ts"))
if page_dict.get("ts")
else datetime.now()
),
)
async def _add_pages_to_db(self, pages: List[Page]):
"""Add batch of pages to db in one insert"""
result = await self.pages.insert_many(
[
page.to_dict(
exclude_unset=True, exclude_none=True, exclude_defaults=True
)
for page in pages
]
)
if not result.inserted_ids:
# pylint: disable=broad-exception-raised
raise Exception("No pages inserted")
async def add_page_to_db(
self,
page_dict: Dict[str, Any],
crawl_id: str,
qa_run_id: Optional[str],
oid: UUID,
):
"""Add page to database"""
page = self._get_page_from_dict(page_dict, crawl_id, oid)
try:
await self.pages.insert_one(
page.to_dict(
exclude_unset=True, exclude_none=True, exclude_defaults=True
)
)
except pymongo.errors.DuplicateKeyError:
pass
# pylint: disable=broad-except
except Exception as err:
print(
f"Error adding page {page.id} from crawl {crawl_id} to db: {err}",
flush=True,
)
return
# qa data
if qa_run_id and page:
compare_dict = page_dict.get("comparison")
if compare_dict is None:
print("QA Run, but compare data missing!")
return
compare = PageQACompare(**compare_dict)
print("Adding QA Run Data for Page", page_dict.get("url"), compare)
await self.add_qa_run_for_page(page.id, oid, qa_run_id, compare)
async def delete_crawl_pages(self, crawl_id: str, oid: Optional[UUID] = None):
"""Delete crawl pages from db"""
query: Dict[str, Union[str, UUID]] = {"crawl_id": crawl_id}
if oid:
query["oid"] = oid
try:
await self.pages.delete_many(query)
# pylint: disable=broad-except
except Exception as err:
print(
f"Error deleting pages from crawl {crawl_id}: {err}",
flush=True,
)
async def get_page_raw(
self,
page_id: UUID,
oid: UUID,
crawl_id: Optional[str] = None,
) -> Dict[str, Any]:
"""Return page dict by id"""
query: Dict[str, Union[str, UUID]] = {"_id": page_id, "oid": oid}
if crawl_id:
query["crawl_id"] = crawl_id
page = await self.pages.find_one(query)
if not page:
raise HTTPException(status_code=404, detail="page_not_found")
return page
async def get_page(
self,
page_id: UUID,
oid: UUID,
crawl_id: Optional[str] = None,
) -> Page:
"""Return Page object by id"""
page_raw = await self.get_page_raw(page_id, oid, crawl_id)
return Page.from_dict(page_raw)
async def get_page_out(
self,
page_id: UUID,
oid: UUID,
crawl_id: Optional[str] = None,
qa_run_id: Optional[str] = None,
) -> Union[PageOut, PageOutWithSingleQA]:
"""Return PageOut or PageOutWithSingleQA for page"""
page_raw = await self.get_page_raw(page_id, oid, crawl_id)
if qa_run_id:
qa = page_raw.get("qa")
if qa and qa.get(qa_run_id):
page_raw["qa"] = qa.get(qa_run_id)
else:
print(
f"Error: Page {page_id} does not have data from QA run {qa_run_id}",
flush=True,
)
page_raw["qa"] = None
return PageOutWithSingleQA.from_dict(page_raw)
return PageOut.from_dict(page_raw)
async def add_qa_run_for_page(
self, page_id: UUID, oid: UUID, qa_run_id: str, compare: PageQACompare
) -> bool:
"""Update page heuristics and mime/type from QA run"""
# modified = datetime.utcnow().replace(microsecond=0, tzinfo=None)
result = await self.pages.find_one_and_update(
{"_id": page_id, "oid": oid},
{"$set": {f"qa.{qa_run_id}": compare.dict()}},
return_document=pymongo.ReturnDocument.AFTER,
)
if not result:
raise HTTPException(status_code=404, detail="page_not_found")
return True
async def delete_qa_run_from_pages(self, crawl_id: str, qa_run_id: str):
"""delete pages"""
result = await self.pages.update_many(
{"crawl_id": crawl_id}, {"$unset": {f"qa.{qa_run_id}": ""}}
)
return result
async def update_page_approval(
self,
page_id: UUID,
oid: UUID,
approved: Optional[bool] = None,
crawl_id: Optional[str] = None,
user: Optional[User] = None,
) -> Dict[str, bool]:
"""Update page manual review"""
query: Dict[str, Union[Optional[bool], str, datetime, UUID]] = {
"approved": approved
}
query["modified"] = datetime.utcnow().replace(microsecond=0, tzinfo=None)
if user:
query["userid"] = user.id
result = await self.pages.find_one_and_update(
{"_id": page_id, "oid": oid, "crawl_id": crawl_id},
{"$set": query},
return_document=pymongo.ReturnDocument.AFTER,
)
if not result:
raise HTTPException(status_code=404, detail="page_not_found")
return {"updated": True}
async def add_page_note(
self,
page_id: UUID,
oid: UUID,
text: str,
user: User,
crawl_id: str,
) -> Dict[str, bool]:
"""Add note to page"""
note = PageNote(id=uuid4(), text=text, userid=user.id, userName=user.name)
modified = datetime.utcnow().replace(microsecond=0, tzinfo=None)
result = await self.pages.find_one_and_update(
{"_id": page_id, "oid": oid, "crawl_id": crawl_id},
{
"$push": {"notes": note.dict()},
"$set": {"modified": modified},
},
return_document=pymongo.ReturnDocument.AFTER,
)
if not result:
raise HTTPException(status_code=404, detail="page_not_found")
return {"added": True}
async def update_page_note(
self,
page_id: UUID,
oid: UUID,
note_in: PageNoteEdit,
user: User,
crawl_id: str,
) -> Dict[str, bool]:
"""Update specific page note"""
page = await self.get_page_raw(page_id, oid)
page_notes = page.get("notes", [])
try:
matching_index = [
index
for index, note in enumerate(page_notes)
if note["id"] == note_in.id
][0]
except IndexError:
# pylint: disable=raise-missing-from
raise HTTPException(status_code=404, detail="page_note_not_found")
new_note = PageNote(
id=note_in.id, text=note_in.text, userid=user.id, userName=user.name
)
page_notes[matching_index] = new_note.dict()
modified = datetime.utcnow().replace(microsecond=0, tzinfo=None)
result = await self.pages.find_one_and_update(
{"_id": page_id, "oid": oid, "crawl_id": crawl_id},
{"$set": {"notes": page_notes, "modified": modified}},
return_document=pymongo.ReturnDocument.AFTER,
)
if not result:
raise HTTPException(status_code=404, detail="page_not_found")
return {"updated": True}
async def delete_page_notes(
self,
page_id: UUID,
oid: UUID,
delete: PageNoteDelete,
crawl_id: str,
) -> Dict[str, bool]:
"""Delete specific page notes"""
page = await self.get_page_raw(page_id, oid)
page_notes = page.get("notes", [])
remaining_notes = []
for note in page_notes:
if not note.get("id") in delete.delete_list:
remaining_notes.append(note)
modified = datetime.utcnow().replace(microsecond=0, tzinfo=None)
result = await self.pages.find_one_and_update(
{"_id": page_id, "oid": oid, "crawl_id": crawl_id},
{"$set": {"notes": remaining_notes, "modified": modified}},
return_document=pymongo.ReturnDocument.AFTER,
)
if not result:
raise HTTPException(status_code=404, detail="page_not_found")
return {"deleted": True}
async def list_pages(
self,
crawl_id: str,
org: Optional[Organization] = None,
qa_run_id: Optional[str] = None,
qa_filter_by: Optional[str] = None,
qa_gte: Optional[float] = None,
qa_gt: Optional[float] = None,
qa_lte: Optional[float] = None,
qa_lt: Optional[float] = None,
reviewed: Optional[bool] = None,
approved: Optional[List[Union[bool, None]]] = None,
has_notes: Optional[bool] = None,
page_size: int = DEFAULT_PAGE_SIZE,
page: int = 1,
sort_by: Optional[str] = None,
sort_direction: Optional[int] = -1,
) -> Tuple[Union[List[PageOut], List[PageOutWithSingleQA]], int]:
"""List all pages in crawl"""
# pylint: disable=duplicate-code, too-many-locals, too-many-branches, too-many-statements
# Zero-index page for query
page = page - 1
skip = page_size * page
query: dict[str, object] = {
"crawl_id": crawl_id,
}
if org:
query["oid"] = org.id
if reviewed:
query["$or"] = [
{"approved": {"$ne": None}},
{"notes.0": {"$exists": True}},
]
if reviewed is False:
query["$and"] = [
{"approved": {"$eq": None}},
{"notes.0": {"$exists": False}},
]
if approved:
query["approved"] = {"$in": approved}
if has_notes is not None:
query["notes.0"] = {"$exists": has_notes}
if qa_run_id:
query[f"qa.{qa_run_id}"] = {"$exists": True}
range_filter = {}
if qa_gte:
range_filter["$gte"] = qa_gte
if qa_lte:
range_filter["$lte"] = qa_lte
if qa_gt:
range_filter["$gt"] = qa_gt
if qa_lt:
range_filter["$lt"] = qa_lt
if qa_filter_by:
if not range_filter:
raise HTTPException(status_code=400, detail="range_missing")
query[f"qa.{qa_run_id}.{qa_filter_by}"] = range_filter
aggregate = [{"$match": query}]
if sort_by:
# Sorting options to add:
# - automated heuristics like screenshot_comparison (dict keyed by QA run id)
# - Ensure notes sorting works okay with notes in list
sort_fields = ("url", "title", "notes", "approved")
qa_sort_fields = ("screenshotMatch", "textMatch")
if sort_by not in sort_fields and sort_by not in qa_sort_fields:
raise HTTPException(status_code=400, detail="invalid_sort_by")
if sort_direction not in (1, -1):
raise HTTPException(status_code=400, detail="invalid_sort_direction")
if sort_by in qa_sort_fields:
if not qa_run_id:
raise HTTPException(
status_code=400, detail="qa_run_id_missing_for_qa_sort"
)
sort_by = f"qa.{qa_run_id}.{sort_by}"
aggregate.extend([{"$sort": {sort_by: sort_direction}}])
if qa_run_id:
aggregate.extend([{"$set": {"qa": f"$qa.{qa_run_id}"}}])
# aggregate.extend([{"$project": {"qa": f"$qa.{qa_run_id}"}}])
aggregate.extend(
[
{
"$facet": {
"items": [
{"$skip": skip},
{"$limit": page_size},
],
"total": [{"$count": "count"}],
}
},
]
)
# Get total
cursor = self.pages.aggregate(aggregate)
results = await cursor.to_list(length=1)
result = results[0]
items = result["items"]
try:
total = int(result["total"][0]["count"])
except (IndexError, ValueError):
total = 0
if qa_run_id:
return [PageOutWithSingleQA.from_dict(data) for data in items], total
return [PageOut.from_dict(data) for data in items], total
async def re_add_crawl_pages(self, crawl_id: str, oid: UUID):
"""Delete existing pages for crawl and re-add from WACZs."""
await self.delete_crawl_pages(crawl_id, oid)
print(f"Deleted pages for crawl {crawl_id}", flush=True)
await self.add_crawl_pages_to_db_from_wacz(crawl_id)
async def re_add_all_crawl_pages(self, oid: UUID):
"""Re-add pages for all crawls in org"""
crawl_ids = await self.crawls.distinct(
"_id", {"type": "crawl", "finished": {"$ne": None}}
)
for crawl_id in crawl_ids:
await self.re_add_crawl_pages(crawl_id, oid)
# ============================================================================
# pylint: disable=too-many-arguments, too-many-locals, invalid-name, fixme
def init_pages_api(app, mdb, crawl_ops, org_ops, storage_ops, user_dep):
"""init pages API"""
# pylint: disable=invalid-name
ops = PageOps(mdb, crawl_ops, org_ops, storage_ops)
org_crawl_dep = org_ops.org_crawl_dep
@app.post("/orgs/{oid}/crawls/all/pages/reAdd", tags=["pages"])
async def re_add_all_crawl_pages(
org: Organization = Depends(org_crawl_dep), user: User = Depends(user_dep)
):
"""Re-add pages for all crawls in org (superuser only)"""
if not user.is_superuser:
raise HTTPException(status_code=403, detail="Not Allowed")
asyncio.create_task(ops.re_add_all_crawl_pages(org.id))
return {"started": True}
@app.post("/orgs/{oid}/crawls/{crawl_id}/pages/reAdd", tags=["pages"])
async def re_add_crawl_pages(
crawl_id: str, org: Organization = Depends(org_crawl_dep)
):
"""Re-add pages for crawl"""
asyncio.create_task(ops.re_add_crawl_pages(crawl_id, org.id))
return {"started": True}
@app.get(
"/orgs/{oid}/crawls/{crawl_id}/pages/{page_id}",
tags=["pages"],
response_model=PageOut,
)
async def get_page(
crawl_id: str,
page_id: UUID,
org: Organization = Depends(org_crawl_dep),
):
"""GET single page"""
return await ops.get_page_out(page_id, org.id, crawl_id)
@app.get(
"/orgs/{oid}/crawls/{crawl_id}/qa/{qa_run_id}/pages/{page_id}",
tags=["pages", "qa"],
response_model=PageOutWithSingleQA,
)
async def get_page_with_qa(
crawl_id: str,
qa_run_id: str,
page_id: UUID,
org: Organization = Depends(org_crawl_dep),
):
"""GET single page"""
return await ops.get_page_out(page_id, org.id, crawl_id, qa_run_id=qa_run_id)
@app.patch(
"/orgs/{oid}/crawls/{crawl_id}/pages/{page_id}",
tags=["pages"],
)
async def update_page_approval(
crawl_id: str,
page_id: UUID,
update: PageReviewUpdate,
org: Organization = Depends(org_crawl_dep),
user: User = Depends(user_dep),
):
"""Update review for specific page"""
return await ops.update_page_approval(
page_id, org.id, update.approved, crawl_id, user
)
@app.post(
"/orgs/{oid}/crawls/{crawl_id}/pages/{page_id}/notes",
tags=["pages"],
)
async def add_page_note(
crawl_id: str,
page_id: UUID,
note: PageNoteIn,
org: Organization = Depends(org_crawl_dep),
user: User = Depends(user_dep),
):
"""Add note to page"""
return await ops.add_page_note(page_id, org.id, note.text, user, crawl_id)
@app.patch(
"/orgs/{oid}/crawls/{crawl_id}/pages/{page_id}/notes",
tags=["pages"],
)
async def edit_page_note(
crawl_id: str,
page_id: UUID,
note: PageNoteEdit,
org: Organization = Depends(org_crawl_dep),
user: User = Depends(user_dep),
):
"""Edit page note"""
return await ops.update_page_note(page_id, org.id, note, user, crawl_id)
@app.post(
"/orgs/{oid}/crawls/{crawl_id}/pages/{page_id}/notes/delete",
tags=["pages"],
)
async def delete_page_notes(
crawl_id: str,
page_id: UUID,
delete: PageNoteDelete,
org: Organization = Depends(org_crawl_dep),
):
"""Edit page note"""
return await ops.delete_page_notes(page_id, org.id, delete, crawl_id)
@app.get(
"/orgs/{oid}/crawls/{crawl_id}/pages",
tags=["pages"],
response_model=PaginatedResponse,
)
async def get_pages_list(
crawl_id: str,
org: Organization = Depends(org_crawl_dep),
reviewed: Optional[bool] = None,
approved: Optional[str] = None,
hasNotes: Optional[bool] = None,
pageSize: int = DEFAULT_PAGE_SIZE,
page: int = 1,
sortBy: Optional[str] = None,
sortDirection: Optional[int] = -1,
):
"""Retrieve paginated list of pages"""
formatted_approved: Optional[List[Union[bool, None]]] = None
if approved:
formatted_approved = str_list_to_bools(approved.split(","))
pages, total = await ops.list_pages(
crawl_id=crawl_id,
org=org,
reviewed=reviewed,
approved=formatted_approved,
has_notes=hasNotes,
page_size=pageSize,
page=page,
sort_by=sortBy,
sort_direction=sortDirection,
)
return paginated_format(pages, total, page, pageSize)
@app.get(
"/orgs/{oid}/crawls/{crawl_id}/qa/{qa_run_id}/pages",
tags=["pages", "qa"],
response_model=PaginatedResponse,
)
async def get_pages_list_with_qa(
crawl_id: str,
qa_run_id: str,
filterQABy: Optional[str] = None,
gte: Optional[float] = None,
gt: Optional[float] = None,
lte: Optional[float] = None,
lt: Optional[float] = None,
reviewed: Optional[bool] = None,
approved: Optional[str] = None,
hasNotes: Optional[bool] = None,
org: Organization = Depends(org_crawl_dep),
pageSize: int = DEFAULT_PAGE_SIZE,
page: int = 1,
sortBy: Optional[str] = None,
sortDirection: Optional[int] = -1,
):
"""Retrieve paginated list of pages"""
formatted_approved: Optional[List[Union[bool, None]]] = None
if approved:
formatted_approved = str_list_to_bools(approved.split(","))
pages, total = await ops.list_pages(
crawl_id=crawl_id,
org=org,
qa_run_id=qa_run_id,
qa_filter_by=filterQABy,
qa_gte=gte,
qa_gt=gt,
qa_lte=lte,
qa_lt=lt,
reviewed=reviewed,
approved=formatted_approved,
has_notes=hasNotes,
page_size=pageSize,
page=page,
sort_by=sortBy,
sort_direction=sortDirection,
)
return paginated_format(pages, total, page, pageSize)
return ops