2020-09-11 14:06:52 +00:00
|
|
|
__package__ = 'archivebox.extractors'
|
|
|
|
|
|
|
|
from pathlib import Path
|
|
|
|
|
|
|
|
from typing import Optional
|
|
|
|
|
2020-09-14 16:22:35 +00:00
|
|
|
from ..index.schema import Link, ArchiveResult, ArchiveOutput
|
|
|
|
from ..system import atomic_write
|
2020-09-11 14:06:52 +00:00
|
|
|
from ..util import (
|
|
|
|
enforce_types,
|
|
|
|
get_headers,
|
|
|
|
)
|
|
|
|
from ..config import (
|
|
|
|
TIMEOUT,
|
|
|
|
CURL_BINARY,
|
|
|
|
CURL_USER_AGENT,
|
|
|
|
CURL_VERSION,
|
|
|
|
CHECK_SSL_VALIDITY,
|
2020-09-24 13:37:27 +00:00
|
|
|
SAVE_HEADERS
|
2020-09-11 14:06:52 +00:00
|
|
|
)
|
|
|
|
from ..logging_util import TimedProgress
|
|
|
|
|
|
|
|
@enforce_types
|
|
|
|
def should_save_headers(link: Link, out_dir: Optional[str]=None) -> bool:
|
|
|
|
out_dir = out_dir or link.link_dir
|
|
|
|
|
|
|
|
output = Path(out_dir or link.link_dir) / 'headers.json'
|
2020-09-24 13:37:27 +00:00
|
|
|
return not output.exists() and SAVE_HEADERS
|
2020-09-11 14:06:52 +00:00
|
|
|
|
|
|
|
|
|
|
|
@enforce_types
|
|
|
|
def save_headers(link: Link, out_dir: Optional[str]=None, timeout: int=TIMEOUT) -> ArchiveResult:
|
|
|
|
"""Download site headers"""
|
|
|
|
|
|
|
|
out_dir = Path(out_dir or link.link_dir)
|
|
|
|
output_folder = out_dir.absolute()
|
|
|
|
output: ArchiveOutput = 'headers.json'
|
|
|
|
|
|
|
|
status = 'succeeded'
|
|
|
|
timer = TimedProgress(timeout, prefix=' ')
|
|
|
|
|
|
|
|
cmd = [
|
|
|
|
CURL_BINARY,
|
2020-09-11 19:28:04 +00:00
|
|
|
'--silent',
|
|
|
|
'--max-time', str(timeout),
|
|
|
|
'--location',
|
|
|
|
'--compressed',
|
|
|
|
'--head',
|
2020-09-11 14:06:52 +00:00
|
|
|
*(['--user-agent', '{}'.format(CURL_USER_AGENT)] if CURL_USER_AGENT else []),
|
|
|
|
*([] if CHECK_SSL_VALIDITY else ['--insecure']),
|
|
|
|
link.url,
|
|
|
|
]
|
|
|
|
try:
|
|
|
|
json_headers = get_headers(link.url)
|
|
|
|
|
|
|
|
output_folder.mkdir(exist_ok=True)
|
|
|
|
atomic_write(str(output_folder / "headers.json"), json_headers)
|
|
|
|
|
|
|
|
except (Exception, OSError) as err:
|
|
|
|
status = 'failed'
|
|
|
|
output = err
|
|
|
|
finally:
|
|
|
|
timer.end()
|
|
|
|
|
|
|
|
return ArchiveResult(
|
|
|
|
cmd=cmd,
|
|
|
|
pwd=str(out_dir),
|
|
|
|
cmd_version=CURL_VERSION,
|
|
|
|
output=output,
|
|
|
|
status=status,
|
|
|
|
**timer.stats,
|
|
|
|
)
|