util.py 13 KB

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