__init__.py 20 KB

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