ArchiveBox/archivebox/extractors/favicon.py

65 lines
1.7 KiB
Python
Raw Normal View History

2019-04-27 21:26:24 +00:00
__package__ = 'archivebox.extractors'
import os
from typing import Optional
from ..index.schema import Link, ArchiveResult, ArchiveOutput
2020-06-26 02:14:40 +00:00
from ..system import chmod_file, run
2019-05-01 03:13:04 +00:00
from ..util import enforce_types, domain
2019-04-27 21:26:24 +00:00
from ..config import (
TIMEOUT,
SAVE_FAVICON,
CURL_BINARY,
CURL_VERSION,
CHECK_SSL_VALIDITY,
2020-06-26 01:30:29 +00:00
CURL_USER_AGENT,
2019-04-27 21:26:24 +00:00
)
2019-05-01 03:13:04 +00:00
from ..cli.logging import TimedProgress
2019-04-27 21:26:24 +00:00
@enforce_types
def should_save_favicon(link: Link, out_dir: Optional[str]=None) -> bool:
out_dir = out_dir or link.link_dir
if os.path.exists(os.path.join(out_dir, 'favicon.ico')):
return False
return SAVE_FAVICON
@enforce_types
def save_favicon(link: Link, out_dir: Optional[str]=None, timeout: int=TIMEOUT) -> ArchiveResult:
"""download site favicon from google's favicon api"""
out_dir = out_dir or link.link_dir
output: ArchiveOutput = 'favicon.ico'
cmd = [
CURL_BINARY,
2020-06-25 21:47:55 +00:00
'--silent',
2019-04-27 21:26:24 +00:00
'--max-time', str(timeout),
'--location',
'--output', str(output),
2020-06-26 02:14:40 +00:00
*(['--user-agent', '{}'.format(CURL_USER_AGENT)] if CURL_USER_AGENT else []),
2019-04-27 21:26:24 +00:00
*([] if CHECK_SSL_VALIDITY else ['--insecure']),
'https://www.google.com/s2/favicons?domain={}'.format(domain(link.url)),
]
2020-06-26 01:30:29 +00:00
status = 'pending'
2019-04-27 21:26:24 +00:00
timer = TimedProgress(timeout, prefix=' ')
try:
2020-06-26 02:14:40 +00:00
run(cmd, cwd=out_dir, timeout=timeout)
2019-04-27 21:26:24 +00:00
chmod_file(output, cwd=out_dir)
2020-06-26 01:30:29 +00:00
status = 'succeeded'
2019-04-27 21:26:24 +00:00
except Exception as err:
status = 'failed'
output = err
finally:
timer.end()
return ArchiveResult(
cmd=cmd,
pwd=out_dir,
cmd_version=CURL_VERSION,
output=output,
status=status,
**timer.stats,
)