2019-04-27 21:26:24 +00:00
|
|
|
__package__ = 'archivebox.extractors'
|
|
|
|
|
2019-05-01 03:13:04 +00:00
|
|
|
import re
|
2020-09-15 19:05:48 +00:00
|
|
|
from pathlib import Path
|
2019-04-27 21:26:24 +00:00
|
|
|
|
|
|
|
from typing import Optional
|
2021-04-10 08:19:30 +00:00
|
|
|
from datetime import datetime, timezone
|
2019-04-27 21:26:24 +00:00
|
|
|
|
2019-05-01 03:13:04 +00:00
|
|
|
from ..index.schema import Link, ArchiveResult, ArchiveOutput, ArchiveError
|
2020-06-30 09:55:34 +00:00
|
|
|
from ..system import run, chmod_file
|
2019-04-27 21:26:24 +00:00
|
|
|
from ..util import (
|
|
|
|
enforce_types,
|
2019-05-01 03:13:04 +00:00
|
|
|
without_fragment,
|
|
|
|
without_query,
|
|
|
|
path,
|
|
|
|
domain,
|
|
|
|
urldecode,
|
2024-02-21 21:13:06 +00:00
|
|
|
dedupe,
|
2019-04-27 21:26:24 +00:00
|
|
|
)
|
|
|
|
from ..config import (
|
2020-10-15 13:31:49 +00:00
|
|
|
WGET_ARGS,
|
2024-02-21 21:13:06 +00:00
|
|
|
WGET_EXTRA_ARGS,
|
2019-04-27 21:26:24 +00:00
|
|
|
TIMEOUT,
|
|
|
|
SAVE_WGET,
|
|
|
|
SAVE_WARC,
|
|
|
|
WGET_BINARY,
|
|
|
|
WGET_VERSION,
|
2020-06-26 01:30:29 +00:00
|
|
|
RESTRICT_FILE_NAMES,
|
2019-04-27 21:26:24 +00:00
|
|
|
CHECK_SSL_VALIDITY,
|
|
|
|
SAVE_WGET_REQUISITES,
|
|
|
|
WGET_AUTO_COMPRESSION,
|
|
|
|
WGET_USER_AGENT,
|
|
|
|
COOKIES_FILE,
|
|
|
|
)
|
2020-07-22 16:02:13 +00:00
|
|
|
from ..logging_util import TimedProgress
|
2019-04-27 21:26:24 +00:00
|
|
|
|
|
|
|
|
2024-05-12 05:28:59 +00:00
|
|
|
def get_output_path():
|
|
|
|
# TODO: actually save output into this folder, instead of do {domain}/**/index.html
|
|
|
|
return 'wget/'
|
|
|
|
|
|
|
|
def get_embed_path(archiveresult=None):
|
|
|
|
if not archiveresult:
|
|
|
|
return get_output_path()
|
|
|
|
|
|
|
|
link = archiveresult.snapshot.as_link()
|
|
|
|
return wget_output_path(link)
|
|
|
|
|
|
|
|
|
2019-04-27 21:26:24 +00:00
|
|
|
@enforce_types
|
2021-01-21 21:45:11 +00:00
|
|
|
def should_save_wget(link: Link, out_dir: Optional[Path]=None, overwrite: Optional[bool]=False) -> bool:
|
2019-04-27 21:26:24 +00:00
|
|
|
output_path = wget_output_path(link)
|
2020-09-15 19:05:48 +00:00
|
|
|
out_dir = out_dir or Path(link.link_dir)
|
2021-01-21 21:45:11 +00:00
|
|
|
if not overwrite and output_path and (out_dir / output_path).exists():
|
2019-04-27 21:26:24 +00:00
|
|
|
return False
|
|
|
|
|
|
|
|
return SAVE_WGET
|
|
|
|
|
|
|
|
|
|
|
|
@enforce_types
|
2020-09-15 19:05:48 +00:00
|
|
|
def save_wget(link: Link, out_dir: Optional[Path]=None, timeout: int=TIMEOUT) -> ArchiveResult:
|
2019-04-27 21:26:24 +00:00
|
|
|
"""download full site using wget"""
|
|
|
|
|
|
|
|
out_dir = out_dir or link.link_dir
|
|
|
|
if SAVE_WARC:
|
2020-09-15 19:05:48 +00:00
|
|
|
warc_dir = out_dir / "warc"
|
|
|
|
warc_dir.mkdir(exist_ok=True)
|
2021-04-10 08:19:30 +00:00
|
|
|
warc_path = warc_dir / str(int(datetime.now(timezone.utc).timestamp()))
|
2019-04-27 21:26:24 +00:00
|
|
|
|
|
|
|
# WGET CLI Docs: https://www.gnu.org/software/wget/manual/wget.html
|
|
|
|
output: ArchiveOutput = None
|
2024-03-01 20:50:32 +00:00
|
|
|
# later options take precedence
|
2024-02-21 21:13:06 +00:00
|
|
|
options = [
|
2024-03-01 20:50:32 +00:00
|
|
|
*WGET_ARGS,
|
|
|
|
*WGET_EXTRA_ARGS,
|
2019-04-27 21:26:24 +00:00
|
|
|
'--timeout={}'.format(timeout),
|
2020-06-26 01:30:29 +00:00
|
|
|
*(['--restrict-file-names={}'.format(RESTRICT_FILE_NAMES)] if RESTRICT_FILE_NAMES else []),
|
2020-09-15 19:05:48 +00:00
|
|
|
*(['--warc-file={}'.format(str(warc_path))] if SAVE_WARC else []),
|
2019-04-27 21:26:24 +00:00
|
|
|
*(['--page-requisites'] if SAVE_WGET_REQUISITES else []),
|
|
|
|
*(['--user-agent={}'.format(WGET_USER_AGENT)] if WGET_USER_AGENT else []),
|
2021-01-21 00:13:53 +00:00
|
|
|
*(['--load-cookies', str(COOKIES_FILE)] if COOKIES_FILE else []),
|
2019-04-27 21:26:24 +00:00
|
|
|
*(['--compression=auto'] if WGET_AUTO_COMPRESSION else []),
|
2020-06-26 01:30:29 +00:00
|
|
|
*([] if SAVE_WARC else ['--timestamping']),
|
2019-04-27 21:26:24 +00:00
|
|
|
*([] if CHECK_SSL_VALIDITY else ['--no-check-certificate', '--no-hsts']),
|
2024-02-21 21:13:06 +00:00
|
|
|
# '--server-response', # print headers for better error parsing
|
|
|
|
]
|
|
|
|
cmd = [
|
|
|
|
WGET_BINARY,
|
2024-03-06 03:13:45 +00:00
|
|
|
*dedupe(options),
|
2019-04-27 21:26:24 +00:00
|
|
|
link.url,
|
|
|
|
]
|
2020-06-30 06:04:16 +00:00
|
|
|
|
2019-04-27 21:26:24 +00:00
|
|
|
status = 'succeeded'
|
|
|
|
timer = TimedProgress(timeout, prefix=' ')
|
|
|
|
try:
|
2020-09-15 19:05:48 +00:00
|
|
|
result = run(cmd, cwd=str(out_dir), timeout=timeout)
|
2019-04-27 21:26:24 +00:00
|
|
|
output = wget_output_path(link)
|
|
|
|
|
|
|
|
# parse out number of files downloaded from last line of stderr:
|
|
|
|
# "Downloaded: 76 files, 4.0M in 1.6s (2.52 MB/s)"
|
|
|
|
output_tail = [
|
|
|
|
line.strip()
|
|
|
|
for line in (result.stdout + result.stderr).decode().rsplit('\n', 3)[-3:]
|
|
|
|
if line.strip()
|
|
|
|
]
|
|
|
|
files_downloaded = (
|
|
|
|
int(output_tail[-1].strip().split(' ', 2)[1] or 0)
|
|
|
|
if 'Downloaded:' in output_tail[-1]
|
|
|
|
else 0
|
|
|
|
)
|
2020-07-22 05:46:38 +00:00
|
|
|
hints = (
|
|
|
|
'Got wget response code: {}.'.format(result.returncode),
|
|
|
|
*output_tail,
|
|
|
|
)
|
2019-04-27 21:26:24 +00:00
|
|
|
|
|
|
|
# Check for common failure cases
|
2020-07-22 05:46:38 +00:00
|
|
|
if (result.returncode > 0 and files_downloaded < 1) or output is None:
|
2019-04-27 21:26:24 +00:00
|
|
|
if b'403: Forbidden' in result.stderr:
|
|
|
|
raise ArchiveError('403 Forbidden (try changing WGET_USER_AGENT)', hints)
|
|
|
|
if b'404: Not Found' in result.stderr:
|
|
|
|
raise ArchiveError('404 Not Found', hints)
|
|
|
|
if b'ERROR 500: Internal Server Error' in result.stderr:
|
|
|
|
raise ArchiveError('500 Internal Server Error', hints)
|
2020-07-22 05:46:38 +00:00
|
|
|
raise ArchiveError('Wget failed or got an error from the server', hints)
|
2021-01-31 03:02:11 +00:00
|
|
|
|
|
|
|
if (out_dir / output).exists():
|
|
|
|
chmod_file(output, cwd=str(out_dir))
|
|
|
|
else:
|
|
|
|
print(f' {out_dir}/{output}')
|
|
|
|
raise ArchiveError('Failed to find wget output after running', hints)
|
2019-04-27 21:26:24 +00:00
|
|
|
except Exception as err:
|
|
|
|
status = 'failed'
|
|
|
|
output = err
|
|
|
|
finally:
|
|
|
|
timer.end()
|
|
|
|
|
|
|
|
return ArchiveResult(
|
|
|
|
cmd=cmd,
|
2020-09-15 19:05:48 +00:00
|
|
|
pwd=str(out_dir),
|
2019-04-27 21:26:24 +00:00
|
|
|
cmd_version=WGET_VERSION,
|
|
|
|
output=output,
|
|
|
|
status=status,
|
|
|
|
**timer.stats,
|
|
|
|
)
|
2019-05-01 03:13:04 +00:00
|
|
|
|
|
|
|
|
|
|
|
@enforce_types
|
2024-05-07 12:03:23 +00:00
|
|
|
def unsafe_wget_output_path(link: Link) -> Optional[str]:
|
|
|
|
# There used to be a bunch of complex reverse-engineering path mapping logic here,
|
|
|
|
# but it was removed in favor of just walking through the output folder recursively to try to find the
|
|
|
|
# html file that wget produced. It's *much much much* slower than deriving it statically, and is currently
|
|
|
|
# one of the main bottlenecks of ArchiveBox's performance (the output data is often on a slow HDD or network mount).
|
|
|
|
# But it's STILL better than trying to figure out URL -> html filepath mappings ourselves from first principles.
|
2019-05-01 03:13:04 +00:00
|
|
|
full_path = without_fragment(without_query(path(link.url))).strip('/')
|
2020-09-15 19:05:48 +00:00
|
|
|
search_dir = Path(link.link_dir) / domain(link.url).replace(":", "+") / urldecode(full_path)
|
2019-05-01 03:13:04 +00:00
|
|
|
for _ in range(4):
|
2024-05-07 11:12:07 +00:00
|
|
|
try:
|
|
|
|
if search_dir.exists():
|
|
|
|
if search_dir.is_dir():
|
|
|
|
html_files = [
|
|
|
|
f for f in search_dir.iterdir()
|
|
|
|
if re.search(".+\\.[Ss]?[Hh][Tt][Mm][Ll]?$", str(f), re.I | re.M)
|
|
|
|
]
|
|
|
|
if html_files:
|
|
|
|
return str(html_files[0].relative_to(link.link_dir))
|
|
|
|
|
|
|
|
# sometimes wget'd URLs have no ext and return non-html
|
|
|
|
# e.g. /some/example/rss/all -> some RSS XML content)
|
|
|
|
# /some/other/url.o4g -> some binary unrecognized ext)
|
|
|
|
# test this with archivebox add --depth=1 https://getpocket.com/users/nikisweeting/feed/all
|
|
|
|
last_part_of_url = urldecode(full_path.rsplit('/', 1)[-1])
|
|
|
|
for file_present in search_dir.iterdir():
|
|
|
|
if file_present == last_part_of_url:
|
|
|
|
return str((search_dir / file_present).relative_to(link.link_dir))
|
|
|
|
except OSError:
|
|
|
|
# OSError 36 and others can happen here, caused by trying to check for impossible paths
|
|
|
|
# (paths derived from URLs can often contain illegal unicode characters or be too long,
|
|
|
|
# causing the OS / filesystem to reject trying to open them with a system-level error)
|
|
|
|
pass
|
2021-01-22 19:06:01 +00:00
|
|
|
|
2019-05-01 03:13:04 +00:00
|
|
|
# Move up one directory level
|
2020-09-15 19:05:48 +00:00
|
|
|
search_dir = search_dir.parent
|
2019-05-01 03:13:04 +00:00
|
|
|
|
2020-09-15 19:05:48 +00:00
|
|
|
if str(search_dir) == link.link_dir:
|
2019-05-01 03:13:04 +00:00
|
|
|
break
|
2021-01-22 19:06:01 +00:00
|
|
|
|
2021-02-01 07:22:02 +00:00
|
|
|
# check for literally any file present that isnt an empty folder
|
2021-01-31 03:02:39 +00:00
|
|
|
domain_dir = Path(domain(link.url).replace(":", "+"))
|
2024-05-07 12:38:29 +00:00
|
|
|
files_within = [path for path in (Path(link.link_dir) / domain_dir).glob('**/*.*') if not str(path).endswith('.orig')]
|
2021-01-31 03:02:39 +00:00
|
|
|
if files_within:
|
|
|
|
return str((domain_dir / files_within[-1]).relative_to(link.link_dir))
|
2024-05-07 12:03:23 +00:00
|
|
|
|
|
|
|
# abandon all hope, wget either never downloaded, or it produced an output path so horribly mutilated
|
|
|
|
# that it's better we just pretend it doesnt exist
|
|
|
|
# this is why ArchiveBox's specializes in REDUNDANTLY saving copies of sites with multiple different tools
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
@enforce_types
|
2024-08-27 03:16:43 +00:00
|
|
|
def wget_output_path(link: Link, nocache: bool=False) -> Optional[str]:
|
2024-05-07 12:03:23 +00:00
|
|
|
"""calculate the path to the wgetted .html file, since wget may
|
|
|
|
adjust some paths to be different than the base_url path.
|
|
|
|
|
|
|
|
See docs on: wget --adjust-extension (-E), --restrict-file-names=windows|unix|ascii, --convert-links
|
|
|
|
|
|
|
|
WARNING: this function is extremely error prone because mapping URLs to filesystem paths deterministically
|
|
|
|
is basically impossible. Every OS and filesystem have different requirements on what special characters are
|
|
|
|
allowed, and URLs are *full* of all kinds of special characters, illegal unicode, and generally unsafe strings
|
|
|
|
that you dont want anywhere near your filesystem. Also URLs can be obscenely long, but most filesystems dont
|
|
|
|
accept paths longer than 250 characters. On top of all that, this function only exists to try to reverse engineer
|
|
|
|
wget's approach to solving this problem, so this is a shittier, less tested version of their already insanely
|
|
|
|
complicated attempt to do this. Here be dragons:
|
|
|
|
- https://github.com/ArchiveBox/ArchiveBox/issues/549
|
|
|
|
- https://github.com/ArchiveBox/ArchiveBox/issues/1373
|
|
|
|
- https://stackoverflow.com/questions/9532499/check-whether-a-path-is-valid-in-python-without-creating-a-file-at-the-paths-ta
|
|
|
|
- and probably many more that I didn't realize were caused by this...
|
|
|
|
|
|
|
|
The only constructive thing we could possibly do to this function is to figure out how to remove it.
|
|
|
|
|
|
|
|
Preach loudly to anyone who will listen: never attempt to map URLs to filesystem paths,
|
|
|
|
and pray you never have to deal with the aftermath of someone else's attempt to do so...
|
|
|
|
"""
|
|
|
|
|
|
|
|
# Wget downloads can save in a number of different ways depending on the url:
|
|
|
|
# https://example.com
|
|
|
|
# > example.com/index.html
|
|
|
|
# https://example.com?v=zzVa_tX1OiI
|
|
|
|
# > example.com/index.html@v=zzVa_tX1OiI.html
|
|
|
|
# https://www.example.com/?v=zzVa_tX1OiI
|
|
|
|
# > example.com/index.html@v=zzVa_tX1OiI.html
|
|
|
|
|
|
|
|
# https://example.com/abc
|
|
|
|
# > example.com/abc.html
|
|
|
|
# https://example.com/abc/
|
|
|
|
# > example.com/abc/index.html
|
|
|
|
# https://example.com/abc?v=zzVa_tX1OiI.html
|
|
|
|
# > example.com/abc@v=zzVa_tX1OiI.html
|
|
|
|
# https://example.com/abc/?v=zzVa_tX1OiI.html
|
|
|
|
# > example.com/abc/index.html@v=zzVa_tX1OiI.html
|
|
|
|
|
|
|
|
# https://example.com/abc/test.html
|
|
|
|
# > example.com/abc/test.html
|
|
|
|
# https://example.com/abc/test?v=zzVa_tX1OiI
|
|
|
|
# > example.com/abc/test@v=zzVa_tX1OiI.html
|
|
|
|
# https://example.com/abc/test/?v=zzVa_tX1OiI
|
|
|
|
# > example.com/abc/test/index.html@v=zzVa_tX1OiI.html
|
|
|
|
|
2024-09-05 06:42:36 +00:00
|
|
|
cache_key = f'{link.url_hash}:{link.timestamp}-{link.downloaded_at and link.downloaded_at.timestamp()}-wget-output-path'
|
2024-08-27 03:16:43 +00:00
|
|
|
|
|
|
|
if not nocache:
|
|
|
|
from django.core.cache import cache
|
|
|
|
cached_result = cache.get(cache_key)
|
|
|
|
if cached_result:
|
|
|
|
return cached_result
|
|
|
|
|
|
|
|
|
2024-05-07 12:03:23 +00:00
|
|
|
# There's also lots of complexity around how the urlencoding and renaming
|
|
|
|
# is done for pages with query and hash fragments, extensions like shtml / htm / php / etc,
|
|
|
|
# unicode escape sequences, punycode domain names, unicode double-width characters, extensions longer than
|
|
|
|
# 4 characters, paths with multipe extensions, etc. the list goes on...
|
|
|
|
|
|
|
|
output_path = None
|
|
|
|
try:
|
|
|
|
output_path = unsafe_wget_output_path(link)
|
|
|
|
except Exception as err:
|
|
|
|
pass # better to pretend it just failed to download than expose gnarly OSErrors to users
|
|
|
|
|
|
|
|
# check for unprintable unicode characters
|
|
|
|
# https://github.com/ArchiveBox/ArchiveBox/issues/1373
|
|
|
|
if output_path:
|
|
|
|
safe_path = output_path.encode('utf-8', 'replace').decode()
|
|
|
|
if output_path != safe_path:
|
|
|
|
# contains unprintable unicode characters that will break other parts of archivebox
|
|
|
|
# better to pretend it doesnt exist and fallback to parent dir than crash archivebox
|
|
|
|
output_path = None
|
|
|
|
|
|
|
|
# check for a path that is just too long to safely handle across different OS's
|
|
|
|
# https://github.com/ArchiveBox/ArchiveBox/issues/549
|
|
|
|
if output_path and len(output_path) > 250:
|
|
|
|
output_path = None
|
|
|
|
|
2024-05-07 12:38:29 +00:00
|
|
|
if output_path:
|
2024-08-27 03:16:43 +00:00
|
|
|
if not nocache:
|
|
|
|
cache.set(cache_key, output_path)
|
2024-05-07 12:38:29 +00:00
|
|
|
return output_path
|
2024-05-07 12:03:23 +00:00
|
|
|
|
2021-01-31 03:02:39 +00:00
|
|
|
# fallback to just the domain dir
|
|
|
|
search_dir = Path(link.link_dir) / domain(link.url).replace(":", "+")
|
|
|
|
if search_dir.is_dir():
|
|
|
|
return domain(link.url).replace(":", "+")
|
2019-05-01 03:13:04 +00:00
|
|
|
|
2024-01-19 11:34:07 +00:00
|
|
|
# fallback to just the domain dir without port
|
|
|
|
search_dir = Path(link.link_dir) / domain(link.url).split(":", 1)[0]
|
|
|
|
if search_dir.is_dir():
|
|
|
|
return domain(link.url).split(":", 1)[0]
|
|
|
|
|
2019-05-01 03:13:04 +00:00
|
|
|
return None
|