__init__.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  1. __package__ = 'archivebox.index'
  2. import os
  3. import shutil
  4. from pathlib import Path
  5. from itertools import chain
  6. from typing import List, Tuple, Dict, Optional, Iterable
  7. from collections import OrderedDict
  8. from contextlib import contextmanager
  9. from urllib.parse import urlparse
  10. from django.db.models import QuerySet, Q
  11. from ..util import (
  12. scheme,
  13. enforce_types,
  14. ExtendedEncoder,
  15. )
  16. from ..config import (
  17. ARCHIVE_DIR_NAME,
  18. SQL_INDEX_FILENAME,
  19. JSON_INDEX_FILENAME,
  20. OUTPUT_DIR,
  21. TIMEOUT,
  22. URL_DENYLIST_PTN,
  23. URL_ALLOWLIST_PTN,
  24. stderr,
  25. OUTPUT_PERMISSIONS
  26. )
  27. from ..logging_util import (
  28. TimedProgress,
  29. log_indexing_process_started,
  30. log_indexing_process_finished,
  31. log_indexing_started,
  32. log_indexing_finished,
  33. log_parsing_finished,
  34. log_deduping_finished,
  35. )
  36. from .schema import Link, ArchiveResult
  37. from .html import (
  38. write_html_link_details,
  39. )
  40. from .json import (
  41. pyjson,
  42. parse_json_link_details,
  43. write_json_link_details,
  44. )
  45. from .sql import (
  46. write_sql_main_index,
  47. write_sql_link_details,
  48. )
  49. from ..search import search_backend_enabled, query_search_index
  50. ### Link filtering and checking
  51. @enforce_types
  52. def merge_links(a: Link, b: Link) -> Link:
  53. """deterministially merge two links, favoring longer field values over shorter,
  54. and "cleaner" values over worse ones.
  55. """
  56. assert a.base_url == b.base_url, f'Cannot merge two links with different URLs ({a.base_url} != {b.base_url})'
  57. # longest url wins (because a fuzzy url will always be shorter)
  58. url = a.url if len(a.url) > len(b.url) else b.url
  59. # best title based on length and quality
  60. possible_titles = [
  61. title
  62. for title in (a.title, b.title)
  63. if title and title.strip() and '://' not in title
  64. ]
  65. title = None
  66. if len(possible_titles) == 2:
  67. title = max(possible_titles, key=lambda t: len(t))
  68. elif len(possible_titles) == 1:
  69. title = possible_titles[0]
  70. # earliest valid timestamp
  71. timestamp = (
  72. a.timestamp
  73. if float(a.timestamp or 0) < float(b.timestamp or 0) else
  74. b.timestamp
  75. )
  76. # all unique, truthy tags
  77. tags_set = (
  78. set(tag.strip() for tag in (a.tags or '').split(','))
  79. | set(tag.strip() for tag in (b.tags or '').split(','))
  80. )
  81. tags = ','.join(tags_set) or None
  82. # all unique source entries
  83. sources = list(set(a.sources + b.sources))
  84. # all unique history entries for the combined archive methods
  85. all_methods = set(list(a.history.keys()) + list(a.history.keys()))
  86. history = {
  87. method: (a.history.get(method) or []) + (b.history.get(method) or [])
  88. for method in all_methods
  89. }
  90. for method in all_methods:
  91. deduped_jsons = {
  92. pyjson.dumps(result, sort_keys=True, cls=ExtendedEncoder)
  93. for result in history[method]
  94. }
  95. history[method] = list(reversed(sorted(
  96. (ArchiveResult.from_json(pyjson.loads(result)) for result in deduped_jsons),
  97. key=lambda result: result.start_ts,
  98. )))
  99. return Link(
  100. url=url,
  101. timestamp=timestamp,
  102. title=title,
  103. tags=tags,
  104. sources=sources,
  105. history=history,
  106. )
  107. @enforce_types
  108. def validate_links(links: Iterable[Link]) -> List[Link]:
  109. timer = TimedProgress(TIMEOUT * 4)
  110. try:
  111. links = archivable_links(links) # remove chrome://, about:, mailto: etc.
  112. links = sorted_links(links) # deterministically sort the links based on timestamp, url
  113. links = fix_duplicate_links(links) # merge/dedupe duplicate timestamps & urls
  114. finally:
  115. timer.end()
  116. return list(links)
  117. @enforce_types
  118. def archivable_links(links: Iterable[Link]) -> Iterable[Link]:
  119. """remove chrome://, about:// or other schemed links that cant be archived"""
  120. for link in links:
  121. try:
  122. urlparse(link.url)
  123. except ValueError:
  124. continue
  125. if scheme(link.url) not in ('http', 'https', 'ftp'):
  126. continue
  127. if URL_DENYLIST_PTN and URL_DENYLIST_PTN.search(link.url):
  128. continue
  129. if URL_ALLOWLIST_PTN and (not URL_ALLOWLIST_PTN.search(link.url)):
  130. continue
  131. yield link
  132. @enforce_types
  133. def fix_duplicate_links(sorted_links: Iterable[Link]) -> Iterable[Link]:
  134. """
  135. ensures that all non-duplicate links have monotonically increasing timestamps
  136. """
  137. # from core.models import Snapshot
  138. unique_urls: OrderedDict[str, Link] = OrderedDict()
  139. for link in sorted_links:
  140. if link.url in unique_urls:
  141. # merge with any other links that share the same url
  142. link = merge_links(unique_urls[link.url], link)
  143. unique_urls[link.url] = link
  144. return unique_urls.values()
  145. @enforce_types
  146. def sorted_links(links: Iterable[Link]) -> Iterable[Link]:
  147. sort_func = lambda link: (link.timestamp.split('.', 1)[0], link.url)
  148. return sorted(links, key=sort_func, reverse=True)
  149. @enforce_types
  150. def links_after_timestamp(links: Iterable[Link], resume: Optional[float]=None) -> Iterable[Link]:
  151. if not resume:
  152. yield from links
  153. return
  154. for link in links:
  155. try:
  156. if float(link.timestamp) <= resume:
  157. yield link
  158. except (ValueError, TypeError):
  159. print('Resume value and all timestamp values must be valid numbers.')
  160. @enforce_types
  161. def lowest_uniq_timestamp(used_timestamps: OrderedDict, timestamp: str) -> str:
  162. """resolve duplicate timestamps by appending a decimal 1234, 1234 -> 1234.1, 1234.2"""
  163. timestamp = timestamp.split('.')[0]
  164. nonce = 0
  165. # first try 152323423 before 152323423.0
  166. if timestamp not in used_timestamps:
  167. return timestamp
  168. new_timestamp = '{}.{}'.format(timestamp, nonce)
  169. while new_timestamp in used_timestamps:
  170. nonce += 1
  171. new_timestamp = '{}.{}'.format(timestamp, nonce)
  172. return new_timestamp
  173. ### Main Links Index
  174. @contextmanager
  175. @enforce_types
  176. def timed_index_update(out_path: Path):
  177. log_indexing_started(out_path)
  178. timer = TimedProgress(TIMEOUT * 2, prefix=' ')
  179. try:
  180. yield
  181. finally:
  182. timer.end()
  183. assert out_path.exists(), f'Failed to write index file: {out_path}'
  184. log_indexing_finished(out_path)
  185. @enforce_types
  186. def write_main_index(links: List[Link], out_dir: Path=OUTPUT_DIR) -> None:
  187. """Writes links to sqlite3 file for a given list of links"""
  188. log_indexing_process_started(len(links))
  189. try:
  190. with timed_index_update(out_dir / SQL_INDEX_FILENAME):
  191. write_sql_main_index(links, out_dir=out_dir)
  192. os.chmod(out_dir / SQL_INDEX_FILENAME, int(OUTPUT_PERMISSIONS, base=8)) # set here because we don't write it with atomic writes
  193. except (KeyboardInterrupt, SystemExit):
  194. stderr('[!] Warning: Still writing index to disk...', color='lightyellow')
  195. stderr(' Run archivebox init to fix any inconsistencies from an ungraceful exit.')
  196. with timed_index_update(out_dir / SQL_INDEX_FILENAME):
  197. write_sql_main_index(links, out_dir=out_dir)
  198. os.chmod(out_dir / SQL_INDEX_FILENAME, int(OUTPUT_PERMISSIONS, base=8)) # set here because we don't write it with atomic writes
  199. raise SystemExit(0)
  200. log_indexing_process_finished()
  201. @enforce_types
  202. def load_main_index(out_dir: Path=OUTPUT_DIR, warn: bool=True) -> List[Link]:
  203. """parse and load existing index with any new links from import_path merged in"""
  204. from core.models import Snapshot
  205. try:
  206. return Snapshot.objects.all().only('id')
  207. except (KeyboardInterrupt, SystemExit):
  208. raise SystemExit(0)
  209. @enforce_types
  210. def load_main_index_meta(out_dir: Path=OUTPUT_DIR) -> Optional[dict]:
  211. index_path = out_dir / JSON_INDEX_FILENAME
  212. if index_path.exists():
  213. with open(index_path, 'r', encoding='utf-8') as f:
  214. meta_dict = pyjson.load(f)
  215. meta_dict.pop('links')
  216. return meta_dict
  217. return None
  218. @enforce_types
  219. def parse_links_from_source(source_path: str, root_url: Optional[str]=None, parser: str="auto") -> Tuple[List[Link], List[Link]]:
  220. from ..parsers import parse_links
  221. new_links: List[Link] = []
  222. # parse and validate the import file
  223. raw_links, parser_name = parse_links(source_path, root_url=root_url, parser=parser)
  224. new_links = validate_links(raw_links)
  225. if parser_name:
  226. num_parsed = len(raw_links)
  227. log_parsing_finished(num_parsed, parser_name)
  228. return new_links
  229. @enforce_types
  230. def fix_duplicate_links_in_index(snapshots: QuerySet, links: Iterable[Link]) -> Iterable[Link]:
  231. """
  232. Given a list of in-memory Links, dedupe and merge them with any conflicting Snapshots in the DB.
  233. """
  234. unique_urls: OrderedDict[str, Link] = OrderedDict()
  235. for link in links:
  236. index_link = snapshots.filter(url=link.url)
  237. if index_link:
  238. link = merge_links(index_link[0].as_link(), link)
  239. unique_urls[link.url] = link
  240. return unique_urls.values()
  241. @enforce_types
  242. def dedupe_links(snapshots: QuerySet,
  243. new_links: List[Link]) -> List[Link]:
  244. """
  245. The validation of links happened at a different stage. This method will
  246. focus on actual deduplication and timestamp fixing.
  247. """
  248. # merge existing links in out_dir and new links
  249. dedup_links = fix_duplicate_links_in_index(snapshots, new_links)
  250. new_links = [
  251. link for link in new_links
  252. if not snapshots.filter(url=link.url).exists()
  253. ]
  254. dedup_links_dict = {link.url: link for link in dedup_links}
  255. # Replace links in new_links with the dedup version
  256. for i in range(len(new_links)):
  257. if new_links[i].url in dedup_links_dict.keys():
  258. new_links[i] = dedup_links_dict[new_links[i].url]
  259. log_deduping_finished(len(new_links))
  260. return new_links
  261. ### Link Details Index
  262. @enforce_types
  263. def write_link_details(link: Link, out_dir: Optional[str]=None, skip_sql_index: bool=False) -> None:
  264. out_dir = out_dir or link.link_dir
  265. write_json_link_details(link, out_dir=out_dir)
  266. write_html_link_details(link, out_dir=out_dir)
  267. if not skip_sql_index:
  268. write_sql_link_details(link)
  269. @enforce_types
  270. def load_link_details(link: Link, out_dir: Optional[str]=None) -> Link:
  271. """check for an existing link archive in the given directory,
  272. and load+merge it into the given link dict
  273. """
  274. out_dir = out_dir or link.link_dir
  275. existing_link = parse_json_link_details(out_dir)
  276. if existing_link:
  277. return merge_links(existing_link, link)
  278. return link
  279. LINK_FILTERS = {
  280. 'exact': lambda pattern: Q(url=pattern),
  281. 'substring': lambda pattern: Q(url__icontains=pattern),
  282. 'regex': lambda pattern: Q(url__iregex=pattern),
  283. 'domain': lambda pattern: Q(url__istartswith=f"http://{pattern}") | Q(url__istartswith=f"https://{pattern}") | Q(url__istartswith=f"ftp://{pattern}"),
  284. 'tag': lambda pattern: Q(tags__name=pattern),
  285. 'timestamp': lambda pattern: Q(timestamp=pattern),
  286. }
  287. @enforce_types
  288. def q_filter(snapshots: QuerySet, filter_patterns: List[str], filter_type: str='exact') -> QuerySet:
  289. q_filter = Q()
  290. for pattern in filter_patterns:
  291. try:
  292. q_filter = q_filter | LINK_FILTERS[filter_type](pattern)
  293. except KeyError:
  294. stderr()
  295. stderr(
  296. f'[X] Got invalid pattern for --filter-type={filter_type}:',
  297. color='red',
  298. )
  299. stderr(f' {pattern}')
  300. raise SystemExit(2)
  301. return snapshots.filter(q_filter)
  302. def search_filter(snapshots: QuerySet, filter_patterns: List[str], filter_type: str='search') -> QuerySet:
  303. if not search_backend_enabled():
  304. stderr()
  305. stderr(
  306. '[X] The search backend is not enabled, set config.USE_SEARCHING_BACKEND = True',
  307. color='red',
  308. )
  309. raise SystemExit(2)
  310. from core.models import Snapshot
  311. qsearch = Snapshot.objects.none()
  312. for pattern in filter_patterns:
  313. try:
  314. qsearch |= query_search_index(pattern)
  315. except:
  316. raise SystemExit(2)
  317. return snapshots & qsearch
  318. @enforce_types
  319. def snapshot_filter(snapshots: QuerySet, filter_patterns: List[str], filter_type: str='exact') -> QuerySet:
  320. if filter_type != 'search':
  321. return q_filter(snapshots, filter_patterns, filter_type)
  322. else:
  323. return search_filter(snapshots, filter_patterns, filter_type)
  324. def get_indexed_folders(snapshots, out_dir: Path=OUTPUT_DIR) -> Dict[str, Optional[Link]]:
  325. """indexed links without checking archive status or data directory validity"""
  326. links = (snapshot.as_link() for snapshot in snapshots.iterator())
  327. return {
  328. link.link_dir: link
  329. for link in links
  330. }
  331. def get_archived_folders(snapshots, out_dir: Path=OUTPUT_DIR) -> Dict[str, Optional[Link]]:
  332. """indexed links that are archived with a valid data directory"""
  333. links = (snapshot.as_link() for snapshot in snapshots.iterator())
  334. return {
  335. link.link_dir: link
  336. for link in filter(is_archived, links)
  337. }
  338. def get_unarchived_folders(snapshots, out_dir: Path=OUTPUT_DIR) -> Dict[str, Optional[Link]]:
  339. """indexed links that are unarchived with no data directory or an empty data directory"""
  340. links = (snapshot.as_link() for snapshot in snapshots.iterator())
  341. return {
  342. link.link_dir: link
  343. for link in filter(is_unarchived, links)
  344. }
  345. def get_present_folders(snapshots, out_dir: Path=OUTPUT_DIR) -> Dict[str, Optional[Link]]:
  346. """dirs that actually exist in the archive/ folder"""
  347. all_folders = {}
  348. for entry in (out_dir / ARCHIVE_DIR_NAME).iterdir():
  349. if entry.is_dir():
  350. link = None
  351. try:
  352. link = parse_json_link_details(entry.path)
  353. except Exception:
  354. pass
  355. all_folders[entry.name] = link
  356. return all_folders
  357. def get_valid_folders(snapshots, out_dir: Path=OUTPUT_DIR) -> Dict[str, Optional[Link]]:
  358. """dirs with a valid index matched to the main index and archived content"""
  359. links = [snapshot.as_link_with_details() for snapshot in snapshots.iterator()]
  360. return {
  361. link.link_dir: link
  362. for link in filter(is_valid, links)
  363. }
  364. def get_invalid_folders(snapshots, out_dir: Path=OUTPUT_DIR) -> Dict[str, Optional[Link]]:
  365. """dirs that are invalid for any reason: corrupted/duplicate/orphaned/unrecognized"""
  366. duplicate = get_duplicate_folders(snapshots, out_dir=OUTPUT_DIR)
  367. orphaned = get_orphaned_folders(snapshots, out_dir=OUTPUT_DIR)
  368. corrupted = get_corrupted_folders(snapshots, out_dir=OUTPUT_DIR)
  369. unrecognized = get_unrecognized_folders(snapshots, out_dir=OUTPUT_DIR)
  370. return {**duplicate, **orphaned, **corrupted, **unrecognized}
  371. def get_duplicate_folders(snapshots, out_dir: Path=OUTPUT_DIR) -> Dict[str, Optional[Link]]:
  372. """dirs that conflict with other directories that have the same link URL or timestamp"""
  373. by_url = {}
  374. by_timestamp = {}
  375. duplicate_folders = {}
  376. data_folders = (
  377. str(entry)
  378. for entry in (Path(out_dir) / ARCHIVE_DIR_NAME).iterdir()
  379. if entry.is_dir() and not snapshots.filter(timestamp=entry.name).exists()
  380. )
  381. for path in chain(snapshots.iterator(), data_folders):
  382. link = None
  383. if type(path) is not str:
  384. path = path.as_link().link_dir
  385. try:
  386. link = parse_json_link_details(path)
  387. except Exception:
  388. pass
  389. if link:
  390. # link folder has same timestamp as different link folder
  391. by_timestamp[link.timestamp] = by_timestamp.get(link.timestamp, 0) + 1
  392. if by_timestamp[link.timestamp] > 1:
  393. duplicate_folders[path] = link
  394. # link folder has same url as different link folder
  395. by_url[link.url] = by_url.get(link.url, 0) + 1
  396. if by_url[link.url] > 1:
  397. duplicate_folders[path] = link
  398. return duplicate_folders
  399. def get_orphaned_folders(snapshots, out_dir: Path=OUTPUT_DIR) -> Dict[str, Optional[Link]]:
  400. """dirs that contain a valid index but aren't listed in the main index"""
  401. orphaned_folders = {}
  402. for entry in (Path(out_dir) / ARCHIVE_DIR_NAME).iterdir():
  403. if entry.is_dir():
  404. link = None
  405. try:
  406. link = parse_json_link_details(str(entry))
  407. except Exception:
  408. pass
  409. if link and not snapshots.filter(timestamp=entry.name).exists():
  410. # folder is a valid link data dir with index details, but it's not in the main index
  411. orphaned_folders[str(entry)] = link
  412. return orphaned_folders
  413. def get_corrupted_folders(snapshots, out_dir: Path=OUTPUT_DIR) -> Dict[str, Optional[Link]]:
  414. """dirs that don't contain a valid index and aren't listed in the main index"""
  415. corrupted = {}
  416. for snapshot in snapshots.iterator():
  417. link = snapshot.as_link()
  418. if is_corrupt(link):
  419. corrupted[link.link_dir] = link
  420. return corrupted
  421. def get_unrecognized_folders(snapshots, out_dir: Path=OUTPUT_DIR) -> Dict[str, Optional[Link]]:
  422. """dirs that don't contain recognizable archive data and aren't listed in the main index"""
  423. unrecognized_folders: Dict[str, Optional[Link]] = {}
  424. for entry in (Path(out_dir) / ARCHIVE_DIR_NAME).iterdir():
  425. if entry.is_dir():
  426. index_exists = (entry / "index.json").exists()
  427. link = None
  428. try:
  429. link = parse_json_link_details(str(entry))
  430. except KeyError:
  431. # Try to fix index
  432. if index_exists:
  433. try:
  434. # Last attempt to repair the detail index
  435. link_guessed = parse_json_link_details(str(entry), guess=True)
  436. write_json_link_details(link_guessed, out_dir=str(entry))
  437. link = parse_json_link_details(str(entry))
  438. except Exception:
  439. pass
  440. if index_exists and link is None:
  441. # index exists but it's corrupted or unparseable
  442. unrecognized_folders[str(entry)] = link
  443. elif not index_exists:
  444. # link details index doesn't exist and the folder isn't in the main index
  445. timestamp = entry.name
  446. if not snapshots.filter(timestamp=timestamp).exists():
  447. unrecognized_folders[str(entry)] = link
  448. return unrecognized_folders
  449. def is_valid(link: Link) -> bool:
  450. dir_exists = Path(link.link_dir).exists()
  451. index_exists = (Path(link.link_dir) / "index.json").exists()
  452. if not dir_exists:
  453. # unarchived links are not included in the valid list
  454. return False
  455. if dir_exists and not index_exists:
  456. return False
  457. if dir_exists and index_exists:
  458. try:
  459. parsed_link = parse_json_link_details(link.link_dir, guess=True)
  460. return link.url == parsed_link.url
  461. except Exception:
  462. pass
  463. return False
  464. def is_corrupt(link: Link) -> bool:
  465. if not Path(link.link_dir).exists():
  466. # unarchived links are not considered corrupt
  467. return False
  468. if is_valid(link):
  469. return False
  470. return True
  471. def is_archived(link: Link) -> bool:
  472. return is_valid(link) and link.is_archived
  473. def is_unarchived(link: Link) -> bool:
  474. if not Path(link.link_dir).exists():
  475. return True
  476. return not link.is_archived
  477. def fix_invalid_folder_locations(out_dir: Path=OUTPUT_DIR) -> Tuple[List[str], List[str]]:
  478. fixed = []
  479. cant_fix = []
  480. for entry in os.scandir(out_dir / ARCHIVE_DIR_NAME):
  481. if entry.is_dir(follow_symlinks=True):
  482. if (Path(entry.path) / 'index.json').exists():
  483. try:
  484. link = parse_json_link_details(entry.path)
  485. except KeyError:
  486. link = None
  487. if not link:
  488. continue
  489. if not entry.path.endswith(f'/{link.timestamp}'):
  490. dest = out_dir / ARCHIVE_DIR_NAME / link.timestamp
  491. if dest.exists():
  492. cant_fix.append(entry.path)
  493. else:
  494. shutil.move(entry.path, dest)
  495. fixed.append(dest)
  496. timestamp = entry.path.rsplit('/', 1)[-1]
  497. assert link.link_dir == entry.path
  498. assert link.timestamp == timestamp
  499. write_json_link_details(link, out_dir=entry.path)
  500. return fixed, cant_fix