1
0
Fork 0
mirror of synced 2024-06-26 10:00:19 +12:00
ArchiveBox/archivebox/extractors/headers.py

77 lines
1.9 KiB
Python
Raw Normal View History

2020-09-12 02:06:52 +12:00
__package__ = 'archivebox.extractors'
from pathlib import Path
from typing import Optional
2020-09-15 04:22:35 +12:00
from ..index.schema import Link, ArchiveResult, ArchiveOutput
from ..system import atomic_write
2020-09-12 02:06:52 +12:00
from ..util import (
enforce_types,
get_headers,
dedupe,
2020-09-12 02:06:52 +12:00
)
from ..config import (
TIMEOUT,
CURL_BINARY,
CURL_ARGS,
CURL_EXTRA_ARGS,
2020-09-12 02:06:52 +12:00
CURL_USER_AGENT,
CURL_VERSION,
CHECK_SSL_VALIDITY,
2020-09-25 01:37:27 +12:00
SAVE_HEADERS
2020-09-12 02:06:52 +12:00
)
from ..logging_util import TimedProgress
@enforce_types
def should_save_headers(link: Link, out_dir: Optional[str]=None, overwrite: Optional[bool]=False) -> bool:
out_dir = out_dir or Path(link.link_dir)
if not overwrite and (out_dir / 'headers.json').exists():
return False
2020-09-12 02:06:52 +12:00
return SAVE_HEADERS
2020-09-12 02:06:52 +12: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=' ')
2024-03-02 09:50:32 +13:00
# later options take precedence
options = [
2024-03-02 09:50:32 +13:00
*CURL_ARGS,
*CURL_EXTRA_ARGS,
'--head',
2020-09-12 07:28:04 +12:00
'--max-time', str(timeout),
2020-09-12 02:06:52 +12:00
*(['--user-agent', '{}'.format(CURL_USER_AGENT)] if CURL_USER_AGENT else []),
*([] if CHECK_SSL_VALIDITY else ['--insecure']),
]
cmd = [
CURL_BINARY,
*dedupe(options),
2020-09-12 02:06:52 +12:00
link.url,
]
try:
2020-11-01 00:55:27 +13:00
json_headers = get_headers(link.url, timeout=timeout)
2020-09-12 02:06:52 +12:00
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,
)