__init__.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. __package__ = 'archivebox.extractors'
  2. from typing import Callable, Optional, Dict, List, Iterable, Union, Protocol, cast
  3. import os
  4. import sys
  5. from pathlib import Path
  6. from importlib import import_module
  7. from datetime import datetime, timezone
  8. from django.db.models import QuerySet
  9. from ..index.schema import ArchiveResult, Link
  10. from ..index.sql import write_link_to_sql_index
  11. from ..index import (
  12. load_link_details,
  13. write_link_details,
  14. )
  15. from archivebox.misc.util import enforce_types
  16. from archivebox.misc.logging_util import (
  17. log_archiving_started,
  18. log_archiving_paused,
  19. log_archiving_finished,
  20. log_link_archiving_started,
  21. log_link_archiving_finished,
  22. log_archive_method_started,
  23. log_archive_method_finished,
  24. )
  25. ShouldSaveFunction = Callable[[Link, Optional[Path], Optional[bool]], bool]
  26. SaveFunction = Callable[[Link, Optional[Path], int], ArchiveResult]
  27. ArchiveMethodEntry = tuple[str, ShouldSaveFunction, SaveFunction]
  28. def get_default_archive_methods() -> List[ArchiveMethodEntry]:
  29. # TODO: move to abx.pm.hook.get_EXTRACTORS()
  30. return [
  31. # ('favicon', should_save_favicon, save_favicon),
  32. # ('headers', should_save_headers, save_headers),
  33. # ('singlefile', should_save_singlefile, save_singlefile),
  34. # ('pdf', should_save_pdf, save_pdf),
  35. # ('screenshot', should_save_screenshot, save_screenshot),
  36. # ('dom', should_save_dom, save_dom),
  37. # ('wget', should_save_wget, save_wget),
  38. # # keep title, readability, and htmltotext below wget and singlefile, as they depend on them
  39. # ('title', should_save_title, save_title),
  40. # ('readability', should_save_readability, save_readability),
  41. # ('mercury', should_save_mercury, save_mercury),
  42. # ('htmltotext', should_save_htmltotext, save_htmltotext),
  43. # ('git', should_save_git, save_git),
  44. # ('media', should_save_media, save_media),
  45. # ('archive_org', should_save_archive_dot_org, save_archive_dot_org),
  46. ]
  47. ARCHIVE_METHODS_INDEXING_PRECEDENCE = [
  48. ('readability', 1),
  49. ('mercury', 2),
  50. ('htmltotext', 3),
  51. ('singlefile', 4),
  52. ('dom', 5),
  53. ('wget', 6)
  54. ]
  55. @enforce_types
  56. def get_archive_methods_for_link(link: Link) -> Iterable[ArchiveMethodEntry]:
  57. from archivebox.config.common import ARCHIVING_CONFIG
  58. DEFAULT_METHODS = get_default_archive_methods()
  59. allowed_methods = {
  60. method_name
  61. for url_pattern, methods in ARCHIVING_CONFIG.SAVE_ALLOWLIST_PTNS.items()
  62. for method_name in methods
  63. if url_pattern.search(link.url)
  64. } or { method[0] for method in DEFAULT_METHODS }
  65. denied_methods = {
  66. method_name
  67. for url_pattern, methods in ARCHIVING_CONFIG.SAVE_DENYLIST_PTNS.items()
  68. for method_name in methods
  69. if url_pattern.search(link.url)
  70. }
  71. allowed_methods -= denied_methods
  72. return [method for method in DEFAULT_METHODS if method[0] in allowed_methods]
  73. @enforce_types
  74. def ignore_methods(to_ignore: List[str]) -> Iterable[str]:
  75. ARCHIVE_METHODS = get_default_archive_methods()
  76. return [method[0] for method in ARCHIVE_METHODS if method[0] not in to_ignore]
  77. @enforce_types
  78. def archive_link(link: Link, overwrite: bool=False, methods: Optional[Iterable[str]]=None, out_dir: Optional[Path]=None, created_by_id: int | None=None) -> Link:
  79. """download the DOM, PDF, and a screenshot into a folder named after the link's timestamp"""
  80. from django.conf import settings
  81. from ..search import write_search_index
  82. # TODO: Remove when the input is changed to be a snapshot. Suboptimal approach.
  83. from core.models import Snapshot, ArchiveResult
  84. try:
  85. snapshot = Snapshot.objects.get(url=link.url) # TODO: This will be unnecessary once everything is a snapshot
  86. except Snapshot.DoesNotExist:
  87. snapshot = write_link_to_sql_index(link, created_by_id=created_by_id)
  88. active_methods = get_archive_methods_for_link(link)
  89. if methods:
  90. active_methods = [
  91. method for method in active_methods
  92. if method[0] in methods
  93. ]
  94. out_dir = out_dir or Path(link.link_dir)
  95. try:
  96. is_new = not Path(out_dir).exists()
  97. if is_new:
  98. os.makedirs(out_dir)
  99. link = load_link_details(link, out_dir=out_dir)
  100. write_link_details(link, out_dir=out_dir, skip_sql_index=False)
  101. log_link_archiving_started(link, str(out_dir), is_new)
  102. link = link.overwrite(downloaded_at=datetime.now(timezone.utc))
  103. stats = {'skipped': 0, 'succeeded': 0, 'failed': 0}
  104. start_ts = datetime.now(timezone.utc)
  105. for method_name, should_run, method_function in active_methods:
  106. try:
  107. if method_name not in link.history:
  108. link.history[method_name] = []
  109. if should_run(link, out_dir, overwrite):
  110. log_archive_method_started(method_name)
  111. result = method_function(link=link, out_dir=out_dir)
  112. link.history[method_name].append(result)
  113. stats[result.status] += 1
  114. log_archive_method_finished(result)
  115. write_search_index(link=link, texts=result.index_texts)
  116. ArchiveResult.objects.create(snapshot=snapshot, extractor=method_name, cmd=result.cmd, cmd_version=result.cmd_version,
  117. output=result.output, pwd=result.pwd, start_ts=result.start_ts, end_ts=result.end_ts, status=result.status, created_by_id=snapshot.created_by_id)
  118. # bump the downloaded_at time on the main Snapshot here, this is critical
  119. # to be able to cache summaries of the ArchiveResults for a given
  120. # snapshot without having to load all the results from the DB each time.
  121. # (we use {Snapshot.pk}-{Snapshot.downloaded_at} as the cache key and assume
  122. # ArchiveResults are unchanged as long as the downloaded_at timestamp is unchanged)
  123. snapshot.save()
  124. else:
  125. # print('{black} X {}{reset}'.format(method_name, **ANSI))
  126. stats['skipped'] += 1
  127. except Exception as e:
  128. # https://github.com/ArchiveBox/ArchiveBox/issues/984#issuecomment-1150541627
  129. with open(settings.ERROR_LOG, "a", encoding='utf-8') as f:
  130. command = ' '.join(sys.argv)
  131. ts = datetime.now(timezone.utc).strftime('%Y-%m-%d__%H:%M:%S')
  132. f.write(("\n" + 'Exception in archive_methods.save_{}(Link(url={})) command={}; ts={}'.format(
  133. method_name,
  134. link.url,
  135. command,
  136. ts
  137. ) + "\n" + str(e) + "\n"))
  138. #f.write(f"\n> {command}; ts={ts} version={config['VERSION']} docker={config['IN_DOCKER']} is_tty={config['IS_TTY']}\n")
  139. # print(f' ERROR: {method_name} {e.__class__.__name__}: {e} {getattr(e, "hints", "")}', ts, link.url, command)
  140. raise e from Exception('Exception in archive_methods.save_{}(Link(url={}))'.format(
  141. method_name,
  142. link.url,
  143. ))
  144. # print(' ', stats)
  145. try:
  146. latest_title = link.history['title'][-1].output.strip()
  147. if latest_title and len(latest_title) >= len(link.title or ''):
  148. link = link.overwrite(title=latest_title)
  149. except Exception:
  150. pass
  151. write_link_details(link, out_dir=out_dir, skip_sql_index=False)
  152. log_link_archiving_finished(link, out_dir, is_new, stats, start_ts)
  153. except KeyboardInterrupt:
  154. try:
  155. write_link_details(link, out_dir=link.link_dir)
  156. except:
  157. pass
  158. raise
  159. except Exception as err:
  160. print(' ! Failed to archive link: {}: {}'.format(err.__class__.__name__, err))
  161. raise
  162. return link
  163. @enforce_types
  164. def archive_links(all_links: Union[Iterable[Link], QuerySet], overwrite: bool=False, methods: Optional[Iterable[str]]=None, out_dir: Optional[Path]=None, created_by_id: int | None=None) -> List[Link]:
  165. if type(all_links) is QuerySet:
  166. num_links: int = all_links.count()
  167. get_link = lambda x: x.as_link_with_details()
  168. all_links = all_links.iterator(chunk_size=500)
  169. else:
  170. num_links: int = len(all_links)
  171. get_link = lambda x: x
  172. if num_links == 0:
  173. return []
  174. log_archiving_started(num_links)
  175. idx: int = 0
  176. try:
  177. for link in all_links:
  178. idx += 1
  179. to_archive = get_link(link)
  180. archive_link(to_archive, overwrite=overwrite, methods=methods, out_dir=Path(link.link_dir), created_by_id=created_by_id)
  181. except KeyboardInterrupt:
  182. log_archiving_paused(num_links, idx, link.timestamp)
  183. raise SystemExit(0)
  184. except BaseException:
  185. print()
  186. raise
  187. log_archiving_finished(num_links)
  188. return all_links
  189. EXTRACTORS_DIR = Path(__file__).parent
  190. class ExtractorModuleProtocol(Protocol):
  191. """Type interface for an Extractor Module (WIP)"""
  192. get_output_path: Callable
  193. # TODO:
  194. # get_embed_path: Callable | None
  195. # should_extract(Snapshot)
  196. # extract(Snapshot)
  197. def get_extractors(dir: Path=EXTRACTORS_DIR) -> Dict[str, ExtractorModuleProtocol]:
  198. """iterate through archivebox/extractors/*.py and load extractor modules"""
  199. EXTRACTORS = {}
  200. # for filename in EXTRACTORS_DIR.glob('*.py'):
  201. # if filename.name.startswith('__'):
  202. # continue
  203. # extractor_name = filename.name.replace('.py', '')
  204. # extractor_module = cast(ExtractorModuleProtocol, import_module(f'.{extractor_name}', package=__package__))
  205. # # assert getattr(extractor_module, 'get_output_path')
  206. # EXTRACTORS[extractor_name] = extractor_module
  207. return EXTRACTORS
  208. EXTRACTORS = get_extractors(EXTRACTORS_DIR)