schema.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. import os
  2. from datetime import datetime
  3. from typing import List, Dict, Any, Optional, Union
  4. from dataclasses import dataclass, asdict, field, fields
  5. class ArchiveError(Exception):
  6. def __init__(self, message, hints=None):
  7. super().__init__(message)
  8. self.hints = hints
  9. LinkDict = Dict[str, Any]
  10. ArchiveOutput = Union[str, Exception, None]
  11. @dataclass(frozen=True)
  12. class ArchiveResult:
  13. cmd: List[str]
  14. pwd: Optional[str]
  15. cmd_version: Optional[str]
  16. output: ArchiveOutput
  17. status: str
  18. start_ts: datetime
  19. end_ts: datetime
  20. schema: str = 'ArchiveResult'
  21. def __post_init__(self):
  22. self.typecheck()
  23. def _asdict(self):
  24. return asdict(self)
  25. def typecheck(self) -> None:
  26. assert self.schema == self.__class__.__name__
  27. assert isinstance(self.status, str) and self.status
  28. assert isinstance(self.start_ts, datetime)
  29. assert isinstance(self.end_ts, datetime)
  30. assert isinstance(self.cmd, list)
  31. assert all(isinstance(arg, str) and arg for arg in self.cmd)
  32. assert self.pwd is None or isinstance(self.pwd, str) and self.pwd
  33. assert self.cmd_version is None or isinstance(self.cmd_version, str) and self.cmd_version
  34. assert self.output is None or isinstance(self.output, (str, Exception))
  35. if isinstance(self.output, str):
  36. assert self.output
  37. @classmethod
  38. def from_json(cls, json_info):
  39. from .util import parse_date
  40. allowed_fields = {f.name for f in fields(cls)}
  41. info = {
  42. key: val
  43. for key, val in json_info.items()
  44. if key in allowed_fields
  45. }
  46. info['start_ts'] = parse_date(info['start_ts'])
  47. info['end_ts'] = parse_date(info['end_ts'])
  48. return cls(**info)
  49. @property
  50. def duration(self) -> int:
  51. return (self.end_ts - self.start_ts).seconds
  52. @dataclass(frozen=True)
  53. class Link:
  54. timestamp: str
  55. url: str
  56. title: Optional[str]
  57. tags: Optional[str]
  58. sources: List[str]
  59. history: Dict[str, List[ArchiveResult]] = field(default_factory=lambda: {})
  60. updated: Optional[datetime] = None
  61. schema: str = 'Link'
  62. def __post_init__(self):
  63. self.typecheck()
  64. def overwrite(self, **kwargs):
  65. """pure functional version of dict.update that returns a new instance"""
  66. return Link(**{**self._asdict(), **kwargs})
  67. def __eq__(self, other):
  68. if not isinstance(other, Link):
  69. return NotImplemented
  70. return self.url == other.url
  71. def __gt__(self, other):
  72. if not isinstance(other, Link):
  73. return NotImplemented
  74. if not self.timestamp or not other.timestamp:
  75. return
  76. return float(self.timestamp) > float(other.timestamp)
  77. def typecheck(self) -> None:
  78. assert self.schema == self.__class__.__name__
  79. assert isinstance(self.timestamp, str) and self.timestamp
  80. assert self.timestamp.replace('.', '').isdigit()
  81. assert isinstance(self.url, str) and '://' in self.url
  82. assert self.updated is None or isinstance(self.updated, datetime)
  83. assert self.title is None or isinstance(self.title, str) and self.title
  84. assert self.tags is None or isinstance(self.tags, str) and self.tags
  85. assert isinstance(self.sources, list)
  86. assert all(isinstance(source, str) and source for source in self.sources)
  87. assert isinstance(self.history, dict)
  88. for method, results in self.history.items():
  89. assert isinstance(method, str) and method
  90. assert isinstance(results, list)
  91. assert all(isinstance(result, ArchiveResult) for result in results)
  92. def _asdict(self, extended=False):
  93. info = {
  94. 'schema': 'Link',
  95. 'url': self.url,
  96. 'title': self.title or None,
  97. 'timestamp': self.timestamp,
  98. 'updated': self.updated or None,
  99. 'tags': self.tags or None,
  100. 'sources': self.sources or [],
  101. 'history': self.history or {},
  102. }
  103. if extended:
  104. info.update({
  105. 'link_dir': self.link_dir,
  106. 'archive_path': self.archive_path,
  107. 'bookmarked_date': self.bookmarked_date,
  108. 'updated_date': self.updated_date,
  109. 'domain': self.domain,
  110. 'path': self.path,
  111. 'basename': self.basename,
  112. 'extension': self.extension,
  113. 'base_url': self.base_url,
  114. 'is_static': self.is_static,
  115. 'is_archived': self.is_archived,
  116. 'num_outputs': self.num_outputs,
  117. 'num_failures': self.num_failures,
  118. 'oldest_archive_date': self.oldest_archive_date,
  119. 'newest_archive_date': self.newest_archive_date,
  120. })
  121. return info
  122. @classmethod
  123. def from_json(cls, json_info):
  124. from .util import parse_date
  125. allowed_fields = {f.name for f in fields(cls)}
  126. info = {
  127. key: val
  128. for key, val in json_info.items()
  129. if key in allowed_fields
  130. }
  131. info['updated'] = parse_date(info['updated'])
  132. json_history = info['history']
  133. cast_history = {}
  134. for method, method_history in json_history.items():
  135. cast_history[method] = []
  136. for json_result in method_history:
  137. assert isinstance(json_result, dict), 'Items in Link["history"][method] must be dicts'
  138. cast_result = ArchiveResult.from_json(json_result)
  139. cast_history[method].append(cast_result)
  140. info['history'] = cast_history
  141. return cls(**info)
  142. @property
  143. def link_dir(self) -> str:
  144. from .config import ARCHIVE_DIR
  145. return os.path.join(ARCHIVE_DIR, self.timestamp)
  146. @property
  147. def archive_path(self) -> str:
  148. from .config import ARCHIVE_DIR_NAME
  149. return '{}/{}'.format(ARCHIVE_DIR_NAME, self.timestamp)
  150. ### URL Helpers
  151. @property
  152. def urlhash(self):
  153. from .util import hashurl
  154. return hashurl(self.url)
  155. @property
  156. def extension(self) -> str:
  157. from .util import extension
  158. return extension(self.url)
  159. @property
  160. def domain(self) -> str:
  161. from .util import domain
  162. return domain(self.url)
  163. @property
  164. def path(self) -> str:
  165. from .util import path
  166. return path(self.url)
  167. @property
  168. def basename(self) -> str:
  169. from .util import basename
  170. return basename(self.url)
  171. @property
  172. def base_url(self) -> str:
  173. from .util import base_url
  174. return base_url(self.url)
  175. ### Pretty Printing Helpers
  176. @property
  177. def bookmarked_date(self) -> Optional[str]:
  178. from .util import ts_to_date
  179. return ts_to_date(self.timestamp) if self.timestamp else None
  180. @property
  181. def updated_date(self) -> Optional[str]:
  182. from .util import ts_to_date
  183. return ts_to_date(self.updated) if self.updated else None
  184. @property
  185. def archive_dates(self) -> List[datetime]:
  186. return [
  187. result.start_ts
  188. for method in self.history.keys()
  189. for result in self.history[method]
  190. ]
  191. @property
  192. def oldest_archive_date(self) -> Optional[datetime]:
  193. return min(self.archive_dates, default=None)
  194. @property
  195. def newest_archive_date(self) -> Optional[datetime]:
  196. return max(self.archive_dates, default=None)
  197. ### Archive Status Helpers
  198. @property
  199. def num_outputs(self) -> int:
  200. return len(tuple(filter(None, self.latest_outputs().values())))
  201. @property
  202. def num_failures(self) -> int:
  203. return sum(1
  204. for method in self.history.keys()
  205. for result in self.history[method]
  206. if result.status == 'failed')
  207. @property
  208. def is_static(self) -> bool:
  209. from .util import is_static_file
  210. return is_static_file(self.url)
  211. @property
  212. def is_archived(self) -> bool:
  213. from .config import ARCHIVE_DIR
  214. from .util import domain
  215. return os.path.exists(os.path.join(
  216. ARCHIVE_DIR,
  217. self.timestamp,
  218. domain(self.url),
  219. ))
  220. def latest_outputs(self, status: str=None) -> Dict[str, ArchiveOutput]:
  221. """get the latest output that each archive method produced for link"""
  222. ARCHIVE_METHODS = (
  223. 'title', 'favicon', 'wget', 'warc', 'pdf',
  224. 'screenshot', 'dom', 'git', 'media', 'archive_org',
  225. )
  226. latest: Dict[str, ArchiveOutput] = {}
  227. for archive_method in ARCHIVE_METHODS:
  228. # get most recent succesful result in history for each archive method
  229. history = self.history.get(archive_method) or []
  230. history = list(filter(lambda result: result.output, reversed(history)))
  231. if status is not None:
  232. history = list(filter(lambda result: result.status == status, history))
  233. history = list(history)
  234. if history:
  235. latest[archive_method] = history[0].output
  236. else:
  237. latest[archive_method] = None
  238. return latest
  239. def canonical_outputs(self) -> Dict[str, Optional[str]]:
  240. from .util import wget_output_path
  241. canonical = {
  242. 'index_url': 'index.html',
  243. 'favicon_url': 'favicon.ico',
  244. 'google_favicon_url': 'https://www.google.com/s2/favicons?domain={}'.format(self.domain),
  245. 'archive_url': wget_output_path(self),
  246. 'warc_url': 'warc',
  247. 'pdf_url': 'output.pdf',
  248. 'screenshot_url': 'screenshot.png',
  249. 'dom_url': 'output.html',
  250. 'archive_org_url': 'https://web.archive.org/web/{}'.format(self.base_url),
  251. 'git_url': 'git',
  252. 'media_url': 'media',
  253. }
  254. if self.is_static:
  255. # static binary files like PDF and images are handled slightly differently.
  256. # they're just downloaded once and aren't archived separately multiple times,
  257. # so the wget, screenshot, & pdf urls should all point to the same file
  258. static_url = wget_output_path(self)
  259. canonical.update({
  260. 'title': self.basename,
  261. 'archive_url': static_url,
  262. 'pdf_url': static_url,
  263. 'screenshot_url': static_url,
  264. 'dom_url': static_url,
  265. })
  266. return canonical