schema.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. """
  2. WARNING: THIS FILE IS ALL LEGACY CODE TO BE REMOVED.
  3. DO NOT ADD ANY NEW FEATURES TO THIS FILE, NEW CODE GOES HERE: core/models.py
  4. """
  5. __package__ = 'archivebox.index'
  6. from pathlib import Path
  7. from datetime import datetime, timedelta
  8. from typing import List, Dict, Any, Optional, Union
  9. from dataclasses import dataclass, asdict, field, fields
  10. from ..system import get_dir_size
  11. from ..config import OUTPUT_DIR, ARCHIVE_DIR_NAME
  12. class ArchiveError(Exception):
  13. def __init__(self, message, hints=None):
  14. super().__init__(message)
  15. self.hints = hints
  16. LinkDict = Dict[str, Any]
  17. ArchiveOutput = Union[str, Exception, None]
  18. @dataclass(frozen=True)
  19. class ArchiveResult:
  20. cmd: List[str]
  21. pwd: Optional[str]
  22. cmd_version: Optional[str]
  23. output: ArchiveOutput
  24. status: str
  25. start_ts: datetime
  26. end_ts: datetime
  27. index_texts: Union[List[str], None] = None
  28. schema: str = 'ArchiveResult'
  29. def __post_init__(self):
  30. self.typecheck()
  31. def _asdict(self):
  32. return asdict(self)
  33. def typecheck(self) -> None:
  34. assert self.schema == self.__class__.__name__
  35. assert isinstance(self.status, str) and self.status
  36. assert isinstance(self.start_ts, datetime)
  37. assert isinstance(self.end_ts, datetime)
  38. assert isinstance(self.cmd, list)
  39. assert all(isinstance(arg, str) and arg for arg in self.cmd)
  40. assert self.pwd is None or isinstance(self.pwd, str) and self.pwd
  41. assert self.cmd_version is None or isinstance(self.cmd_version, str) and self.cmd_version
  42. assert self.output is None or isinstance(self.output, (str, Exception))
  43. if isinstance(self.output, str):
  44. assert self.output
  45. @classmethod
  46. def guess_ts(_cls, dict_info):
  47. from ..util import parse_date
  48. parsed_timestamp = parse_date(dict_info["timestamp"])
  49. start_ts = parsed_timestamp
  50. end_ts = parsed_timestamp + timedelta(seconds=int(dict_info["duration"]))
  51. return start_ts, end_ts
  52. @classmethod
  53. def from_json(cls, json_info, guess=False):
  54. from ..util import parse_date
  55. info = {
  56. key: val
  57. for key, val in json_info.items()
  58. if key in cls.field_names()
  59. }
  60. if guess:
  61. keys = info.keys()
  62. if "start_ts" not in keys:
  63. info["start_ts"], info["end_ts"] = cls.guess_ts(json_info)
  64. else:
  65. info['start_ts'] = parse_date(info['start_ts'])
  66. info['end_ts'] = parse_date(info['end_ts'])
  67. if "pwd" not in keys:
  68. info["pwd"] = str(Path(OUTPUT_DIR) / ARCHIVE_DIR_NAME / json_info["timestamp"])
  69. if "cmd_version" not in keys:
  70. info["cmd_version"] = "Undefined"
  71. if "cmd" not in keys:
  72. info["cmd"] = []
  73. else:
  74. info['start_ts'] = parse_date(info['start_ts'])
  75. info['end_ts'] = parse_date(info['end_ts'])
  76. info['cmd_version'] = info.get('cmd_version')
  77. if type(info["cmd"]) is str:
  78. info["cmd"] = [info["cmd"]]
  79. return cls(**info)
  80. def to_dict(self, *keys) -> dict:
  81. if keys:
  82. return {k: v for k, v in asdict(self).items() if k in keys}
  83. return asdict(self)
  84. def to_json(self, indent=4, sort_keys=True) -> str:
  85. from .json import to_json
  86. return to_json(self, indent=indent, sort_keys=sort_keys)
  87. def to_csv(self, cols: Optional[List[str]]=None, separator: str=',', ljust: int=0) -> str:
  88. from .csv import to_csv
  89. return to_csv(self, csv_col=cols or self.field_names(), separator=separator, ljust=ljust)
  90. @classmethod
  91. def field_names(cls):
  92. return [f.name for f in fields(cls)]
  93. @property
  94. def duration(self) -> int:
  95. return (self.end_ts - self.start_ts).seconds
  96. @dataclass(frozen=True)
  97. class Link:
  98. timestamp: str
  99. url: str
  100. title: Optional[str]
  101. tags: Optional[str]
  102. sources: List[str]
  103. history: Dict[str, List[ArchiveResult]] = field(default_factory=lambda: {})
  104. updated: Optional[datetime] = None
  105. schema: str = 'Link'
  106. def __str__(self) -> str:
  107. return f'[{self.timestamp}] {self.url} "{self.title}"'
  108. def __post_init__(self):
  109. self.typecheck()
  110. def overwrite(self, **kwargs):
  111. """pure functional version of dict.update that returns a new instance"""
  112. return Link(**{**self._asdict(), **kwargs})
  113. def __eq__(self, other):
  114. if not isinstance(other, Link):
  115. return NotImplemented
  116. return self.url == other.url
  117. def __gt__(self, other):
  118. if not isinstance(other, Link):
  119. return NotImplemented
  120. if not self.timestamp or not other.timestamp:
  121. return
  122. return float(self.timestamp) > float(other.timestamp)
  123. def typecheck(self) -> None:
  124. from ..config import stderr, ANSI
  125. try:
  126. assert self.schema == self.__class__.__name__
  127. assert isinstance(self.timestamp, str) and self.timestamp
  128. assert self.timestamp.replace('.', '').isdigit()
  129. assert isinstance(self.url, str) and '://' in self.url
  130. assert self.updated is None or isinstance(self.updated, datetime)
  131. assert self.title is None or (isinstance(self.title, str) and self.title)
  132. assert self.tags is None or isinstance(self.tags, str)
  133. assert isinstance(self.sources, list)
  134. assert all(isinstance(source, str) and source for source in self.sources)
  135. assert isinstance(self.history, dict)
  136. for method, results in self.history.items():
  137. assert isinstance(method, str) and method
  138. assert isinstance(results, list)
  139. assert all(isinstance(result, ArchiveResult) for result in results)
  140. except Exception:
  141. stderr('{red}[X] Error while loading link! [{}] {} "{}"{reset}'.format(self.timestamp, self.url, self.title, **ANSI))
  142. raise
  143. def _asdict(self, extended=False):
  144. info = {
  145. 'schema': 'Link',
  146. 'url': self.url,
  147. 'title': self.title or None,
  148. 'timestamp': self.timestamp,
  149. 'updated': self.updated or None,
  150. 'tags': self.tags or None,
  151. 'sources': self.sources or [],
  152. 'history': self.history or {},
  153. }
  154. if extended:
  155. info.update({
  156. 'link_dir': self.link_dir,
  157. 'archive_path': self.archive_path,
  158. 'hash': self.url_hash,
  159. 'base_url': self.base_url,
  160. 'scheme': self.scheme,
  161. 'domain': self.domain,
  162. 'path': self.path,
  163. 'basename': self.basename,
  164. 'extension': self.extension,
  165. 'is_static': self.is_static,
  166. 'bookmarked_date': self.bookmarked_date,
  167. 'updated_date': self.updated_date,
  168. 'oldest_archive_date': self.oldest_archive_date,
  169. 'newest_archive_date': self.newest_archive_date,
  170. 'is_archived': self.is_archived,
  171. 'num_outputs': self.num_outputs,
  172. 'num_failures': self.num_failures,
  173. 'latest': self.latest_outputs(),
  174. 'canonical': self.canonical_outputs(),
  175. })
  176. return info
  177. def as_snapshot(self):
  178. from core.models import Snapshot
  179. return Snapshot.objects.get(url=self.url)
  180. @classmethod
  181. def from_json(cls, json_info, guess=False):
  182. from ..util import parse_date
  183. info = {
  184. key: val
  185. for key, val in json_info.items()
  186. if key in cls.field_names()
  187. }
  188. info['updated'] = parse_date(info.get('updated'))
  189. info['sources'] = info.get('sources') or []
  190. json_history = info.get('history') or {}
  191. cast_history = {}
  192. for method, method_history in json_history.items():
  193. cast_history[method] = []
  194. for json_result in method_history:
  195. assert isinstance(json_result, dict), 'Items in Link["history"][method] must be dicts'
  196. cast_result = ArchiveResult.from_json(json_result, guess)
  197. cast_history[method].append(cast_result)
  198. info['history'] = cast_history
  199. return cls(**info)
  200. def to_json(self, indent=4, sort_keys=True) -> str:
  201. from .json import to_json
  202. return to_json(self, indent=indent, sort_keys=sort_keys)
  203. def to_csv(self, cols: Optional[List[str]]=None, separator: str=',', ljust: int=0) -> str:
  204. from .csv import to_csv
  205. return to_csv(self, cols=cols or self.field_names(), separator=separator, ljust=ljust)
  206. @classmethod
  207. def field_names(cls):
  208. return [f.name for f in fields(cls)]
  209. @property
  210. def link_dir(self) -> str:
  211. from ..config import CONFIG
  212. return str(Path(CONFIG['ARCHIVE_DIR']) / self.timestamp)
  213. @property
  214. def archive_path(self) -> str:
  215. from ..config import ARCHIVE_DIR_NAME
  216. return '{}/{}'.format(ARCHIVE_DIR_NAME, self.timestamp)
  217. @property
  218. def archive_size(self) -> float:
  219. try:
  220. return get_dir_size(self.archive_path)[0]
  221. except Exception:
  222. return 0
  223. ### URL Helpers
  224. @property
  225. def url_hash(self):
  226. from ..util import hashurl
  227. return hashurl(self.url)
  228. @property
  229. def scheme(self) -> str:
  230. from ..util import scheme
  231. return scheme(self.url)
  232. @property
  233. def extension(self) -> str:
  234. from ..util import extension
  235. return extension(self.url)
  236. @property
  237. def domain(self) -> str:
  238. from ..util import domain
  239. return domain(self.url)
  240. @property
  241. def path(self) -> str:
  242. from ..util import path
  243. return path(self.url)
  244. @property
  245. def basename(self) -> str:
  246. from ..util import basename
  247. return basename(self.url)
  248. @property
  249. def base_url(self) -> str:
  250. from ..util import base_url
  251. return base_url(self.url)
  252. ### Pretty Printing Helpers
  253. @property
  254. def bookmarked_date(self) -> Optional[str]:
  255. from ..util import ts_to_date
  256. max_ts = (datetime.now() + timedelta(days=30)).timestamp()
  257. if self.timestamp and self.timestamp.replace('.', '').isdigit():
  258. if 0 < float(self.timestamp) < max_ts:
  259. return ts_to_date(datetime.fromtimestamp(float(self.timestamp)))
  260. else:
  261. return str(self.timestamp)
  262. return None
  263. @property
  264. def updated_date(self) -> Optional[str]:
  265. from ..util import ts_to_date
  266. return ts_to_date(self.updated) if self.updated else None
  267. @property
  268. def archive_dates(self) -> List[datetime]:
  269. return [
  270. result.start_ts
  271. for method in self.history.keys()
  272. for result in self.history[method]
  273. ]
  274. @property
  275. def oldest_archive_date(self) -> Optional[datetime]:
  276. return min(self.archive_dates, default=None)
  277. @property
  278. def newest_archive_date(self) -> Optional[datetime]:
  279. return max(self.archive_dates, default=None)
  280. ### Archive Status Helpers
  281. @property
  282. def num_outputs(self) -> int:
  283. return self.as_snapshot().num_outputs
  284. @property
  285. def num_failures(self) -> int:
  286. return sum(1
  287. for method in self.history.keys()
  288. for result in self.history[method]
  289. if result.status == 'failed')
  290. @property
  291. def is_static(self) -> bool:
  292. from ..util import is_static_file
  293. return is_static_file(self.url)
  294. @property
  295. def is_archived(self) -> bool:
  296. from ..config import ARCHIVE_DIR
  297. from ..util import domain
  298. output_paths = (
  299. domain(self.url),
  300. 'output.pdf',
  301. 'screenshot.png',
  302. 'output.html',
  303. 'media',
  304. 'singlefile.html'
  305. )
  306. return any(
  307. (Path(ARCHIVE_DIR) / self.timestamp / path).exists()
  308. for path in output_paths
  309. )
  310. def latest_outputs(self, status: str=None) -> Dict[str, ArchiveOutput]:
  311. """get the latest output that each archive method produced for link"""
  312. ARCHIVE_METHODS = (
  313. 'title', 'favicon', 'wget', 'warc', 'singlefile', 'pdf',
  314. 'screenshot', 'dom', 'git', 'media', 'archive_org',
  315. )
  316. latest: Dict[str, ArchiveOutput] = {}
  317. for archive_method in ARCHIVE_METHODS:
  318. # get most recent succesful result in history for each archive method
  319. history = self.history.get(archive_method) or []
  320. history = list(filter(lambda result: result.output, reversed(history)))
  321. if status is not None:
  322. history = list(filter(lambda result: result.status == status, history))
  323. history = list(history)
  324. if history:
  325. latest[archive_method] = history[0].output
  326. else:
  327. latest[archive_method] = None
  328. return latest
  329. def canonical_outputs(self) -> Dict[str, Optional[str]]:
  330. """predict the expected output paths that should be present after archiving"""
  331. from ..extractors.wget import wget_output_path
  332. canonical = {
  333. 'index_path': 'index.html',
  334. 'favicon_path': 'favicon.ico',
  335. 'google_favicon_path': 'https://www.google.com/s2/favicons?domain={}'.format(self.domain),
  336. 'wget_path': wget_output_path(self),
  337. 'warc_path': 'warc/',
  338. 'singlefile_path': 'singlefile.html',
  339. 'readability_path': 'readability/content.html',
  340. 'mercury_path': 'mercury/content.html',
  341. 'pdf_path': 'output.pdf',
  342. 'screenshot_path': 'screenshot.png',
  343. 'dom_path': 'output.html',
  344. 'archive_org_path': 'https://web.archive.org/web/{}'.format(self.base_url),
  345. 'git_path': 'git/',
  346. 'media_path': 'media/',
  347. 'headers_path': 'headers.json',
  348. }
  349. if self.is_static:
  350. # static binary files like PDF and images are handled slightly differently.
  351. # they're just downloaded once and aren't archived separately multiple times,
  352. # so the wget, screenshot, & pdf urls should all point to the same file
  353. static_path = wget_output_path(self)
  354. canonical.update({
  355. 'title': self.basename,
  356. 'wget_path': static_path,
  357. 'pdf_path': static_path,
  358. 'screenshot_path': static_path,
  359. 'dom_path': static_path,
  360. 'singlefile_path': static_path,
  361. 'readability_path': static_path,
  362. 'mercury_path': static_path,
  363. })
  364. return canonical