2
0

util.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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. return response.text
  142. @enforce_types
  143. def get_headers(url: str, timeout: int=None) -> str:
  144. """Download the contents of a remote url and return the headers"""
  145. from .config import TIMEOUT, CHECK_SSL_VALIDITY, WGET_USER_AGENT
  146. timeout = timeout or TIMEOUT
  147. try:
  148. response = requests.head(
  149. url,
  150. headers={'User-Agent': WGET_USER_AGENT},
  151. verify=CHECK_SSL_VALIDITY,
  152. timeout=timeout,
  153. allow_redirects=True,
  154. )
  155. if response.status_code >= 400:
  156. raise RequestException
  157. except ReadTimeout:
  158. raise
  159. except RequestException:
  160. response = requests.get(
  161. url,
  162. headers={'User-Agent': WGET_USER_AGENT},
  163. verify=CHECK_SSL_VALIDITY,
  164. timeout=timeout,
  165. stream=True
  166. )
  167. return pyjson.dumps(
  168. {
  169. 'Status-Code': response.status_code,
  170. **dict(response.headers),
  171. },
  172. indent=4,
  173. )
  174. @enforce_types
  175. def chrome_args(**options) -> List[str]:
  176. """helper to build up a chrome shell command with arguments"""
  177. # Chrome CLI flag documentation: https://peter.sh/experiments/chromium-command-line-switches/
  178. from .config import CHROME_OPTIONS, CHROME_VERSION
  179. options = {**CHROME_OPTIONS, **options}
  180. if not options['CHROME_BINARY']:
  181. raise Exception('Could not find any CHROME_BINARY installed on your system')
  182. cmd_args = [options['CHROME_BINARY']]
  183. if options['CHROME_HEADLESS']:
  184. chrome_major_version = int(re.search(r'\s(\d+)\.\d', CHROME_VERSION)[1])
  185. if chrome_major_version >= 111:
  186. cmd_args += ("--headless=new",)
  187. else:
  188. cmd_args += ('--headless',)
  189. if not options['CHROME_SANDBOX']:
  190. # assume this means we are running inside a docker container
  191. # in docker, GPU support is limited, sandboxing is unecessary,
  192. # and SHM is limited to 64MB by default (which is too low to be usable).
  193. cmd_args += (
  194. "--no-sandbox",
  195. "--no-zygote",
  196. "--disable-dev-shm-usage",
  197. "--disable-software-rasterizer",
  198. "--run-all-compositor-stages-before-draw",
  199. "--hide-scrollbars",
  200. "--autoplay-policy=no-user-gesture-required",
  201. "--no-first-run",
  202. "--use-fake-ui-for-media-stream",
  203. "--use-fake-device-for-media-stream",
  204. "--disable-sync",
  205. # "--password-store=basic",
  206. )
  207. # disable automatic updating when running headless, as there's no user to see the upgrade prompts
  208. cmd_args += ("--simulate-outdated-no-au='Tue, 31 Dec 2099 23:59:59 GMT'",)
  209. # set window size for screenshot/pdf/etc. rendering
  210. cmd_args += ('--window-size={}'.format(options['RESOLUTION']),)
  211. if not options['CHECK_SSL_VALIDITY']:
  212. cmd_args += ('--disable-web-security', '--ignore-certificate-errors')
  213. if options['CHROME_USER_AGENT']:
  214. cmd_args += ('--user-agent={}'.format(options['CHROME_USER_AGENT']),)
  215. if options['CHROME_TIMEOUT']:
  216. cmd_args += ('--timeout={}'.format(options['CHROME_TIMEOUT'] * 1000),)
  217. if options['CHROME_USER_DATA_DIR']:
  218. cmd_args.append('--user-data-dir={}'.format(options['CHROME_USER_DATA_DIR']))
  219. return cmd_args
  220. def chrome_cleanup():
  221. """
  222. Cleans up any state or runtime files that chrome leaves behind when killed by
  223. a timeout or other error
  224. """
  225. from .config import IN_DOCKER
  226. if IN_DOCKER and lexists("/home/archivebox/.config/chromium/SingletonLock"):
  227. remove_file("/home/archivebox/.config/chromium/SingletonLock")
  228. def ansi_to_html(text):
  229. """
  230. Based on: https://stackoverflow.com/questions/19212665/python-converting-ansi-color-codes-to-html
  231. """
  232. from .config import COLOR_DICT
  233. TEMPLATE = '<span style="color: rgb{}"><br>'
  234. text = text.replace('[m', '</span>')
  235. def single_sub(match):
  236. argsdict = match.groupdict()
  237. if argsdict['arg_3'] is None:
  238. if argsdict['arg_2'] is None:
  239. _, color = 0, argsdict['arg_1']
  240. else:
  241. _, color = argsdict['arg_1'], argsdict['arg_2']
  242. else:
  243. _, color = argsdict['arg_3'], argsdict['arg_2']
  244. return TEMPLATE.format(COLOR_DICT[color][0])
  245. return COLOR_REGEX.sub(single_sub, text)
  246. class AttributeDict(dict):
  247. """Helper to allow accessing dict values via Example.key or Example['key']"""
  248. def __init__(self, *args, **kwargs):
  249. super().__init__(*args, **kwargs)
  250. # Recursively convert nested dicts to AttributeDicts (optional):
  251. # for key, val in self.items():
  252. # if isinstance(val, dict) and type(val) is not AttributeDict:
  253. # self[key] = AttributeDict(val)
  254. def __getattr__(self, attr: str) -> Any:
  255. return dict.__getitem__(self, attr)
  256. def __setattr__(self, attr: str, value: Any) -> None:
  257. return dict.__setitem__(self, attr, value)
  258. class ExtendedEncoder(pyjson.JSONEncoder):
  259. """
  260. Extended json serializer that supports serializing several model
  261. fields and objects
  262. """
  263. def default(self, obj):
  264. cls_name = obj.__class__.__name__
  265. if hasattr(obj, '_asdict'):
  266. return obj._asdict()
  267. elif isinstance(obj, bytes):
  268. return obj.decode()
  269. elif isinstance(obj, datetime):
  270. return obj.isoformat()
  271. elif isinstance(obj, Exception):
  272. return '{}: {}'.format(obj.__class__.__name__, obj)
  273. elif isinstance(obj, Path):
  274. return str(obj)
  275. elif cls_name in ('dict_items', 'dict_keys', 'dict_values'):
  276. return tuple(obj)
  277. return pyjson.JSONEncoder.default(self, obj)