favicon.py 1.9 KB

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