headers.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. __package__ = 'archivebox.extractors'
  2. from pathlib import Path
  3. from typing import Optional
  4. from ..index.schema import Link, ArchiveResult, ArchiveOutput
  5. from ..system import atomic_write
  6. from ..util import (
  7. enforce_types,
  8. get_headers,
  9. dedupe,
  10. )
  11. from ..config import (
  12. TIMEOUT,
  13. CURL_BINARY,
  14. CURL_ARGS,
  15. CURL_EXTRA_ARGS,
  16. CURL_USER_AGENT,
  17. CURL_VERSION,
  18. CHECK_SSL_VALIDITY,
  19. SAVE_HEADERS
  20. )
  21. from ..logging_util import TimedProgress
  22. @enforce_types
  23. def should_save_headers(link: Link, out_dir: Optional[str]=None, overwrite: Optional[bool]=False) -> bool:
  24. out_dir = out_dir or Path(link.link_dir)
  25. if not overwrite and (out_dir / 'headers.json').exists():
  26. return False
  27. return SAVE_HEADERS
  28. @enforce_types
  29. def save_headers(link: Link, out_dir: Optional[str]=None, timeout: int=TIMEOUT) -> ArchiveResult:
  30. """Download site headers"""
  31. out_dir = Path(out_dir or link.link_dir)
  32. output_folder = out_dir.absolute()
  33. output: ArchiveOutput = 'headers.json'
  34. status = 'succeeded'
  35. timer = TimedProgress(timeout, prefix=' ')
  36. # later options take precedence
  37. options = [
  38. *CURL_ARGS,
  39. *CURL_EXTRA_ARGS,
  40. '--head',
  41. '--max-time', str(timeout),
  42. *(['--user-agent', '{}'.format(CURL_USER_AGENT)] if CURL_USER_AGENT else []),
  43. *([] if CHECK_SSL_VALIDITY else ['--insecure']),
  44. ]
  45. cmd = [
  46. CURL_BINARY,
  47. *dedupe(options),
  48. link.url,
  49. ]
  50. try:
  51. json_headers = get_headers(link.url, timeout=timeout)
  52. output_folder.mkdir(exist_ok=True)
  53. atomic_write(str(output_folder / "headers.json"), json_headers)
  54. except (Exception, OSError) as err:
  55. status = 'failed'
  56. output = err
  57. finally:
  58. timer.end()
  59. return ArchiveResult(
  60. cmd=cmd,
  61. pwd=str(out_dir),
  62. cmd_version=CURL_VERSION,
  63. output=output,
  64. status=status,
  65. **timer.stats,
  66. )