favicon.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 chmod_file, run
  6. from ..util import enforce_types, domain
  7. from ..config import (
  8. TIMEOUT,
  9. SAVE_FAVICON,
  10. FAVICON_PROVIDER,
  11. CURL_BINARY,
  12. CURL_ARGS,
  13. CURL_VERSION,
  14. CHECK_SSL_VALIDITY,
  15. CURL_USER_AGENT,
  16. )
  17. from ..logging_util import TimedProgress
  18. @enforce_types
  19. def should_save_favicon(link: Link, out_dir: Optional[str]=None, overwrite: Optional[bool]=False) -> bool:
  20. out_dir = out_dir or Path(link.link_dir)
  21. if not overwrite and (out_dir / 'favicon.ico').exists():
  22. return False
  23. return SAVE_FAVICON
  24. @enforce_types
  25. def save_favicon(link: Link, out_dir: Optional[Path]=None, timeout: int=TIMEOUT) -> ArchiveResult:
  26. """download site favicon from google's favicon api"""
  27. out_dir = out_dir or link.link_dir
  28. output: ArchiveOutput = 'favicon.ico'
  29. cmd = [
  30. CURL_BINARY,
  31. *CURL_ARGS,
  32. '--max-time', str(timeout),
  33. '--output', str(output),
  34. *(['--user-agent', '{}'.format(CURL_USER_AGENT)] if CURL_USER_AGENT else []),
  35. *([] if CHECK_SSL_VALIDITY else ['--insecure']),
  36. FAVICON_PROVIDER.format(domain(link.url)),
  37. ]
  38. status = 'failed'
  39. timer = TimedProgress(timeout, prefix=' ')
  40. try:
  41. run(cmd, cwd=str(out_dir), timeout=timeout)
  42. chmod_file(output, cwd=str(out_dir))
  43. status = 'succeeded'
  44. except Exception as err:
  45. output = err
  46. finally:
  47. timer.end()
  48. return ArchiveResult(
  49. cmd=cmd,
  50. pwd=str(out_dir),
  51. cmd_version=CURL_VERSION,
  52. output=output,
  53. status=status,
  54. **timer.stats,
  55. )