util.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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
  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 = 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'http[s]?://' # start matching from allowed schemes
  49. r'(?:[a-zA-Z]|[0-9]' # followed by allowed alphanum characters
  50. r'|[$-_@.&+]|[!*\(\),]' # or allowed symbols
  51. r'|(?:%[0-9a-fA-F][0-9a-fA-F]))' # or allowed unicode bytes
  52. r'[^\]\[\(\)<>"\'\s]+', # stop parsing at these symbols
  53. re.IGNORECASE,
  54. )
  55. COLOR_REGEX = re.compile(r'\[(?P<arg_1>\d+)(;(?P<arg_2>\d+)(;(?P<arg_3>\d+))?)?m')
  56. def is_static_file(url: str):
  57. # TODO: the proper way is with MIME type detection + ext, not only extension
  58. from .config import STATICFILE_EXTENSIONS
  59. return extension(url).lower() in STATICFILE_EXTENSIONS
  60. def enforce_types(func):
  61. """
  62. Enforce function arg and kwarg types at runtime using its python3 type hints
  63. """
  64. # TODO: check return type as well
  65. @wraps(func)
  66. def typechecked_function(*args, **kwargs):
  67. sig = signature(func)
  68. def check_argument_type(arg_key, arg_val):
  69. try:
  70. annotation = sig.parameters[arg_key].annotation
  71. except KeyError:
  72. annotation = None
  73. if annotation is not None and annotation.__class__ is type:
  74. if not isinstance(arg_val, annotation):
  75. raise TypeError(
  76. '{}(..., {}: {}) got unexpected {} argument {}={}'.format(
  77. func.__name__,
  78. arg_key,
  79. annotation.__name__,
  80. type(arg_val).__name__,
  81. arg_key,
  82. str(arg_val)[:64],
  83. )
  84. )
  85. # check args
  86. for arg_val, arg_key in zip(args, sig.parameters):
  87. check_argument_type(arg_key, arg_val)
  88. # check kwargs
  89. for arg_key, arg_val in kwargs.items():
  90. check_argument_type(arg_key, arg_val)
  91. return func(*args, **kwargs)
  92. return typechecked_function
  93. def docstring(text: Optional[str]):
  94. """attach the given docstring to the decorated function"""
  95. def decorator(func):
  96. if text:
  97. func.__doc__ = text
  98. return func
  99. return decorator
  100. @enforce_types
  101. def str_between(string: str, start: str, end: str=None) -> str:
  102. """(<abc>12345</def>, <abc>, </def>) -> 12345"""
  103. content = string.split(start, 1)[-1]
  104. if end is not None:
  105. content = content.rsplit(end, 1)[0]
  106. return content
  107. @enforce_types
  108. def parse_date(date: Any) -> Optional[datetime]:
  109. """Parse unix timestamps, iso format, and human-readable strings"""
  110. if date is None:
  111. return None
  112. if isinstance(date, datetime):
  113. return date
  114. if isinstance(date, (float, int)):
  115. date = str(date)
  116. if isinstance(date, str):
  117. return dateparser(date)
  118. raise ValueError('Tried to parse invalid date! {}'.format(date))
  119. @enforce_types
  120. def download_url(url: str, timeout: int=None) -> str:
  121. """Download the contents of a remote url and return the text"""
  122. from .config import TIMEOUT, CHECK_SSL_VALIDITY, WGET_USER_AGENT
  123. timeout = timeout or TIMEOUT
  124. response = requests.get(
  125. url,
  126. headers={'User-Agent': WGET_USER_AGENT},
  127. verify=CHECK_SSL_VALIDITY,
  128. timeout=timeout,
  129. )
  130. content_type = response.headers.get('Content-Type', '')
  131. encoding = http_content_type_encoding(content_type) or html_body_declared_encoding(response.text)
  132. if encoding is not None:
  133. response.encoding = encoding
  134. return response.text
  135. @enforce_types
  136. def get_headers(url: str, timeout: int=None) -> str:
  137. """Download the contents of a remote url and return the headers"""
  138. from .config import TIMEOUT, CHECK_SSL_VALIDITY, WGET_USER_AGENT
  139. timeout = timeout or TIMEOUT
  140. try:
  141. response = requests.head(
  142. url,
  143. headers={'User-Agent': WGET_USER_AGENT},
  144. verify=CHECK_SSL_VALIDITY,
  145. timeout=timeout,
  146. allow_redirects=True,
  147. )
  148. if response.status_code >= 400:
  149. raise RequestException
  150. except ReadTimeout:
  151. raise
  152. except RequestException:
  153. response = requests.get(
  154. url,
  155. headers={'User-Agent': WGET_USER_AGENT},
  156. verify=CHECK_SSL_VALIDITY,
  157. timeout=timeout,
  158. stream=True
  159. )
  160. return pyjson.dumps(
  161. {
  162. 'Status-Code': response.status_code,
  163. **dict(response.headers),
  164. },
  165. indent=4,
  166. )
  167. @enforce_types
  168. def chrome_args(**options) -> List[str]:
  169. """helper to build up a chrome shell command with arguments"""
  170. from .config import CHROME_OPTIONS
  171. options = {**CHROME_OPTIONS, **options}
  172. cmd_args = [options['CHROME_BINARY']]
  173. if options['CHROME_HEADLESS']:
  174. cmd_args += ('--headless',)
  175. if not options['CHROME_SANDBOX']:
  176. # assume this means we are running inside a docker container
  177. # in docker, GPU support is limited, sandboxing is unecessary,
  178. # and SHM is limited to 64MB by default (which is too low to be usable).
  179. cmd_args += (
  180. '--no-sandbox',
  181. '--disable-gpu',
  182. '--disable-dev-shm-usage',
  183. '--disable-software-rasterizer',
  184. )
  185. if not options['CHECK_SSL_VALIDITY']:
  186. cmd_args += ('--disable-web-security', '--ignore-certificate-errors')
  187. if options['CHROME_USER_AGENT']:
  188. cmd_args += ('--user-agent={}'.format(options['CHROME_USER_AGENT']),)
  189. if options['RESOLUTION']:
  190. cmd_args += ('--window-size={}'.format(options['RESOLUTION']),)
  191. if options['TIMEOUT']:
  192. cmd_args += ('--timeout={}'.format((options['TIMEOUT']) * 1000),)
  193. if options['CHROME_USER_DATA_DIR']:
  194. cmd_args.append('--user-data-dir={}'.format(options['CHROME_USER_DATA_DIR']))
  195. return cmd_args
  196. def ansi_to_html(text):
  197. """
  198. Based on: https://stackoverflow.com/questions/19212665/python-converting-ansi-color-codes-to-html
  199. """
  200. from .config import COLOR_DICT
  201. TEMPLATE = '<span style="color: rgb{}"><br>'
  202. text = text.replace('[m', '</span>')
  203. def single_sub(match):
  204. argsdict = match.groupdict()
  205. if argsdict['arg_3'] is None:
  206. if argsdict['arg_2'] is None:
  207. _, color = 0, argsdict['arg_1']
  208. else:
  209. _, color = argsdict['arg_1'], argsdict['arg_2']
  210. else:
  211. _, color = argsdict['arg_3'], argsdict['arg_2']
  212. return TEMPLATE.format(COLOR_DICT[color][0])
  213. return COLOR_REGEX.sub(single_sub, text)
  214. class AttributeDict(dict):
  215. """Helper to allow accessing dict values via Example.key or Example['key']"""
  216. def __init__(self, *args, **kwargs):
  217. super().__init__(*args, **kwargs)
  218. # Recursively convert nested dicts to AttributeDicts (optional):
  219. # for key, val in self.items():
  220. # if isinstance(val, dict) and type(val) is not AttributeDict:
  221. # self[key] = AttributeDict(val)
  222. def __getattr__(self, attr: str) -> Any:
  223. return dict.__getitem__(self, attr)
  224. def __setattr__(self, attr: str, value: Any) -> None:
  225. return dict.__setitem__(self, attr, value)
  226. class ExtendedEncoder(pyjson.JSONEncoder):
  227. """
  228. Extended json serializer that supports serializing several model
  229. fields and objects
  230. """
  231. def default(self, obj):
  232. cls_name = obj.__class__.__name__
  233. if hasattr(obj, '_asdict'):
  234. return obj._asdict()
  235. elif isinstance(obj, bytes):
  236. return obj.decode()
  237. elif isinstance(obj, datetime):
  238. return obj.isoformat()
  239. elif isinstance(obj, Exception):
  240. return '{}: {}'.format(obj.__class__.__name__, obj)
  241. elif isinstance(obj, Path):
  242. return str(obj)
  243. elif cls_name in ('dict_items', 'dict_keys', 'dict_values'):
  244. return tuple(obj)
  245. return pyjson.JSONEncoder.default(self, obj)