2019-04-27 21:26:24 +00:00
|
|
|
__package__ = 'archivebox.index'
|
2019-04-19 01:09:54 +00:00
|
|
|
|
2017-07-04 10:38:07 +00:00
|
|
|
import os
|
2019-04-27 21:26:24 +00:00
|
|
|
import shutil
|
2020-08-20 19:34:49 +00:00
|
|
|
from pathlib import Path
|
2017-10-18 22:38:17 +00:00
|
|
|
|
2019-04-27 21:26:24 +00:00
|
|
|
from itertools import chain
|
|
|
|
from typing import List, Tuple, Dict, Optional, Iterable
|
2019-04-03 04:27:37 +00:00
|
|
|
from collections import OrderedDict
|
2019-04-19 01:09:54 +00:00
|
|
|
from contextlib import contextmanager
|
2020-08-17 07:12:17 +00:00
|
|
|
from urllib.parse import urlparse
|
2020-08-21 17:42:08 +00:00
|
|
|
from django.db.models import QuerySet, Q
|
2019-03-26 07:20:41 +00:00
|
|
|
|
2024-09-25 12:10:09 +00:00
|
|
|
|
2024-09-30 22:59:05 +00:00
|
|
|
from archivebox.config import DATA_DIR, CONSTANTS, SEARCH_BACKEND_CONFIG
|
2024-10-01 00:25:15 +00:00
|
|
|
from archivebox.misc.util import (
|
2019-04-27 21:26:24 +00:00
|
|
|
scheme,
|
|
|
|
enforce_types,
|
|
|
|
ExtendedEncoder,
|
|
|
|
)
|
2024-09-25 12:10:09 +00:00
|
|
|
from ..misc.logging import stderr
|
2024-09-30 22:59:05 +00:00
|
|
|
from ..config.legacy import (
|
2019-03-27 14:31:22 +00:00
|
|
|
TIMEOUT,
|
2023-07-31 03:43:04 +00:00
|
|
|
URL_DENYLIST_PTN,
|
|
|
|
URL_ALLOWLIST_PTN,
|
2020-07-22 21:41:43 +00:00
|
|
|
OUTPUT_PERMISSIONS
|
2017-07-05 21:33:51 +00:00
|
|
|
)
|
2020-07-22 16:02:13 +00:00
|
|
|
from ..logging_util import (
|
2019-05-01 03:13:04 +00:00
|
|
|
TimedProgress,
|
2019-04-27 21:26:24 +00:00
|
|
|
log_indexing_process_started,
|
|
|
|
log_indexing_process_finished,
|
|
|
|
log_indexing_started,
|
|
|
|
log_indexing_finished,
|
|
|
|
log_parsing_finished,
|
2020-07-13 15:26:30 +00:00
|
|
|
log_deduping_finished,
|
2019-04-27 21:26:24 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
from .schema import Link, ArchiveResult
|
|
|
|
from .html import (
|
|
|
|
write_html_link_details,
|
|
|
|
)
|
|
|
|
from .json import (
|
2021-01-30 11:07:35 +00:00
|
|
|
pyjson,
|
2019-04-17 06:25:28 +00:00
|
|
|
parse_json_link_details,
|
|
|
|
write_json_link_details,
|
|
|
|
)
|
2019-04-27 21:26:24 +00:00
|
|
|
from .sql import (
|
2019-04-17 07:49:18 +00:00
|
|
|
write_sql_main_index,
|
2020-06-30 17:45:47 +00:00
|
|
|
write_sql_link_details,
|
2019-04-17 07:49:18 +00:00
|
|
|
)
|
2017-10-18 22:38:17 +00:00
|
|
|
|
2020-11-20 04:39:28 +00:00
|
|
|
|
2019-04-03 04:27:37 +00:00
|
|
|
### Link filtering and checking
|
|
|
|
|
|
|
|
@enforce_types
|
|
|
|
def merge_links(a: Link, b: Link) -> Link:
|
|
|
|
"""deterministially merge two links, favoring longer field values over shorter,
|
|
|
|
and "cleaner" values over worse ones.
|
|
|
|
"""
|
2020-08-18 12:12:35 +00:00
|
|
|
assert a.base_url == b.base_url, f'Cannot merge two links with different URLs ({a.base_url} != {b.base_url})'
|
2019-04-03 04:27:37 +00:00
|
|
|
|
2019-04-17 06:25:28 +00:00
|
|
|
# longest url wins (because a fuzzy url will always be shorter)
|
2019-04-03 04:27:37 +00:00
|
|
|
url = a.url if len(a.url) > len(b.url) else b.url
|
|
|
|
|
2019-04-17 06:25:28 +00:00
|
|
|
# best title based on length and quality
|
2019-04-03 04:27:37 +00:00
|
|
|
possible_titles = [
|
|
|
|
title
|
|
|
|
for title in (a.title, b.title)
|
|
|
|
if title and title.strip() and '://' not in title
|
|
|
|
]
|
|
|
|
title = None
|
|
|
|
if len(possible_titles) == 2:
|
|
|
|
title = max(possible_titles, key=lambda t: len(t))
|
|
|
|
elif len(possible_titles) == 1:
|
|
|
|
title = possible_titles[0]
|
|
|
|
|
2019-04-17 06:25:28 +00:00
|
|
|
# earliest valid timestamp
|
2019-04-03 04:27:37 +00:00
|
|
|
timestamp = (
|
|
|
|
a.timestamp
|
|
|
|
if float(a.timestamp or 0) < float(b.timestamp or 0) else
|
|
|
|
b.timestamp
|
|
|
|
)
|
|
|
|
|
2019-04-17 06:25:28 +00:00
|
|
|
# all unique, truthy tags
|
2019-04-03 04:27:37 +00:00
|
|
|
tags_set = (
|
|
|
|
set(tag.strip() for tag in (a.tags or '').split(','))
|
|
|
|
| set(tag.strip() for tag in (b.tags or '').split(','))
|
|
|
|
)
|
|
|
|
tags = ','.join(tags_set) or None
|
|
|
|
|
2019-04-17 06:25:28 +00:00
|
|
|
# all unique source entries
|
2019-04-03 04:27:37 +00:00
|
|
|
sources = list(set(a.sources + b.sources))
|
|
|
|
|
2019-04-17 06:25:28 +00:00
|
|
|
# all unique history entries for the combined archive methods
|
2019-04-03 04:27:37 +00:00
|
|
|
all_methods = set(list(a.history.keys()) + list(a.history.keys()))
|
|
|
|
history = {
|
|
|
|
method: (a.history.get(method) or []) + (b.history.get(method) or [])
|
|
|
|
for method in all_methods
|
|
|
|
}
|
2019-04-11 07:41:25 +00:00
|
|
|
for method in all_methods:
|
|
|
|
deduped_jsons = {
|
2019-04-27 21:26:24 +00:00
|
|
|
pyjson.dumps(result, sort_keys=True, cls=ExtendedEncoder)
|
2019-04-11 07:41:25 +00:00
|
|
|
for result in history[method]
|
|
|
|
}
|
|
|
|
history[method] = list(reversed(sorted(
|
2019-04-27 21:26:24 +00:00
|
|
|
(ArchiveResult.from_json(pyjson.loads(result)) for result in deduped_jsons),
|
2019-04-11 07:41:25 +00:00
|
|
|
key=lambda result: result.start_ts,
|
|
|
|
)))
|
|
|
|
|
2019-04-03 04:27:37 +00:00
|
|
|
return Link(
|
|
|
|
url=url,
|
|
|
|
timestamp=timestamp,
|
|
|
|
title=title,
|
|
|
|
tags=tags,
|
|
|
|
sources=sources,
|
|
|
|
history=history,
|
|
|
|
)
|
|
|
|
|
2019-04-17 06:25:28 +00:00
|
|
|
|
|
|
|
@enforce_types
|
2019-04-27 21:26:24 +00:00
|
|
|
def validate_links(links: Iterable[Link]) -> List[Link]:
|
2019-05-01 06:28:26 +00:00
|
|
|
timer = TimedProgress(TIMEOUT * 4)
|
|
|
|
try:
|
|
|
|
links = archivable_links(links) # remove chrome://, about:, mailto: etc.
|
2020-12-26 00:31:03 +00:00
|
|
|
links = sorted_links(links) # deterministically sort the links based on timestamp, url
|
2020-08-18 12:30:09 +00:00
|
|
|
links = fix_duplicate_links(links) # merge/dedupe duplicate timestamps & urls
|
2019-05-01 06:28:26 +00:00
|
|
|
finally:
|
|
|
|
timer.end()
|
2019-04-03 04:27:37 +00:00
|
|
|
|
2019-04-27 21:26:24 +00:00
|
|
|
return list(links)
|
2019-04-03 04:27:37 +00:00
|
|
|
|
2019-04-17 06:25:28 +00:00
|
|
|
@enforce_types
|
2019-04-03 04:27:37 +00:00
|
|
|
def archivable_links(links: Iterable[Link]) -> Iterable[Link]:
|
|
|
|
"""remove chrome://, about:// or other schemed links that cant be archived"""
|
|
|
|
for link in links:
|
2020-08-17 07:12:17 +00:00
|
|
|
try:
|
|
|
|
urlparse(link.url)
|
|
|
|
except ValueError:
|
|
|
|
continue
|
2020-08-18 12:30:09 +00:00
|
|
|
if scheme(link.url) not in ('http', 'https', 'ftp'):
|
|
|
|
continue
|
2023-07-31 03:43:04 +00:00
|
|
|
if URL_DENYLIST_PTN and URL_DENYLIST_PTN.search(link.url):
|
2021-07-07 03:42:00 +00:00
|
|
|
continue
|
2023-07-31 03:43:04 +00:00
|
|
|
if URL_ALLOWLIST_PTN and (not URL_ALLOWLIST_PTN.search(link.url)):
|
2020-08-18 12:30:09 +00:00
|
|
|
continue
|
|
|
|
|
|
|
|
yield link
|
2019-04-03 04:27:37 +00:00
|
|
|
|
|
|
|
|
2019-04-17 06:25:28 +00:00
|
|
|
@enforce_types
|
2020-08-18 12:30:09 +00:00
|
|
|
def fix_duplicate_links(sorted_links: Iterable[Link]) -> Iterable[Link]:
|
2019-04-03 04:27:37 +00:00
|
|
|
"""
|
|
|
|
ensures that all non-duplicate links have monotonically increasing timestamps
|
|
|
|
"""
|
2020-08-18 13:22:12 +00:00
|
|
|
# from core.models import Snapshot
|
2019-04-03 04:27:37 +00:00
|
|
|
|
|
|
|
unique_urls: OrderedDict[str, Link] = OrderedDict()
|
|
|
|
|
|
|
|
for link in sorted_links:
|
2020-08-18 12:30:09 +00:00
|
|
|
if link.url in unique_urls:
|
2019-04-03 04:27:37 +00:00
|
|
|
# merge with any other links that share the same url
|
2020-08-18 12:30:09 +00:00
|
|
|
link = merge_links(unique_urls[link.url], link)
|
|
|
|
unique_urls[link.url] = link
|
|
|
|
|
|
|
|
return unique_urls.values()
|
2019-04-03 04:27:37 +00:00
|
|
|
|
|
|
|
|
2019-04-17 06:25:28 +00:00
|
|
|
@enforce_types
|
2019-04-03 04:27:37 +00:00
|
|
|
def sorted_links(links: Iterable[Link]) -> Iterable[Link]:
|
|
|
|
sort_func = lambda link: (link.timestamp.split('.', 1)[0], link.url)
|
|
|
|
return sorted(links, key=sort_func, reverse=True)
|
|
|
|
|
|
|
|
|
2019-04-17 06:25:28 +00:00
|
|
|
@enforce_types
|
|
|
|
def links_after_timestamp(links: Iterable[Link], resume: Optional[float]=None) -> Iterable[Link]:
|
2019-04-03 04:27:37 +00:00
|
|
|
if not resume:
|
|
|
|
yield from links
|
|
|
|
return
|
|
|
|
|
|
|
|
for link in links:
|
|
|
|
try:
|
|
|
|
if float(link.timestamp) <= resume:
|
|
|
|
yield link
|
|
|
|
except (ValueError, TypeError):
|
|
|
|
print('Resume value and all timestamp values must be valid numbers.')
|
|
|
|
|
|
|
|
|
2019-04-17 06:25:28 +00:00
|
|
|
@enforce_types
|
2019-04-03 04:27:37 +00:00
|
|
|
def lowest_uniq_timestamp(used_timestamps: OrderedDict, timestamp: str) -> str:
|
|
|
|
"""resolve duplicate timestamps by appending a decimal 1234, 1234 -> 1234.1, 1234.2"""
|
|
|
|
|
|
|
|
timestamp = timestamp.split('.')[0]
|
|
|
|
nonce = 0
|
|
|
|
|
|
|
|
# first try 152323423 before 152323423.0
|
|
|
|
if timestamp not in used_timestamps:
|
|
|
|
return timestamp
|
|
|
|
|
|
|
|
new_timestamp = '{}.{}'.format(timestamp, nonce)
|
|
|
|
while new_timestamp in used_timestamps:
|
|
|
|
nonce += 1
|
|
|
|
new_timestamp = '{}.{}'.format(timestamp, nonce)
|
|
|
|
|
|
|
|
return new_timestamp
|
|
|
|
|
|
|
|
|
2019-03-27 22:24:30 +00:00
|
|
|
|
2019-04-17 06:25:28 +00:00
|
|
|
### Main Links Index
|
2017-10-18 22:38:17 +00:00
|
|
|
|
2019-04-19 01:09:54 +00:00
|
|
|
@contextmanager
|
2019-03-27 02:26:21 +00:00
|
|
|
@enforce_types
|
2020-09-07 22:49:14 +00:00
|
|
|
def timed_index_update(out_path: Path):
|
2019-04-19 01:09:54 +00:00
|
|
|
log_indexing_started(out_path)
|
2019-04-17 07:49:18 +00:00
|
|
|
timer = TimedProgress(TIMEOUT * 2, prefix=' ')
|
|
|
|
try:
|
2019-04-19 01:09:54 +00:00
|
|
|
yield
|
2019-04-17 07:49:18 +00:00
|
|
|
finally:
|
|
|
|
timer.end()
|
|
|
|
|
2020-09-07 22:49:14 +00:00
|
|
|
assert out_path.exists(), f'Failed to write index file: {out_path}'
|
2019-04-19 01:09:54 +00:00
|
|
|
log_indexing_finished(out_path)
|
|
|
|
|
|
|
|
|
|
|
|
@enforce_types
|
2024-09-30 22:59:05 +00:00
|
|
|
def write_main_index(links: List[Link], out_dir: Path=DATA_DIR, created_by_id: int | None=None) -> None:
|
2020-10-08 16:02:26 +00:00
|
|
|
"""Writes links to sqlite3 file for a given list of links"""
|
2019-04-19 01:09:54 +00:00
|
|
|
|
|
|
|
log_indexing_process_started(len(links))
|
|
|
|
|
2020-08-18 08:38:29 +00:00
|
|
|
try:
|
2024-09-30 22:59:05 +00:00
|
|
|
with timed_index_update(CONSTANTS.DATABASE_FILE):
|
2024-08-21 02:28:28 +00:00
|
|
|
write_sql_main_index(links, out_dir=out_dir, created_by_id=created_by_id)
|
2024-09-30 22:59:05 +00:00
|
|
|
os.chmod(CONSTANTS.DATABASE_FILE, int(OUTPUT_PERMISSIONS, base=8)) # set here because we don't write it with atomic writes
|
2020-08-18 08:38:29 +00:00
|
|
|
|
|
|
|
except (KeyboardInterrupt, SystemExit):
|
|
|
|
stderr('[!] Warning: Still writing index to disk...', color='lightyellow')
|
2020-12-02 22:28:26 +00:00
|
|
|
stderr(' Run archivebox init to fix any inconsistencies from an ungraceful exit.')
|
2024-09-30 22:59:05 +00:00
|
|
|
with timed_index_update(CONSTANTS.DATABASE_FILE):
|
2024-08-21 02:28:28 +00:00
|
|
|
write_sql_main_index(links, out_dir=out_dir, created_by_id=created_by_id)
|
2024-09-30 22:59:05 +00:00
|
|
|
os.chmod(CONSTANTS.DATABASE_FILE, int(OUTPUT_PERMISSIONS, base=8)) # set here because we don't write it with atomic writes
|
2020-08-18 08:38:29 +00:00
|
|
|
raise SystemExit(0)
|
2019-04-19 01:09:54 +00:00
|
|
|
|
|
|
|
log_indexing_process_finished()
|
2019-03-26 09:33:34 +00:00
|
|
|
|
2019-03-27 02:26:21 +00:00
|
|
|
@enforce_types
|
2024-10-01 00:44:18 +00:00
|
|
|
def load_main_index(out_dir: Path | str=DATA_DIR, warn: bool=True) -> List[Link]:
|
2019-03-21 05:28:12 +00:00
|
|
|
"""parse and load existing index with any new links from import_path merged in"""
|
2020-08-20 14:18:25 +00:00
|
|
|
from core.models import Snapshot
|
2020-08-18 08:38:29 +00:00
|
|
|
try:
|
2024-03-26 22:22:40 +00:00
|
|
|
return Snapshot.objects.all().only('id')
|
2020-08-18 16:45:27 +00:00
|
|
|
|
2020-08-18 08:38:29 +00:00
|
|
|
except (KeyboardInterrupt, SystemExit):
|
|
|
|
raise SystemExit(0)
|
2019-04-19 01:09:54 +00:00
|
|
|
|
2019-04-22 23:08:01 +00:00
|
|
|
@enforce_types
|
2024-09-30 22:59:05 +00:00
|
|
|
def load_main_index_meta(out_dir: Path=DATA_DIR) -> Optional[dict]:
|
|
|
|
index_path = out_dir / CONSTANTS.JSON_INDEX_FILENAME
|
2020-09-07 22:49:14 +00:00
|
|
|
if index_path.exists():
|
2019-04-22 23:08:01 +00:00
|
|
|
with open(index_path, 'r', encoding='utf-8') as f:
|
2019-04-27 21:26:24 +00:00
|
|
|
meta_dict = pyjson.load(f)
|
2019-04-22 23:08:01 +00:00
|
|
|
meta_dict.pop('links')
|
|
|
|
return meta_dict
|
|
|
|
|
|
|
|
return None
|
2019-04-19 01:09:54 +00:00
|
|
|
|
2020-07-13 15:26:30 +00:00
|
|
|
|
2019-04-19 01:09:54 +00:00
|
|
|
@enforce_types
|
2024-08-21 02:28:28 +00:00
|
|
|
def parse_links_from_source(source_path: str, root_url: Optional[str]=None, parser: str="auto") -> List[Link]:
|
2019-04-27 21:26:24 +00:00
|
|
|
|
2019-05-01 03:13:04 +00:00
|
|
|
from ..parsers import parse_links
|
|
|
|
|
2019-03-26 07:20:41 +00:00
|
|
|
new_links: List[Link] = []
|
2019-04-19 01:09:54 +00:00
|
|
|
|
|
|
|
# parse and validate the import file
|
2021-03-20 16:38:00 +00:00
|
|
|
raw_links, parser_name = parse_links(source_path, root_url=root_url, parser=parser)
|
2019-04-27 21:26:24 +00:00
|
|
|
new_links = validate_links(raw_links)
|
2019-03-21 05:28:12 +00:00
|
|
|
|
2020-07-13 15:26:30 +00:00
|
|
|
if parser_name:
|
|
|
|
num_parsed = len(raw_links)
|
|
|
|
log_parsing_finished(num_parsed, parser_name)
|
|
|
|
|
|
|
|
return new_links
|
|
|
|
|
|
|
|
@enforce_types
|
2020-08-21 14:57:29 +00:00
|
|
|
def fix_duplicate_links_in_index(snapshots: QuerySet, links: Iterable[Link]) -> Iterable[Link]:
|
|
|
|
"""
|
2020-09-08 14:49:30 +00:00
|
|
|
Given a list of in-memory Links, dedupe and merge them with any conflicting Snapshots in the DB.
|
2020-08-21 14:57:29 +00:00
|
|
|
"""
|
|
|
|
unique_urls: OrderedDict[str, Link] = OrderedDict()
|
|
|
|
|
|
|
|
for link in links:
|
|
|
|
index_link = snapshots.filter(url=link.url)
|
|
|
|
if index_link:
|
|
|
|
link = merge_links(index_link[0].as_link(), link)
|
|
|
|
|
|
|
|
unique_urls[link.url] = link
|
|
|
|
|
|
|
|
return unique_urls.values()
|
2020-07-13 15:26:30 +00:00
|
|
|
|
2020-08-21 14:57:29 +00:00
|
|
|
@enforce_types
|
|
|
|
def dedupe_links(snapshots: QuerySet,
|
|
|
|
new_links: List[Link]) -> List[Link]:
|
|
|
|
"""
|
|
|
|
The validation of links happened at a different stage. This method will
|
|
|
|
focus on actual deduplication and timestamp fixing.
|
|
|
|
"""
|
|
|
|
|
2019-03-21 05:28:12 +00:00
|
|
|
# merge existing links in out_dir and new links
|
2020-08-21 14:57:29 +00:00
|
|
|
dedup_links = fix_duplicate_links_in_index(snapshots, new_links)
|
2019-04-27 21:26:24 +00:00
|
|
|
|
|
|
|
new_links = [
|
|
|
|
link for link in new_links
|
2020-08-21 14:57:29 +00:00
|
|
|
if not snapshots.filter(url=link.url).exists()
|
2019-04-27 21:26:24 +00:00
|
|
|
]
|
2020-07-13 19:48:25 +00:00
|
|
|
|
2020-08-21 14:57:29 +00:00
|
|
|
dedup_links_dict = {link.url: link for link in dedup_links}
|
|
|
|
|
|
|
|
# Replace links in new_links with the dedup version
|
2020-07-13 19:48:25 +00:00
|
|
|
for i in range(len(new_links)):
|
2020-08-21 14:57:29 +00:00
|
|
|
if new_links[i].url in dedup_links_dict.keys():
|
|
|
|
new_links[i] = dedup_links_dict[new_links[i].url]
|
2020-07-13 15:26:30 +00:00
|
|
|
log_deduping_finished(len(new_links))
|
2019-03-21 05:28:12 +00:00
|
|
|
|
2020-08-21 14:57:29 +00:00
|
|
|
return new_links
|
2017-07-04 10:38:07 +00:00
|
|
|
|
2019-04-17 06:25:28 +00:00
|
|
|
### Link Details Index
|
2019-03-26 09:33:34 +00:00
|
|
|
|
2019-03-27 02:26:21 +00:00
|
|
|
@enforce_types
|
2020-07-29 16:19:06 +00:00
|
|
|
def write_link_details(link: Link, out_dir: Optional[str]=None, skip_sql_index: bool=False) -> None:
|
2019-04-17 06:25:28 +00:00
|
|
|
out_dir = out_dir or link.link_dir
|
2017-10-18 22:38:17 +00:00
|
|
|
|
2019-04-17 06:25:28 +00:00
|
|
|
write_json_link_details(link, out_dir=out_dir)
|
|
|
|
write_html_link_details(link, out_dir=out_dir)
|
2020-07-29 16:19:06 +00:00
|
|
|
if not skip_sql_index:
|
|
|
|
write_sql_link_details(link)
|
2017-10-23 09:58:41 +00:00
|
|
|
|
2019-03-26 09:33:34 +00:00
|
|
|
|
2019-03-27 02:26:21 +00:00
|
|
|
@enforce_types
|
2019-04-17 06:25:28 +00:00
|
|
|
def load_link_details(link: Link, out_dir: Optional[str]=None) -> Link:
|
2019-03-21 05:28:12 +00:00
|
|
|
"""check for an existing link archive in the given directory,
|
|
|
|
and load+merge it into the given link dict
|
|
|
|
"""
|
2019-04-17 06:25:28 +00:00
|
|
|
out_dir = out_dir or link.link_dir
|
|
|
|
|
|
|
|
existing_link = parse_json_link_details(out_dir)
|
2019-03-27 02:26:21 +00:00
|
|
|
if existing_link:
|
|
|
|
return merge_links(existing_link, link)
|
2019-04-17 06:25:28 +00:00
|
|
|
|
2019-03-27 02:26:21 +00:00
|
|
|
return link
|
2019-04-27 21:26:24 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
LINK_FILTERS = {
|
2020-08-21 17:42:08 +00:00
|
|
|
'exact': lambda pattern: Q(url=pattern),
|
|
|
|
'substring': lambda pattern: Q(url__icontains=pattern),
|
|
|
|
'regex': lambda pattern: Q(url__iregex=pattern),
|
2020-08-21 18:32:31 +00:00
|
|
|
'domain': lambda pattern: Q(url__istartswith=f"http://{pattern}") | Q(url__istartswith=f"https://{pattern}") | Q(url__istartswith=f"ftp://{pattern}"),
|
2020-11-13 17:06:12 +00:00
|
|
|
'tag': lambda pattern: Q(tags__name=pattern),
|
2021-02-16 01:48:35 +00:00
|
|
|
'timestamp': lambda pattern: Q(timestamp=pattern),
|
2019-04-27 21:26:24 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
@enforce_types
|
2020-11-20 04:39:28 +00:00
|
|
|
def q_filter(snapshots: QuerySet, filter_patterns: List[str], filter_type: str='exact') -> QuerySet:
|
2020-08-21 17:42:08 +00:00
|
|
|
q_filter = Q()
|
2019-04-27 21:26:24 +00:00
|
|
|
for pattern in filter_patterns:
|
|
|
|
try:
|
2020-08-21 17:42:08 +00:00
|
|
|
q_filter = q_filter | LINK_FILTERS[filter_type](pattern)
|
|
|
|
except KeyError:
|
2019-04-27 21:26:24 +00:00
|
|
|
stderr()
|
|
|
|
stderr(
|
|
|
|
f'[X] Got invalid pattern for --filter-type={filter_type}:',
|
|
|
|
color='red',
|
|
|
|
)
|
|
|
|
stderr(f' {pattern}')
|
|
|
|
raise SystemExit(2)
|
2020-08-21 17:42:08 +00:00
|
|
|
return snapshots.filter(q_filter)
|
2019-04-27 21:26:24 +00:00
|
|
|
|
2020-11-20 04:39:28 +00:00
|
|
|
def search_filter(snapshots: QuerySet, filter_patterns: List[str], filter_type: str='search') -> QuerySet:
|
2024-09-24 09:13:01 +00:00
|
|
|
from ..search import query_search_index
|
|
|
|
|
2024-09-24 10:05:43 +00:00
|
|
|
if not SEARCH_BACKEND_CONFIG.USE_SEARCHING_BACKEND:
|
2020-11-20 04:39:28 +00:00
|
|
|
stderr()
|
|
|
|
stderr(
|
2020-11-21 14:37:13 +00:00
|
|
|
'[X] The search backend is not enabled, set config.USE_SEARCHING_BACKEND = True',
|
2020-11-20 04:39:28 +00:00
|
|
|
color='red',
|
|
|
|
)
|
|
|
|
raise SystemExit(2)
|
2020-12-11 21:27:15 +00:00
|
|
|
from core.models import Snapshot
|
2020-11-20 04:39:28 +00:00
|
|
|
|
2020-12-11 21:27:15 +00:00
|
|
|
qsearch = Snapshot.objects.none()
|
2020-11-20 04:39:28 +00:00
|
|
|
for pattern in filter_patterns:
|
|
|
|
try:
|
|
|
|
qsearch |= query_search_index(pattern)
|
2020-11-21 14:37:13 +00:00
|
|
|
except:
|
2020-11-20 04:39:28 +00:00
|
|
|
raise SystemExit(2)
|
|
|
|
|
|
|
|
return snapshots & qsearch
|
|
|
|
|
|
|
|
@enforce_types
|
|
|
|
def snapshot_filter(snapshots: QuerySet, filter_patterns: List[str], filter_type: str='exact') -> QuerySet:
|
|
|
|
if filter_type != 'search':
|
|
|
|
return q_filter(snapshots, filter_patterns, filter_type)
|
|
|
|
else:
|
|
|
|
return search_filter(snapshots, filter_patterns, filter_type)
|
|
|
|
|
2019-04-27 21:26:24 +00:00
|
|
|
|
2024-09-30 22:59:05 +00:00
|
|
|
def get_indexed_folders(snapshots, out_dir: Path=DATA_DIR) -> Dict[str, Optional[Link]]:
|
2019-04-27 21:26:24 +00:00
|
|
|
"""indexed links without checking archive status or data directory validity"""
|
2024-08-28 02:28:00 +00:00
|
|
|
links = (snapshot.as_link() for snapshot in snapshots.iterator(chunk_size=500))
|
2019-04-27 21:26:24 +00:00
|
|
|
return {
|
|
|
|
link.link_dir: link
|
|
|
|
for link in links
|
|
|
|
}
|
|
|
|
|
2024-09-30 22:59:05 +00:00
|
|
|
def get_archived_folders(snapshots, out_dir: Path=DATA_DIR) -> Dict[str, Optional[Link]]:
|
2019-04-27 21:26:24 +00:00
|
|
|
"""indexed links that are archived with a valid data directory"""
|
2024-08-28 02:28:00 +00:00
|
|
|
links = (snapshot.as_link() for snapshot in snapshots.iterator(chunk_size=500))
|
2019-04-27 21:26:24 +00:00
|
|
|
return {
|
|
|
|
link.link_dir: link
|
|
|
|
for link in filter(is_archived, links)
|
|
|
|
}
|
|
|
|
|
2024-09-30 22:59:05 +00:00
|
|
|
def get_unarchived_folders(snapshots, out_dir: Path=DATA_DIR) -> Dict[str, Optional[Link]]:
|
2019-04-27 21:26:24 +00:00
|
|
|
"""indexed links that are unarchived with no data directory or an empty data directory"""
|
2024-08-28 02:28:00 +00:00
|
|
|
links = (snapshot.as_link() for snapshot in snapshots.iterator(chunk_size=500))
|
2019-04-27 21:26:24 +00:00
|
|
|
return {
|
|
|
|
link.link_dir: link
|
|
|
|
for link in filter(is_unarchived, links)
|
|
|
|
}
|
|
|
|
|
2024-09-30 22:59:05 +00:00
|
|
|
def get_present_folders(snapshots, out_dir: Path=DATA_DIR) -> Dict[str, Optional[Link]]:
|
2019-05-02 19:20:21 +00:00
|
|
|
"""dirs that actually exist in the archive/ folder"""
|
2020-08-22 13:59:25 +00:00
|
|
|
|
2019-04-27 21:26:24 +00:00
|
|
|
all_folders = {}
|
|
|
|
|
2024-09-30 22:59:05 +00:00
|
|
|
for entry in (out_dir / CONSTANTS.ARCHIVE_DIR_NAME).iterdir():
|
2020-08-22 13:59:25 +00:00
|
|
|
if entry.is_dir():
|
2019-04-27 21:26:24 +00:00
|
|
|
link = None
|
|
|
|
try:
|
|
|
|
link = parse_json_link_details(entry.path)
|
|
|
|
except Exception:
|
|
|
|
pass
|
|
|
|
|
2020-08-22 13:59:25 +00:00
|
|
|
all_folders[entry.name] = link
|
2019-04-27 21:26:24 +00:00
|
|
|
|
|
|
|
return all_folders
|
|
|
|
|
2024-09-30 22:59:05 +00:00
|
|
|
def get_valid_folders(snapshots, out_dir: Path=DATA_DIR) -> Dict[str, Optional[Link]]:
|
2019-04-27 21:26:24 +00:00
|
|
|
"""dirs with a valid index matched to the main index and archived content"""
|
2024-08-28 02:28:00 +00:00
|
|
|
links = [snapshot.as_link_with_details() for snapshot in snapshots.iterator(chunk_size=500)]
|
2019-04-27 21:26:24 +00:00
|
|
|
return {
|
|
|
|
link.link_dir: link
|
|
|
|
for link in filter(is_valid, links)
|
|
|
|
}
|
|
|
|
|
2024-09-30 22:59:05 +00:00
|
|
|
def get_invalid_folders(snapshots, out_dir: Path=DATA_DIR) -> Dict[str, Optional[Link]]:
|
2019-04-27 21:26:24 +00:00
|
|
|
"""dirs that are invalid for any reason: corrupted/duplicate/orphaned/unrecognized"""
|
2024-09-25 12:10:09 +00:00
|
|
|
duplicate = get_duplicate_folders(snapshots, out_dir=out_dir)
|
|
|
|
orphaned = get_orphaned_folders(snapshots, out_dir=out_dir)
|
|
|
|
corrupted = get_corrupted_folders(snapshots, out_dir=out_dir)
|
|
|
|
unrecognized = get_unrecognized_folders(snapshots, out_dir=out_dir)
|
2019-04-27 21:26:24 +00:00
|
|
|
return {**duplicate, **orphaned, **corrupted, **unrecognized}
|
|
|
|
|
|
|
|
|
2024-09-30 22:59:05 +00:00
|
|
|
def get_duplicate_folders(snapshots, out_dir: Path=DATA_DIR) -> Dict[str, Optional[Link]]:
|
2019-04-27 21:26:24 +00:00
|
|
|
"""dirs that conflict with other directories that have the same link URL or timestamp"""
|
2020-08-20 19:34:49 +00:00
|
|
|
by_url = {}
|
|
|
|
by_timestamp = {}
|
2019-04-27 21:26:24 +00:00
|
|
|
duplicate_folders = {}
|
|
|
|
|
|
|
|
data_folders = (
|
2020-08-20 21:47:02 +00:00
|
|
|
str(entry)
|
2024-09-30 22:59:05 +00:00
|
|
|
for entry in CONSTANTS.ARCHIVE_DIR.iterdir()
|
2020-08-20 21:47:02 +00:00
|
|
|
if entry.is_dir() and not snapshots.filter(timestamp=entry.name).exists()
|
2019-04-27 21:26:24 +00:00
|
|
|
)
|
|
|
|
|
2024-08-28 02:28:00 +00:00
|
|
|
for path in chain(snapshots.iterator(chunk_size=500), data_folders):
|
2019-04-27 21:26:24 +00:00
|
|
|
link = None
|
2020-08-20 21:47:02 +00:00
|
|
|
if type(path) is not str:
|
|
|
|
path = path.as_link().link_dir
|
|
|
|
|
2019-04-27 21:26:24 +00:00
|
|
|
try:
|
|
|
|
link = parse_json_link_details(path)
|
|
|
|
except Exception:
|
|
|
|
pass
|
|
|
|
|
|
|
|
if link:
|
|
|
|
# link folder has same timestamp as different link folder
|
|
|
|
by_timestamp[link.timestamp] = by_timestamp.get(link.timestamp, 0) + 1
|
|
|
|
if by_timestamp[link.timestamp] > 1:
|
|
|
|
duplicate_folders[path] = link
|
|
|
|
|
|
|
|
# link folder has same url as different link folder
|
|
|
|
by_url[link.url] = by_url.get(link.url, 0) + 1
|
|
|
|
if by_url[link.url] > 1:
|
|
|
|
duplicate_folders[path] = link
|
|
|
|
return duplicate_folders
|
|
|
|
|
2024-09-30 22:59:05 +00:00
|
|
|
def get_orphaned_folders(snapshots, out_dir: Path=DATA_DIR) -> Dict[str, Optional[Link]]:
|
2019-04-27 21:26:24 +00:00
|
|
|
"""dirs that contain a valid index but aren't listed in the main index"""
|
|
|
|
orphaned_folders = {}
|
|
|
|
|
2024-09-30 22:59:05 +00:00
|
|
|
for entry in CONSTANTS.ARCHIVE_DIR.iterdir():
|
2020-08-20 19:34:49 +00:00
|
|
|
if entry.is_dir():
|
2019-04-27 21:26:24 +00:00
|
|
|
link = None
|
|
|
|
try:
|
2020-08-20 19:34:49 +00:00
|
|
|
link = parse_json_link_details(str(entry))
|
2019-04-27 21:26:24 +00:00
|
|
|
except Exception:
|
|
|
|
pass
|
|
|
|
|
2020-08-20 19:34:49 +00:00
|
|
|
if link and not snapshots.filter(timestamp=entry.name).exists():
|
2019-04-27 21:26:24 +00:00
|
|
|
# folder is a valid link data dir with index details, but it's not in the main index
|
2020-08-20 19:34:49 +00:00
|
|
|
orphaned_folders[str(entry)] = link
|
2019-04-27 21:26:24 +00:00
|
|
|
|
|
|
|
return orphaned_folders
|
|
|
|
|
2024-09-30 22:59:05 +00:00
|
|
|
def get_corrupted_folders(snapshots, out_dir: Path=DATA_DIR) -> Dict[str, Optional[Link]]:
|
2019-04-27 21:26:24 +00:00
|
|
|
"""dirs that don't contain a valid index and aren't listed in the main index"""
|
2020-08-20 19:34:49 +00:00
|
|
|
corrupted = {}
|
2024-08-28 02:28:00 +00:00
|
|
|
for snapshot in snapshots.iterator(chunk_size=500):
|
2020-08-20 19:34:49 +00:00
|
|
|
link = snapshot.as_link()
|
|
|
|
if is_corrupt(link):
|
|
|
|
corrupted[link.link_dir] = link
|
|
|
|
return corrupted
|
|
|
|
|
2024-09-30 22:59:05 +00:00
|
|
|
def get_unrecognized_folders(snapshots, out_dir: Path=DATA_DIR) -> Dict[str, Optional[Link]]:
|
2019-04-27 21:26:24 +00:00
|
|
|
"""dirs that don't contain recognizable archive data and aren't listed in the main index"""
|
|
|
|
unrecognized_folders: Dict[str, Optional[Link]] = {}
|
|
|
|
|
2024-09-30 22:59:05 +00:00
|
|
|
for entry in (Path(out_dir) / CONSTANTS.ARCHIVE_DIR_NAME).iterdir():
|
2020-08-20 19:34:49 +00:00
|
|
|
if entry.is_dir():
|
|
|
|
index_exists = (entry / "index.json").exists()
|
2019-04-27 21:26:24 +00:00
|
|
|
link = None
|
|
|
|
try:
|
2020-08-20 19:34:49 +00:00
|
|
|
link = parse_json_link_details(str(entry))
|
2020-07-24 14:24:52 +00:00
|
|
|
except KeyError:
|
|
|
|
# Try to fix index
|
|
|
|
if index_exists:
|
|
|
|
try:
|
|
|
|
# Last attempt to repair the detail index
|
2020-08-20 19:34:49 +00:00
|
|
|
link_guessed = parse_json_link_details(str(entry), guess=True)
|
|
|
|
write_json_link_details(link_guessed, out_dir=str(entry))
|
|
|
|
link = parse_json_link_details(str(entry))
|
2020-07-24 17:25:25 +00:00
|
|
|
except Exception:
|
2020-07-24 14:24:52 +00:00
|
|
|
pass
|
2019-04-27 21:26:24 +00:00
|
|
|
|
|
|
|
if index_exists and link is None:
|
|
|
|
# index exists but it's corrupted or unparseable
|
2020-08-20 19:34:49 +00:00
|
|
|
unrecognized_folders[str(entry)] = link
|
2019-04-27 21:26:24 +00:00
|
|
|
|
|
|
|
elif not index_exists:
|
|
|
|
# link details index doesn't exist and the folder isn't in the main index
|
2020-08-20 19:34:49 +00:00
|
|
|
timestamp = entry.name
|
|
|
|
if not snapshots.filter(timestamp=timestamp).exists():
|
|
|
|
unrecognized_folders[str(entry)] = link
|
2019-04-27 21:26:24 +00:00
|
|
|
|
|
|
|
return unrecognized_folders
|
|
|
|
|
|
|
|
|
|
|
|
def is_valid(link: Link) -> bool:
|
2020-08-20 19:34:49 +00:00
|
|
|
dir_exists = Path(link.link_dir).exists()
|
|
|
|
index_exists = (Path(link.link_dir) / "index.json").exists()
|
2019-04-27 21:26:24 +00:00
|
|
|
if not dir_exists:
|
|
|
|
# unarchived links are not included in the valid list
|
|
|
|
return False
|
|
|
|
if dir_exists and not index_exists:
|
|
|
|
return False
|
|
|
|
if dir_exists and index_exists:
|
|
|
|
try:
|
2020-07-24 14:24:52 +00:00
|
|
|
parsed_link = parse_json_link_details(link.link_dir, guess=True)
|
2019-04-27 21:26:24 +00:00
|
|
|
return link.url == parsed_link.url
|
2020-07-24 17:25:25 +00:00
|
|
|
except Exception:
|
2019-04-27 21:26:24 +00:00
|
|
|
pass
|
|
|
|
return False
|
|
|
|
|
|
|
|
def is_corrupt(link: Link) -> bool:
|
2020-08-20 19:34:49 +00:00
|
|
|
if not Path(link.link_dir).exists():
|
2019-04-27 21:26:24 +00:00
|
|
|
# unarchived links are not considered corrupt
|
|
|
|
return False
|
|
|
|
|
|
|
|
if is_valid(link):
|
|
|
|
return False
|
|
|
|
|
|
|
|
return True
|
|
|
|
|
|
|
|
def is_archived(link: Link) -> bool:
|
|
|
|
return is_valid(link) and link.is_archived
|
|
|
|
|
|
|
|
def is_unarchived(link: Link) -> bool:
|
2020-09-30 19:32:26 +00:00
|
|
|
if not Path(link.link_dir).exists():
|
2019-04-27 21:26:24 +00:00
|
|
|
return True
|
|
|
|
return not link.is_archived
|
|
|
|
|
|
|
|
|
2024-09-30 22:59:05 +00:00
|
|
|
def fix_invalid_folder_locations(out_dir: Path=DATA_DIR) -> Tuple[List[str], List[str]]:
|
2019-04-27 21:26:24 +00:00
|
|
|
fixed = []
|
|
|
|
cant_fix = []
|
2024-09-30 22:59:05 +00:00
|
|
|
for entry in os.scandir(out_dir / CONSTANTS.ARCHIVE_DIR_NAME):
|
2019-04-27 21:26:24 +00:00
|
|
|
if entry.is_dir(follow_symlinks=True):
|
2020-09-07 22:49:14 +00:00
|
|
|
if (Path(entry.path) / 'index.json').exists():
|
2020-07-22 22:08:32 +00:00
|
|
|
try:
|
|
|
|
link = parse_json_link_details(entry.path)
|
|
|
|
except KeyError:
|
|
|
|
link = None
|
2019-04-27 21:26:24 +00:00
|
|
|
if not link:
|
|
|
|
continue
|
|
|
|
|
|
|
|
if not entry.path.endswith(f'/{link.timestamp}'):
|
2024-09-30 22:59:05 +00:00
|
|
|
dest = out_dir /CONSTANTS.ARCHIVE_DIR_NAME / link.timestamp
|
2020-09-07 22:49:14 +00:00
|
|
|
if dest.exists():
|
2019-04-27 21:26:24 +00:00
|
|
|
cant_fix.append(entry.path)
|
|
|
|
else:
|
|
|
|
shutil.move(entry.path, dest)
|
|
|
|
fixed.append(dest)
|
2019-05-01 03:13:04 +00:00
|
|
|
timestamp = entry.path.rsplit('/', 1)[-1]
|
|
|
|
assert link.link_dir == entry.path
|
|
|
|
assert link.timestamp == timestamp
|
|
|
|
write_json_link_details(link, out_dir=entry.path)
|
2019-04-27 21:26:24 +00:00
|
|
|
|
|
|
|
return fixed, cant_fix
|