util.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. __package__ = 'archivebox'
  2. import re
  3. import requests
  4. import json as pyjson
  5. from typing import List, Optional, Any
  6. from pathlib import Path
  7. from inspect import signature
  8. from functools import wraps
  9. from hashlib import sha256
  10. from urllib.parse import urlparse, quote, unquote
  11. from html import escape, unescape
  12. from datetime import datetime, timezone
  13. from dateparser import parse as dateparser
  14. from requests.exceptions import RequestException, ReadTimeout
  15. from .vendor.base32_crockford import encode as base32_encode # type: ignore
  16. from w3lib.encoding import html_body_declared_encoding, http_content_type_encoding
  17. from os.path import lexists
  18. from os import remove as remove_file
  19. try:
  20. import chardet
  21. detect_encoding = lambda rawdata: chardet.detect(rawdata)["encoding"]
  22. except ImportError:
  23. detect_encoding = lambda rawdata: "utf-8"
  24. ### Parsing Helpers
  25. # All of these are (str) -> str
  26. # shortcuts to: https://docs.python.org/3/library/urllib.parse.html#url-parsing
  27. scheme = lambda url: urlparse(url).scheme.lower()
  28. without_scheme = lambda url: urlparse(url)._replace(scheme='').geturl().strip('//')
  29. without_query = lambda url: urlparse(url)._replace(query='').geturl().strip('//')
  30. without_fragment = lambda url: urlparse(url)._replace(fragment='').geturl().strip('//')
  31. without_path = lambda url: urlparse(url)._replace(path='', fragment='', query='').geturl().strip('//')
  32. path = lambda url: urlparse(url).path
  33. basename = lambda url: urlparse(url).path.rsplit('/', 1)[-1]
  34. domain = lambda url: urlparse(url).netloc
  35. query = lambda url: urlparse(url).query
  36. fragment = lambda url: urlparse(url).fragment
  37. extension = lambda url: basename(url).rsplit('.', 1)[-1].lower() if '.' in basename(url) else ''
  38. base_url = lambda url: without_scheme(url) # uniq base url used to dedupe links
  39. without_www = lambda url: url.replace('://www.', '://', 1)
  40. without_trailing_slash = lambda url: url[:-1] if url[-1] == '/' else url.replace('/?', '?')
  41. hashurl = lambda url: base32_encode(int(sha256(base_url(url).encode('utf-8')).hexdigest(), 16))[:20]
  42. urlencode = lambda s: s and quote(s, encoding='utf-8', errors='replace')
  43. urldecode = lambda s: s and unquote(s)
  44. htmlencode = lambda s: s and escape(s, quote=True)
  45. htmldecode = lambda s: s and unescape(s)
  46. short_ts = lambda ts: str(parse_date(ts).timestamp()).split('.')[0]
  47. ts_to_date_str = lambda ts: ts and parse_date(ts).strftime('%Y-%m-%d %H:%M')
  48. ts_to_iso = lambda ts: ts and parse_date(ts).isoformat()
  49. URL_REGEX = re.compile(
  50. r'(?=('
  51. r'http[s]?://' # start matching from allowed schemes
  52. r'(?:[a-zA-Z]|[0-9]' # followed by allowed alphanum characters
  53. r'|[-_$@.&+!*\(\),]' # or allowed symbols (keep hyphen first to match literal hyphen)
  54. r'|(?:%[0-9a-fA-F][0-9a-fA-F]))' # or allowed unicode bytes
  55. r'[^\]\[\(\)<>"\'\s]+' # stop parsing at these symbols
  56. r'))',
  57. re.IGNORECASE,
  58. )
  59. COLOR_REGEX = re.compile(r'\[(?P<arg_1>\d+)(;(?P<arg_2>\d+)(;(?P<arg_3>\d+))?)?m')
  60. def is_static_file(url: str):
  61. # TODO: the proper way is with MIME type detection + ext, not only extension
  62. from .config import STATICFILE_EXTENSIONS
  63. return extension(url).lower() in STATICFILE_EXTENSIONS
  64. def enforce_types(func):
  65. """
  66. Enforce function arg and kwarg types at runtime using its python3 type hints
  67. """
  68. # TODO: check return type as well
  69. @wraps(func)
  70. def typechecked_function(*args, **kwargs):
  71. sig = signature(func)
  72. def check_argument_type(arg_key, arg_val):
  73. try:
  74. annotation = sig.parameters[arg_key].annotation
  75. except KeyError:
  76. annotation = None
  77. if annotation is not None and annotation.__class__ is type:
  78. if not isinstance(arg_val, annotation):
  79. raise TypeError(
  80. '{}(..., {}: {}) got unexpected {} argument {}={}'.format(
  81. func.__name__,
  82. arg_key,
  83. annotation.__name__,
  84. type(arg_val).__name__,
  85. arg_key,
  86. str(arg_val)[:64],
  87. )
  88. )
  89. # check args
  90. for arg_val, arg_key in zip(args, sig.parameters):
  91. check_argument_type(arg_key, arg_val)
  92. # check kwargs
  93. for arg_key, arg_val in kwargs.items():
  94. check_argument_type(arg_key, arg_val)
  95. return func(*args, **kwargs)
  96. return typechecked_function
  97. def docstring(text: Optional[str]):
  98. """attach the given docstring to the decorated function"""
  99. def decorator(func):
  100. if text:
  101. func.__doc__ = text
  102. return func
  103. return decorator
  104. @enforce_types
  105. def str_between(string: str, start: str, end: str=None) -> str:
  106. """(<abc>12345</def>, <abc>, </def>) -> 12345"""
  107. content = string.split(start, 1)[-1]
  108. if end is not None:
  109. content = content.rsplit(end, 1)[0]
  110. return content
  111. @enforce_types
  112. def parse_date(date: Any) -> Optional[datetime]:
  113. """Parse unix timestamps, iso format, and human-readable strings"""
  114. if date is None:
  115. return None
  116. if isinstance(date, datetime):
  117. if date.tzinfo is None:
  118. return date.replace(tzinfo=timezone.utc)
  119. assert date.tzinfo.utcoffset(datetime.now()).seconds == 0, 'Refusing to load a non-UTC date!'
  120. return date
  121. if isinstance(date, (float, int)):
  122. date = str(date)
  123. if isinstance(date, str):
  124. return dateparser(date, settings={'TIMEZONE': 'UTC'}).replace(tzinfo=timezone.utc)
  125. raise ValueError('Tried to parse invalid date! {}'.format(date))
  126. @enforce_types
  127. def download_url(url: str, timeout: int=None) -> str:
  128. """Download the contents of a remote url and return the text"""
  129. from .config import TIMEOUT, CHECK_SSL_VALIDITY, WGET_USER_AGENT
  130. timeout = timeout or TIMEOUT
  131. response = requests.get(
  132. url,
  133. headers={'User-Agent': WGET_USER_AGENT},
  134. verify=CHECK_SSL_VALIDITY,
  135. timeout=timeout,
  136. )
  137. content_type = response.headers.get('Content-Type', '')
  138. encoding = http_content_type_encoding(content_type) or html_body_declared_encoding(response.text)
  139. if encoding is not None:
  140. response.encoding = encoding
  141. try:
  142. return response.text
  143. except UnicodeDecodeError:
  144. # if response is non-test (e.g. image or other binary files), just return the filename instead
  145. return url.rsplit('/', 1)[-1]
  146. @enforce_types
  147. def get_headers(url: str, timeout: int=None) -> str:
  148. """Download the contents of a remote url and return the headers"""
  149. from .config import TIMEOUT, CHECK_SSL_VALIDITY, WGET_USER_AGENT
  150. timeout = timeout or TIMEOUT
  151. try:
  152. response = requests.head(
  153. url,
  154. headers={'User-Agent': WGET_USER_AGENT},
  155. verify=CHECK_SSL_VALIDITY,
  156. timeout=timeout,
  157. allow_redirects=True,
  158. )
  159. if response.status_code >= 400:
  160. raise RequestException
  161. except ReadTimeout:
  162. raise
  163. except RequestException:
  164. response = requests.get(
  165. url,
  166. headers={'User-Agent': WGET_USER_AGENT},
  167. verify=CHECK_SSL_VALIDITY,
  168. timeout=timeout,
  169. stream=True
  170. )
  171. return pyjson.dumps(
  172. {
  173. 'Status-Code': response.status_code,
  174. **dict(response.headers),
  175. },
  176. indent=4,
  177. )
  178. @enforce_types
  179. def chrome_args(**options) -> List[str]:
  180. """helper to build up a chrome shell command with arguments"""
  181. # Chrome CLI flag documentation: https://peter.sh/experiments/chromium-command-line-switches/
  182. from .config import (
  183. CHROME_OPTIONS,
  184. CHROME_VERSION,
  185. CHROME_EXTRA_ARGS,
  186. )
  187. options = {**CHROME_OPTIONS, **options}
  188. if not options['CHROME_BINARY']:
  189. raise Exception('Could not find any CHROME_BINARY installed on your system')
  190. cmd_args = [options['CHROME_BINARY']]
  191. cmd_args += CHROME_EXTRA_ARGS
  192. if options['CHROME_HEADLESS']:
  193. chrome_major_version = int(re.search(r'\s(\d+)\.\d', CHROME_VERSION)[1])
  194. if chrome_major_version >= 111:
  195. cmd_args += ("--headless=new",)
  196. else:
  197. cmd_args += ('--headless',)
  198. if not options['CHROME_SANDBOX']:
  199. # assume this means we are running inside a docker container
  200. # in docker, GPU support is limited, sandboxing is unecessary,
  201. # and SHM is limited to 64MB by default (which is too low to be usable).
  202. cmd_args += (
  203. "--no-sandbox",
  204. "--no-zygote",
  205. "--disable-dev-shm-usage",
  206. "--disable-software-rasterizer",
  207. "--run-all-compositor-stages-before-draw",
  208. "--hide-scrollbars",
  209. "--autoplay-policy=no-user-gesture-required",
  210. "--no-first-run",
  211. "--use-fake-ui-for-media-stream",
  212. "--use-fake-device-for-media-stream",
  213. "--disable-sync",
  214. # "--password-store=basic",
  215. )
  216. # disable automatic updating when running headless, as there's no user to see the upgrade prompts
  217. cmd_args += ("--simulate-outdated-no-au='Tue, 31 Dec 2099 23:59:59 GMT'",)
  218. # set window size for screenshot/pdf/etc. rendering
  219. cmd_args += ('--window-size={}'.format(options['RESOLUTION']),)
  220. if not options['CHECK_SSL_VALIDITY']:
  221. cmd_args += ('--disable-web-security', '--ignore-certificate-errors')
  222. if options['CHROME_USER_AGENT']:
  223. cmd_args += ('--user-agent={}'.format(options['CHROME_USER_AGENT']),)
  224. if options['CHROME_TIMEOUT']:
  225. cmd_args += ('--timeout={}'.format(options['CHROME_TIMEOUT'] * 1000),)
  226. if options['CHROME_USER_DATA_DIR']:
  227. cmd_args.append('--user-data-dir={}'.format(options['CHROME_USER_DATA_DIR']))
  228. return dedupe(cmd_args)
  229. def chrome_cleanup():
  230. """
  231. Cleans up any state or runtime files that chrome leaves behind when killed by
  232. a timeout or other error
  233. """
  234. from .config import IN_DOCKER
  235. if IN_DOCKER and lexists("/home/archivebox/.config/chromium/SingletonLock"):
  236. remove_file("/home/archivebox/.config/chromium/SingletonLock")
  237. def ansi_to_html(text):
  238. """
  239. Based on: https://stackoverflow.com/questions/19212665/python-converting-ansi-color-codes-to-html
  240. """
  241. from .config import COLOR_DICT
  242. TEMPLATE = '<span style="color: rgb{}"><br>'
  243. text = text.replace('[m', '</span>')
  244. def single_sub(match):
  245. argsdict = match.groupdict()
  246. if argsdict['arg_3'] is None:
  247. if argsdict['arg_2'] is None:
  248. _, color = 0, argsdict['arg_1']
  249. else:
  250. _, color = argsdict['arg_1'], argsdict['arg_2']
  251. else:
  252. _, color = argsdict['arg_3'], argsdict['arg_2']
  253. return TEMPLATE.format(COLOR_DICT[color][0])
  254. return COLOR_REGEX.sub(single_sub, text)
  255. @enforce_types
  256. def dedupe(options: List[str]) -> List[str]:
  257. """
  258. Deduplicates the given options. Options that come later clobber earlier
  259. conflicting options.
  260. """
  261. deduped = {}
  262. for option in options:
  263. deduped[option.split('=')[0]] = option
  264. return list(deduped.values())
  265. class AttributeDict(dict):
  266. """Helper to allow accessing dict values via Example.key or Example['key']"""
  267. def __init__(self, *args, **kwargs):
  268. super().__init__(*args, **kwargs)
  269. # Recursively convert nested dicts to AttributeDicts (optional):
  270. # for key, val in self.items():
  271. # if isinstance(val, dict) and type(val) is not AttributeDict:
  272. # self[key] = AttributeDict(val)
  273. def __getattr__(self, attr: str) -> Any:
  274. return dict.__getitem__(self, attr)
  275. def __setattr__(self, attr: str, value: Any) -> None:
  276. return dict.__setitem__(self, attr, value)
  277. class ExtendedEncoder(pyjson.JSONEncoder):
  278. """
  279. Extended json serializer that supports serializing several model
  280. fields and objects
  281. """
  282. def default(self, obj):
  283. cls_name = obj.__class__.__name__
  284. if hasattr(obj, '_asdict'):
  285. return obj._asdict()
  286. elif isinstance(obj, bytes):
  287. return obj.decode()
  288. elif isinstance(obj, datetime):
  289. return obj.isoformat()
  290. elif isinstance(obj, Exception):
  291. return '{}: {}'.format(obj.__class__.__name__, obj)
  292. elif isinstance(obj, Path):
  293. return str(obj)
  294. elif cls_name in ('dict_items', 'dict_keys', 'dict_values'):
  295. return tuple(obj)
  296. return pyjson.JSONEncoder.default(self, obj)