2
0

util.py 11 KB

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