ArchiveBox/archivebox/extractors/screenshot.py

70 lines
2 KiB
Python
Raw Normal View History

2019-04-27 21:26:24 +00:00
__package__ = 'archivebox.extractors'
2020-09-15 19:05:48 +00:00
from pathlib import Path
2019-04-27 21:26:24 +00:00
from typing import Optional
2019-05-01 03:13:04 +00:00
from ..index.schema import Link, ArchiveResult, ArchiveOutput, ArchiveError
2024-10-01 00:13:55 +00:00
from archivebox.misc.system import run, chmod_file
2024-10-01 00:25:15 +00:00
from archivebox.misc.util import enforce_types, is_static_file
from ..logging_util import TimedProgress
2019-04-27 21:26:24 +00:00
def get_output_path():
return 'screenshot.png'
2019-04-27 21:26:24 +00:00
@enforce_types
def should_save_screenshot(link: Link, out_dir: Optional[Path]=None, overwrite: Optional[bool]=False) -> bool:
from plugins_extractor.chrome.apps import CHROME_CONFIG
2019-04-27 21:26:24 +00:00
if is_static_file(link.url):
return False
out_dir = out_dir or Path(link.link_dir)
if not overwrite and (out_dir / get_output_path()).exists():
2019-04-27 21:26:24 +00:00
return False
return CHROME_CONFIG.SAVE_SCREENSHOT
2019-04-27 21:26:24 +00:00
@enforce_types
def save_screenshot(link: Link, out_dir: Optional[Path]=None, timeout: int=60) -> ArchiveResult:
2019-04-27 21:26:24 +00:00
"""take screenshot of site using chrome --headless"""
from plugins_extractor.chrome.apps import CHROME_CONFIG, CHROME_BINARY
CHROME_BIN = CHROME_BINARY.load()
assert CHROME_BIN.abspath and CHROME_BIN.version
2020-09-15 19:05:48 +00:00
out_dir = out_dir or Path(link.link_dir)
output: ArchiveOutput = get_output_path()
2019-04-27 21:26:24 +00:00
cmd = [
str(CHROME_BIN.abspath),
*CHROME_CONFIG.chrome_args(),
2019-04-27 21:26:24 +00:00
'--screenshot',
link.url,
]
status = 'succeeded'
timer = TimedProgress(timeout, prefix=' ')
try:
result = run(cmd, cwd=str(out_dir), timeout=timeout, text=True)
2019-04-27 21:26:24 +00:00
if result.returncode:
hints = (result.stderr or result.stdout)
2019-04-27 21:26:24 +00:00
raise ArchiveError('Failed to save screenshot', hints)
2020-09-15 19:05:48 +00:00
chmod_file(output, cwd=str(out_dir))
2019-04-27 21:26:24 +00:00
except Exception as err:
status = 'failed'
output = err
CHROME_BINARY.chrome_cleanup_lockfile()
2019-04-27 21:26:24 +00:00
finally:
timer.end()
return ArchiveResult(
cmd=cmd,
2020-09-15 19:05:48 +00:00
pwd=str(out_dir),
cmd_version=str(CHROME_BIN.version),
2019-04-27 21:26:24 +00:00
output=output,
status=status,
**timer.stats,
)