2017-10-18 22:38:17 +00:00
|
|
|
import os
|
2017-10-23 09:58:41 +00:00
|
|
|
import re
|
2017-10-18 22:38:17 +00:00
|
|
|
import sys
|
|
|
|
import time
|
2017-10-23 09:58:41 +00:00
|
|
|
import json
|
2019-01-20 19:07:28 +00:00
|
|
|
import signal
|
2019-02-19 06:45:19 +00:00
|
|
|
from urllib.request import urlopen
|
|
|
|
from urllib.parse import urlparse
|
2017-10-18 22:38:17 +00:00
|
|
|
|
2019-01-11 10:19:07 +00:00
|
|
|
from decimal import Decimal
|
2019-01-09 09:05:19 +00:00
|
|
|
from urllib.parse import quote
|
2017-10-18 22:38:17 +00:00
|
|
|
from datetime import datetime
|
2019-01-20 19:07:28 +00:00
|
|
|
from subprocess import TimeoutExpired, Popen, PIPE, DEVNULL, CompletedProcess, CalledProcessError
|
2017-10-18 22:38:17 +00:00
|
|
|
from multiprocessing import Process
|
|
|
|
|
|
|
|
from config import (
|
2017-10-30 07:50:37 +00:00
|
|
|
IS_TTY,
|
2018-06-11 01:12:55 +00:00
|
|
|
OUTPUT_PERMISSIONS,
|
2018-06-11 00:52:15 +00:00
|
|
|
REPO_DIR,
|
|
|
|
SOURCES_DIR,
|
|
|
|
OUTPUT_DIR,
|
2018-06-11 01:26:11 +00:00
|
|
|
ARCHIVE_DIR,
|
2017-10-18 22:38:17 +00:00
|
|
|
TIMEOUT,
|
|
|
|
TERM_WIDTH,
|
|
|
|
SHOW_PROGRESS,
|
|
|
|
ANSI,
|
|
|
|
CHROME_BINARY,
|
|
|
|
FETCH_WGET,
|
|
|
|
FETCH_PDF,
|
|
|
|
FETCH_SCREENSHOT,
|
2018-06-10 22:45:41 +00:00
|
|
|
FETCH_DOM,
|
2017-10-18 22:38:17 +00:00
|
|
|
FETCH_FAVICON,
|
2019-02-21 17:57:26 +00:00
|
|
|
FETCH_TITLE,
|
2019-01-12 08:13:55 +00:00
|
|
|
FETCH_MEDIA,
|
2017-10-18 22:38:17 +00:00
|
|
|
SUBMIT_ARCHIVE_DOT_ORG,
|
|
|
|
)
|
|
|
|
|
2019-02-19 06:45:19 +00:00
|
|
|
# URL helpers: https://docs.python.org/3/library/urllib.parse.html#url-parsing
|
|
|
|
scheme = lambda url: urlparse(url).scheme
|
|
|
|
without_scheme = lambda url: urlparse(url)._replace(scheme='').geturl().strip('//')
|
|
|
|
without_query = lambda url: urlparse(url)._replace(query='').geturl().strip('//')
|
|
|
|
without_fragment = lambda url: urlparse(url)._replace(fragment='').geturl().strip('//')
|
|
|
|
without_path = lambda url: urlparse(url)._replace(path='', fragment='', query='').geturl().strip('//')
|
|
|
|
path = lambda url: urlparse(url).path
|
|
|
|
basename = lambda url: urlparse(url).path.rsplit('/', 1)[-1]
|
|
|
|
domain = lambda url: urlparse(url).netloc
|
|
|
|
query = lambda url: urlparse(url).query
|
|
|
|
fragment = lambda url: urlparse(url).fragment
|
|
|
|
extension = lambda url: basename(url).rsplit('.', 1)[-1].lower() if '.' in basename(url) else ''
|
2018-04-17 07:54:59 +00:00
|
|
|
base_url = lambda url: without_scheme(url) # uniq base url used to dedupe links
|
2017-10-23 09:58:41 +00:00
|
|
|
|
|
|
|
short_ts = lambda ts: ts.split('.')[0]
|
|
|
|
|
2019-02-05 02:54:02 +00:00
|
|
|
URL_REGEX = 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))[^<\""]+'
|
2019-02-19 06:44:54 +00:00
|
|
|
HTML_TITLE_REGEX = '<title>(.[^<>]+)'
|
2019-01-11 09:09:39 +00:00
|
|
|
|
2017-10-23 09:58:41 +00:00
|
|
|
|
2017-10-18 22:38:17 +00:00
|
|
|
def check_dependencies():
|
|
|
|
"""Check that all necessary dependencies are installed, and have valid versions"""
|
|
|
|
|
|
|
|
python_vers = float('{}.{}'.format(sys.version_info.major, sys.version_info.minor))
|
|
|
|
if python_vers < 3.5:
|
|
|
|
print('{}[X] Python version is not new enough: {} (>3.5 is required){}'.format(ANSI['red'], python_vers, ANSI['reset']))
|
2018-12-20 13:13:50 +00:00
|
|
|
print(' See https://github.com/pirate/ArchiveBox#troubleshooting for help upgrading your Python installation.')
|
2017-10-18 22:38:17 +00:00
|
|
|
raise SystemExit(1)
|
|
|
|
|
2018-06-10 22:45:41 +00:00
|
|
|
if FETCH_PDF or FETCH_SCREENSHOT or FETCH_DOM:
|
2018-04-17 11:30:06 +00:00
|
|
|
if run(['which', CHROME_BINARY], stdout=DEVNULL).returncode:
|
2017-10-18 22:38:17 +00:00
|
|
|
print('{}[X] Missing dependency: {}{}'.format(ANSI['red'], CHROME_BINARY, ANSI['reset']))
|
|
|
|
print(' Run ./setup.sh, then confirm it was installed with: {} --version'.format(CHROME_BINARY))
|
2018-12-20 13:13:50 +00:00
|
|
|
print(' See https://github.com/pirate/ArchiveBox for help.')
|
2017-10-18 22:38:17 +00:00
|
|
|
raise SystemExit(1)
|
|
|
|
|
|
|
|
# parse chrome --version e.g. Google Chrome 61.0.3114.0 canary / Chromium 59.0.3029.110 built on Ubuntu, running on Ubuntu 16.04
|
|
|
|
try:
|
|
|
|
result = run([CHROME_BINARY, '--version'], stdout=PIPE)
|
2017-11-28 01:40:24 +00:00
|
|
|
version_str = result.stdout.decode('utf-8')
|
|
|
|
version_lines = re.sub("(Google Chrome|Chromium) (\\d+?)\\.(\\d+?)\\.(\\d+?).*?$", "\\2", version_str).split('\n')
|
|
|
|
version = [l for l in version_lines if l.isdigit()][-1]
|
2017-10-18 22:38:17 +00:00
|
|
|
if int(version) < 59:
|
2017-11-28 01:40:24 +00:00
|
|
|
print(version_lines)
|
2018-06-10 22:45:41 +00:00
|
|
|
print('{red}[X] Chrome version must be 59 or greater for headless PDF, screenshot, and DOM saving{reset}'.format(**ANSI))
|
2018-12-20 13:13:50 +00:00
|
|
|
print(' See https://github.com/pirate/ArchiveBox for help.')
|
2017-10-18 22:38:17 +00:00
|
|
|
raise SystemExit(1)
|
2017-11-28 01:40:24 +00:00
|
|
|
except (IndexError, TypeError, OSError):
|
2017-10-18 22:38:17 +00:00
|
|
|
print('{red}[X] Failed to parse Chrome version, is it installed properly?{reset}'.format(**ANSI))
|
|
|
|
print(' Run ./setup.sh, then confirm it was installed with: {} --version'.format(CHROME_BINARY))
|
2018-12-20 13:13:50 +00:00
|
|
|
print(' See https://github.com/pirate/ArchiveBox for help.')
|
2017-10-18 22:38:17 +00:00
|
|
|
raise SystemExit(1)
|
|
|
|
|
|
|
|
if FETCH_WGET:
|
2018-04-17 11:30:06 +00:00
|
|
|
if run(['which', 'wget'], stdout=DEVNULL).returncode or run(['wget', '--version'], stdout=DEVNULL).returncode:
|
2017-10-18 22:38:17 +00:00
|
|
|
print('{red}[X] Missing dependency: wget{reset}'.format(**ANSI))
|
|
|
|
print(' Run ./setup.sh, then confirm it was installed with: {} --version'.format('wget'))
|
2018-12-20 13:13:50 +00:00
|
|
|
print(' See https://github.com/pirate/ArchiveBox for help.')
|
2017-10-18 22:38:17 +00:00
|
|
|
raise SystemExit(1)
|
|
|
|
|
|
|
|
if FETCH_FAVICON or SUBMIT_ARCHIVE_DOT_ORG:
|
2018-04-17 11:30:06 +00:00
|
|
|
if run(['which', 'curl'], stdout=DEVNULL).returncode or run(['curl', '--version'], stdout=DEVNULL).returncode:
|
2017-10-18 22:38:17 +00:00
|
|
|
print('{red}[X] Missing dependency: curl{reset}'.format(**ANSI))
|
|
|
|
print(' Run ./setup.sh, then confirm it was installed with: {} --version'.format('curl'))
|
2018-12-20 13:13:50 +00:00
|
|
|
print(' See https://github.com/pirate/ArchiveBox for help.')
|
2017-10-18 22:38:17 +00:00
|
|
|
raise SystemExit(1)
|
|
|
|
|
2019-01-12 08:13:55 +00:00
|
|
|
if FETCH_MEDIA:
|
2018-04-17 11:30:06 +00:00
|
|
|
if run(['which', 'youtube-dl'], stdout=DEVNULL).returncode or run(['youtube-dl', '--version'], stdout=DEVNULL).returncode:
|
2017-10-18 22:38:17 +00:00
|
|
|
print('{red}[X] Missing dependency: youtube-dl{reset}'.format(**ANSI))
|
|
|
|
print(' Run ./setup.sh, then confirm it was installed with: {} --version'.format('youtube-dl'))
|
2018-12-20 13:13:50 +00:00
|
|
|
print(' See https://github.com/pirate/ArchiveBox for help.')
|
2017-10-18 22:38:17 +00:00
|
|
|
raise SystemExit(1)
|
|
|
|
|
|
|
|
|
2018-06-11 01:12:55 +00:00
|
|
|
def chmod_file(path, cwd='.', permissions=OUTPUT_PERMISSIONS, timeout=30):
|
2017-10-18 22:38:17 +00:00
|
|
|
"""chmod -R <permissions> <cwd>/<path>"""
|
|
|
|
|
|
|
|
if not os.path.exists(os.path.join(cwd, path)):
|
|
|
|
raise Exception('Failed to chmod: {} does not exist (did the previous step fail?)'.format(path))
|
|
|
|
|
|
|
|
chmod_result = run(['chmod', '-R', permissions, path], cwd=cwd, stdout=DEVNULL, stderr=PIPE, timeout=timeout)
|
|
|
|
if chmod_result.returncode == 1:
|
|
|
|
print(' ', chmod_result.stderr.decode())
|
|
|
|
raise Exception('Failed to chmod {}/{}'.format(cwd, path))
|
|
|
|
|
|
|
|
|
|
|
|
def progress(seconds=TIMEOUT, prefix=''):
|
|
|
|
"""Show a (subprocess-controlled) progress bar with a <seconds> timeout,
|
|
|
|
returns end() function to instantly finish the progress
|
|
|
|
"""
|
|
|
|
|
|
|
|
if not SHOW_PROGRESS:
|
|
|
|
return lambda: None
|
|
|
|
|
2019-01-20 17:34:15 +00:00
|
|
|
def progress_bar(seconds, prefix):
|
2017-10-18 22:38:17 +00:00
|
|
|
"""show timer in the form of progress bar, with percentage and seconds remaining"""
|
2019-02-05 04:41:35 +00:00
|
|
|
chunk = '█' if sys.stdout.encoding == 'UTF-8' else '#'
|
|
|
|
chunks = TERM_WIDTH - len(prefix) - 20 # number of progress chunks to show (aka max bar width)
|
2017-10-18 22:38:17 +00:00
|
|
|
try:
|
|
|
|
for s in range(seconds * chunks):
|
|
|
|
progress = s / chunks / seconds * 100
|
|
|
|
bar_width = round(progress/(100/chunks))
|
|
|
|
|
|
|
|
# ████████████████████ 0.9% (1/60sec)
|
|
|
|
sys.stdout.write('\r{0}{1}{2}{3} {4}% ({5}/{6}sec)'.format(
|
|
|
|
prefix,
|
|
|
|
ANSI['green'],
|
|
|
|
(chunk * bar_width).ljust(chunks),
|
|
|
|
ANSI['reset'],
|
|
|
|
round(progress, 1),
|
|
|
|
round(s/chunks),
|
|
|
|
seconds,
|
|
|
|
))
|
|
|
|
sys.stdout.flush()
|
|
|
|
time.sleep(1 / chunks)
|
|
|
|
|
|
|
|
# ██████████████████████████████████ 100.0% (60/60sec)
|
|
|
|
sys.stdout.write('\r{0}{1}{2}{3} {4}% ({5}/{6}sec)\n'.format(
|
|
|
|
prefix,
|
|
|
|
ANSI['red'],
|
|
|
|
chunk * chunks,
|
|
|
|
ANSI['reset'],
|
|
|
|
100.0,
|
|
|
|
seconds,
|
|
|
|
seconds,
|
|
|
|
))
|
|
|
|
sys.stdout.flush()
|
|
|
|
except KeyboardInterrupt:
|
|
|
|
print()
|
|
|
|
pass
|
|
|
|
|
2019-01-20 17:34:25 +00:00
|
|
|
p = Process(target=progress_bar, args=(seconds, prefix))
|
2017-10-18 22:38:17 +00:00
|
|
|
p.start()
|
|
|
|
|
2019-02-05 04:45:36 +00:00
|
|
|
def end():
|
2017-10-18 22:38:17 +00:00
|
|
|
"""immediately finish progress and clear the progressbar line"""
|
2019-01-20 17:34:25 +00:00
|
|
|
|
|
|
|
# protect from double termination
|
2019-02-05 04:45:36 +00:00
|
|
|
#if p is None or not hasattr(p, 'kill'):
|
|
|
|
# return
|
|
|
|
nonlocal p
|
|
|
|
if p is not None:
|
|
|
|
p.terminate()
|
2018-11-26 02:29:56 +00:00
|
|
|
p = None
|
|
|
|
|
2017-10-18 22:38:17 +00:00
|
|
|
sys.stdout.write('\r{}{}\r'.format((' ' * TERM_WIDTH), ANSI['reset'])) # clear whole terminal line
|
|
|
|
sys.stdout.flush()
|
|
|
|
|
|
|
|
return end
|
|
|
|
|
2018-06-11 00:52:15 +00:00
|
|
|
def pretty_path(path):
|
2019-01-01 01:53:01 +00:00
|
|
|
"""convert paths like .../ArchiveBox/archivebox/../output/abc into output/abc"""
|
2018-06-11 01:12:55 +00:00
|
|
|
return path.replace(REPO_DIR + '/', '')
|
2018-06-11 00:52:15 +00:00
|
|
|
|
2017-10-18 22:38:17 +00:00
|
|
|
|
2019-01-14 23:11:48 +00:00
|
|
|
def save_source(raw_text):
|
|
|
|
if not os.path.exists(SOURCES_DIR):
|
|
|
|
os.makedirs(SOURCES_DIR)
|
|
|
|
|
|
|
|
ts = str(datetime.now().timestamp()).split('.', 1)[0]
|
|
|
|
|
|
|
|
source_path = os.path.join(SOURCES_DIR, '{}-{}.txt'.format('stdin', ts))
|
|
|
|
|
|
|
|
with open(source_path, 'w', encoding='utf-8') as f:
|
|
|
|
f.write(raw_text)
|
|
|
|
|
|
|
|
return source_path
|
|
|
|
|
|
|
|
|
2017-10-18 22:38:17 +00:00
|
|
|
def download_url(url):
|
2017-10-23 09:58:41 +00:00
|
|
|
"""download a given url's content into downloads/domain.txt"""
|
|
|
|
|
2018-06-11 00:52:15 +00:00
|
|
|
if not os.path.exists(SOURCES_DIR):
|
|
|
|
os.makedirs(SOURCES_DIR)
|
2017-10-23 09:58:41 +00:00
|
|
|
|
2018-06-11 00:52:15 +00:00
|
|
|
ts = str(datetime.now().timestamp()).split('.', 1)[0]
|
|
|
|
|
|
|
|
source_path = os.path.join(SOURCES_DIR, '{}-{}.txt'.format(domain(url), ts))
|
2017-10-18 22:38:17 +00:00
|
|
|
|
|
|
|
print('[*] [{}] Downloading {} > {}'.format(
|
|
|
|
datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
|
|
|
|
url,
|
2018-06-11 00:52:15 +00:00
|
|
|
pretty_path(source_path),
|
2017-10-18 22:38:17 +00:00
|
|
|
))
|
|
|
|
end = progress(TIMEOUT, prefix=' ')
|
|
|
|
try:
|
2019-02-19 06:45:19 +00:00
|
|
|
downloaded_xml = urlopen(url).read().decode('utf-8')
|
2017-10-18 22:38:17 +00:00
|
|
|
end()
|
|
|
|
except Exception as e:
|
|
|
|
end()
|
|
|
|
print('[!] Failed to download {}\n'.format(url))
|
|
|
|
print(' ', e)
|
|
|
|
raise SystemExit(1)
|
|
|
|
|
2018-06-11 00:52:15 +00:00
|
|
|
with open(source_path, 'w', encoding='utf-8') as f:
|
2017-10-18 22:38:17 +00:00
|
|
|
f.write(downloaded_xml)
|
|
|
|
|
2018-06-11 00:52:15 +00:00
|
|
|
return source_path
|
2017-10-18 22:38:17 +00:00
|
|
|
|
2019-01-11 09:09:39 +00:00
|
|
|
|
2019-02-19 06:44:54 +00:00
|
|
|
def fetch_page_title(url, timeout=10, progress=SHOW_PROGRESS):
|
2019-01-11 09:09:39 +00:00
|
|
|
"""Attempt to guess a page's title by downloading the html"""
|
2019-02-21 17:57:26 +00:00
|
|
|
if not FETCH_TITLE:
|
|
|
|
return None
|
|
|
|
|
2019-01-11 09:09:39 +00:00
|
|
|
try:
|
2019-02-19 06:44:54 +00:00
|
|
|
if progress:
|
2019-02-07 06:06:21 +00:00
|
|
|
sys.stdout.write('.')
|
|
|
|
sys.stdout.flush()
|
2019-02-19 06:45:19 +00:00
|
|
|
|
|
|
|
html_content = urlopen(url, timeout=timeout).read().decode('utf-8')
|
|
|
|
match = re.search(HTML_TITLE_REGEX, html_content)
|
|
|
|
return match.group(1).strip() if match else None
|
2019-01-11 09:09:39 +00:00
|
|
|
except Exception:
|
2019-02-19 06:44:54 +00:00
|
|
|
return None
|
2019-01-11 09:09:39 +00:00
|
|
|
|
|
|
|
|
2017-10-23 09:58:41 +00:00
|
|
|
def str_between(string, start, end=None):
|
2017-10-18 22:38:17 +00:00
|
|
|
"""(<abc>12345</def>, <abc>, </def>) -> 12345"""
|
|
|
|
|
|
|
|
content = string.split(start, 1)[-1]
|
|
|
|
if end is not None:
|
|
|
|
content = content.rsplit(end, 1)[0]
|
|
|
|
|
|
|
|
return content
|
|
|
|
|
|
|
|
def get_link_type(link):
|
|
|
|
"""Certain types of links need to be handled specially, this figures out when that's the case"""
|
|
|
|
|
|
|
|
if link['base_url'].endswith('.pdf'):
|
|
|
|
return 'PDF'
|
|
|
|
elif link['base_url'].rsplit('.', 1) in ('pdf', 'png', 'jpg', 'jpeg', 'svg', 'bmp', 'gif', 'tiff', 'webp'):
|
|
|
|
return 'image'
|
|
|
|
elif 'wikipedia.org' in link['domain']:
|
|
|
|
return 'wiki'
|
|
|
|
elif 'youtube.com' in link['domain']:
|
|
|
|
return 'youtube'
|
|
|
|
elif 'soundcloud.com' in link['domain']:
|
|
|
|
return 'soundcloud'
|
|
|
|
elif 'youku.com' in link['domain']:
|
|
|
|
return 'youku'
|
|
|
|
elif 'vimeo.com' in link['domain']:
|
|
|
|
return 'vimeo'
|
|
|
|
return None
|
|
|
|
|
2017-10-30 07:50:37 +00:00
|
|
|
def merge_links(a, b):
|
|
|
|
"""deterministially merge two links, favoring longer field values over shorter,
|
|
|
|
and "cleaner" values over worse ones.
|
|
|
|
"""
|
2019-02-19 06:44:54 +00:00
|
|
|
longer = lambda key: (a[key] if len(a[key]) > len(b[key]) else b[key]) if (a[key] and b[key]) else (a[key] or b[key])
|
2017-10-30 07:50:37 +00:00
|
|
|
earlier = lambda key: a[key] if a[key] < b[key] else b[key]
|
|
|
|
|
|
|
|
url = longer('url')
|
|
|
|
longest_title = longer('title')
|
2019-02-19 06:44:54 +00:00
|
|
|
cleanest_title = a['title'] if '://' not in (a['title'] or '') else b['title']
|
2017-10-30 07:50:37 +00:00
|
|
|
link = {
|
|
|
|
'timestamp': earlier('timestamp'),
|
|
|
|
'url': url,
|
|
|
|
'domain': domain(url),
|
|
|
|
'base_url': base_url(url),
|
|
|
|
'tags': longer('tags'),
|
2019-02-19 06:44:54 +00:00
|
|
|
'title': longest_title if '://' not in (longest_title or '') else cleanest_title,
|
2017-10-30 07:50:37 +00:00
|
|
|
'sources': list(set(a.get('sources', []) + b.get('sources', []))),
|
|
|
|
}
|
|
|
|
link['type'] = get_link_type(link)
|
|
|
|
return link
|
2017-10-18 22:38:17 +00:00
|
|
|
|
2017-10-23 09:58:41 +00:00
|
|
|
def find_link(folder, links):
|
|
|
|
"""for a given archive folder, find the corresponding link object in links"""
|
|
|
|
url = parse_url(folder)
|
|
|
|
if url:
|
|
|
|
for link in links:
|
|
|
|
if (link['base_url'] in url) or (url in link['url']):
|
|
|
|
return link
|
|
|
|
|
|
|
|
timestamp = folder.split('.')[0]
|
|
|
|
for link in links:
|
|
|
|
if link['timestamp'].startswith(timestamp):
|
2018-06-11 01:26:11 +00:00
|
|
|
if link['domain'] in os.listdir(os.path.join(ARCHIVE_DIR, folder)):
|
2017-10-23 09:58:41 +00:00
|
|
|
return link # careful now, this isn't safe for most ppl
|
|
|
|
if link['domain'] in parse_url(folder):
|
|
|
|
return link
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
def parse_url(folder):
|
|
|
|
"""for a given archive folder, figure out what url it's for"""
|
2018-06-11 01:26:11 +00:00
|
|
|
link_json = os.path.join(ARCHIVE_DIR, folder, 'index.json')
|
2017-10-23 09:58:41 +00:00
|
|
|
if os.path.exists(link_json):
|
|
|
|
with open(link_json, 'r') as f:
|
2017-10-30 07:50:37 +00:00
|
|
|
try:
|
|
|
|
link_json = f.read().strip()
|
|
|
|
if link_json:
|
|
|
|
link = json.loads(link_json)
|
|
|
|
return link['base_url']
|
|
|
|
except ValueError:
|
|
|
|
print('File contains invalid JSON: {}!'.format(link_json))
|
2017-10-23 09:58:41 +00:00
|
|
|
|
2018-06-11 01:26:11 +00:00
|
|
|
archive_org_txt = os.path.join(ARCHIVE_DIR, folder, 'archive.org.txt')
|
2017-10-23 09:58:41 +00:00
|
|
|
if os.path.exists(archive_org_txt):
|
|
|
|
with open(archive_org_txt, 'r') as f:
|
|
|
|
original_link = f.read().strip().split('/http', 1)[-1]
|
|
|
|
with_scheme = 'http{}'.format(original_link)
|
|
|
|
return with_scheme
|
|
|
|
|
|
|
|
return ''
|
|
|
|
|
2017-10-30 07:50:37 +00:00
|
|
|
def manually_merge_folders(source, target):
|
|
|
|
"""prompt for user input to resolve a conflict between two archive folders"""
|
|
|
|
|
|
|
|
if not IS_TTY:
|
|
|
|
return
|
|
|
|
|
|
|
|
fname = lambda path: path.split('/')[-1]
|
2017-10-23 09:58:41 +00:00
|
|
|
|
2017-10-30 07:50:37 +00:00
|
|
|
print(' {} and {} have conflicting files, which do you want to keep?'.format(fname(source), fname(target)))
|
|
|
|
print(' - [enter]: do nothing (keep both)')
|
2017-10-30 11:09:33 +00:00
|
|
|
print(' - a: prefer files from {}'.format(source))
|
|
|
|
print(' - b: prefer files from {}'.format(target))
|
2017-10-30 07:50:37 +00:00
|
|
|
print(' - q: quit and resolve the conflict manually')
|
|
|
|
try:
|
|
|
|
answer = input('> ').strip().lower()
|
|
|
|
except KeyboardInterrupt:
|
|
|
|
answer = 'q'
|
|
|
|
|
|
|
|
assert answer in ('', 'a', 'b', 'q'), 'Invalid choice.'
|
|
|
|
|
|
|
|
if answer == 'q':
|
2018-12-20 13:13:50 +00:00
|
|
|
print('\nJust run ArchiveBox again to pick up where you left off.')
|
2017-10-30 07:50:37 +00:00
|
|
|
raise SystemExit(0)
|
|
|
|
elif answer == '':
|
|
|
|
return
|
|
|
|
|
|
|
|
files_in_source = set(os.listdir(source))
|
|
|
|
files_in_target = set(os.listdir(target))
|
2017-10-30 11:09:33 +00:00
|
|
|
for file in files_in_source:
|
2017-10-30 07:50:37 +00:00
|
|
|
if file in files_in_target:
|
|
|
|
to_delete = target if answer == 'a' else source
|
|
|
|
run(['rm', '-Rf', os.path.join(to_delete, file)])
|
|
|
|
run(['mv', os.path.join(source, file), os.path.join(target, file)])
|
|
|
|
|
|
|
|
if not set(os.listdir(source)):
|
|
|
|
run(['rm', '-Rf', source])
|
|
|
|
|
2017-10-30 11:09:33 +00:00
|
|
|
def fix_folder_path(archive_path, link_folder, link):
|
2017-10-23 09:58:41 +00:00
|
|
|
"""given a folder, merge it to the canonical 'correct' path for the given link object"""
|
2017-10-30 11:09:33 +00:00
|
|
|
source = os.path.join(archive_path, link_folder)
|
|
|
|
target = os.path.join(archive_path, link['timestamp'])
|
2017-10-30 07:50:37 +00:00
|
|
|
|
2017-10-30 11:09:33 +00:00
|
|
|
url_in_folder = parse_url(source)
|
|
|
|
if not (url_in_folder in link['base_url']
|
|
|
|
or link['base_url'] in url_in_folder):
|
2017-10-30 07:50:37 +00:00
|
|
|
raise ValueError('The link does not match the url for this folder.')
|
|
|
|
|
|
|
|
if not os.path.exists(target):
|
|
|
|
# target doesn't exist so nothing needs merging, simply move A to B
|
2017-10-30 11:09:33 +00:00
|
|
|
run(['mv', source, target])
|
2017-10-30 07:50:37 +00:00
|
|
|
else:
|
|
|
|
# target folder exists, check for conflicting files and attempt manual merge
|
|
|
|
files_in_source = set(os.listdir(source))
|
|
|
|
files_in_target = set(os.listdir(target))
|
2017-10-30 11:09:33 +00:00
|
|
|
conflicting_files = files_in_source & files_in_target
|
2017-10-30 07:50:37 +00:00
|
|
|
|
2017-10-30 11:09:33 +00:00
|
|
|
if not conflicting_files:
|
2017-10-30 07:50:37 +00:00
|
|
|
for file in files_in_source:
|
|
|
|
run(['mv', os.path.join(source, file), os.path.join(target, file)])
|
|
|
|
|
2017-10-30 07:55:39 +00:00
|
|
|
if os.path.exists(source):
|
|
|
|
files_in_source = set(os.listdir(source))
|
|
|
|
if files_in_source:
|
|
|
|
manually_merge_folders(source, target)
|
|
|
|
else:
|
|
|
|
run(['rm', '-R', source])
|
2017-10-23 09:58:41 +00:00
|
|
|
|
|
|
|
|
2018-06-11 03:01:56 +00:00
|
|
|
def migrate_data():
|
|
|
|
# migrate old folder to new OUTPUT folder
|
|
|
|
old_dir = os.path.join(REPO_DIR, 'html')
|
|
|
|
if os.path.exists(old_dir):
|
|
|
|
print('[!] WARNING: Moved old output folder "html" to new location: {}'.format(OUTPUT_DIR))
|
|
|
|
run(['mv', old_dir, OUTPUT_DIR], timeout=10)
|
|
|
|
|
|
|
|
|
2017-10-30 11:09:33 +00:00
|
|
|
def cleanup_archive(archive_path, links):
|
2017-10-23 09:58:41 +00:00
|
|
|
"""move any incorrectly named folders to their canonical locations"""
|
|
|
|
|
|
|
|
# for each folder that exists, see if we can match it up with a known good link
|
2017-10-30 11:09:33 +00:00
|
|
|
# if we can, then merge the two folders (TODO: if not, move it to lost & found)
|
2017-10-23 09:58:41 +00:00
|
|
|
|
|
|
|
unmatched = []
|
2017-10-30 07:50:37 +00:00
|
|
|
bad_folders = []
|
|
|
|
|
2017-10-30 11:09:33 +00:00
|
|
|
if not os.path.exists(archive_path):
|
2017-10-30 07:50:37 +00:00
|
|
|
return
|
2017-10-23 09:58:41 +00:00
|
|
|
|
2017-10-30 11:09:33 +00:00
|
|
|
for folder in os.listdir(archive_path):
|
|
|
|
try:
|
|
|
|
files = os.listdir(os.path.join(archive_path, folder))
|
|
|
|
except NotADirectoryError:
|
|
|
|
continue
|
|
|
|
|
|
|
|
if files:
|
2017-10-30 07:50:37 +00:00
|
|
|
link = find_link(folder, links)
|
|
|
|
if link is None:
|
|
|
|
unmatched.append(folder)
|
|
|
|
continue
|
|
|
|
|
|
|
|
if folder != link['timestamp']:
|
|
|
|
bad_folders.append((folder, link))
|
2017-10-30 11:09:33 +00:00
|
|
|
else:
|
|
|
|
# delete empty folders
|
|
|
|
run(['rm', '-R', os.path.join(archive_path, folder)])
|
2017-10-30 07:50:37 +00:00
|
|
|
|
2017-10-30 11:09:33 +00:00
|
|
|
if bad_folders and IS_TTY and input('[!] Cleanup archive? y/[n]: ') == 'y':
|
2017-10-30 07:50:37 +00:00
|
|
|
print('[!] Fixing {} improperly named folders in archive...'.format(len(bad_folders)))
|
|
|
|
for folder, link in bad_folders:
|
2017-10-30 11:09:33 +00:00
|
|
|
fix_folder_path(archive_path, folder, link)
|
|
|
|
elif bad_folders:
|
2018-12-20 13:13:50 +00:00
|
|
|
print('[!] Warning! {} folders need to be merged, fix by running ArchiveBox.'.format(len(bad_folders)))
|
2017-10-23 09:58:41 +00:00
|
|
|
|
|
|
|
if unmatched:
|
|
|
|
print('[!] Warning! {} unrecognized folders in html/archive/'.format(len(unmatched)))
|
2017-10-30 08:03:31 +00:00
|
|
|
print(' '+ '\n '.join(unmatched))
|
2017-10-23 09:58:41 +00:00
|
|
|
|
|
|
|
|
2018-04-17 13:13:38 +00:00
|
|
|
def wget_output_path(link, look_in=None):
|
2017-10-23 09:58:41 +00:00
|
|
|
"""calculate the path to the wgetted .html file, since wget may
|
|
|
|
adjust some paths to be different than the base_url path.
|
|
|
|
|
2018-04-17 13:13:38 +00:00
|
|
|
See docs on wget --adjust-extension (-E)
|
2017-10-23 09:58:41 +00:00
|
|
|
"""
|
|
|
|
|
2018-06-11 02:43:01 +00:00
|
|
|
# if we have it stored, always prefer the actual output path to computed one
|
|
|
|
if link.get('latest', {}).get('wget'):
|
|
|
|
return link['latest']['wget']
|
|
|
|
|
2018-04-17 13:44:07 +00:00
|
|
|
urlencode = lambda s: quote(s, encoding='utf-8', errors='replace')
|
|
|
|
|
2017-10-23 09:58:41 +00:00
|
|
|
if link['type'] in ('PDF', 'image'):
|
2018-04-17 13:44:07 +00:00
|
|
|
return urlencode(link['base_url'])
|
2018-04-17 13:13:38 +00:00
|
|
|
|
|
|
|
# Since the wget algorithm to for -E (appending .html) is incredibly complex
|
|
|
|
# instead of trying to emulate it here, we just look in the output folder
|
|
|
|
# to see what html file wget actually created as the output
|
2018-04-17 21:16:29 +00:00
|
|
|
wget_folder = link['base_url'].rsplit('/', 1)[0].split('/')
|
2018-06-11 01:26:11 +00:00
|
|
|
look_in = os.path.join(ARCHIVE_DIR, link['timestamp'], *wget_folder)
|
2018-04-17 13:13:38 +00:00
|
|
|
|
|
|
|
if look_in and os.path.exists(look_in):
|
|
|
|
html_files = [
|
|
|
|
f for f in os.listdir(look_in)
|
|
|
|
if re.search(".+\\.[Hh][Tt][Mm][Ll]?$", f, re.I | re.M)
|
|
|
|
]
|
|
|
|
if html_files:
|
2018-04-17 21:16:29 +00:00
|
|
|
return urlencode(os.path.join(*wget_folder, html_files[0]))
|
|
|
|
|
|
|
|
return None
|
2018-04-17 13:13:38 +00:00
|
|
|
|
|
|
|
# If finding the actual output file didn't work, fall back to the buggy
|
|
|
|
# implementation of the wget .html appending algorithm
|
2018-04-17 21:16:29 +00:00
|
|
|
# split_url = link['url'].split('#', 1)
|
|
|
|
# query = ('%3F' + link['url'].split('?', 1)[-1]) if '?' in link['url'] else ''
|
|
|
|
|
|
|
|
# if re.search(".+\\.[Hh][Tt][Mm][Ll]?$", split_url[0], re.I | re.M):
|
|
|
|
# # already ends in .html
|
|
|
|
# return urlencode(link['base_url'])
|
|
|
|
# else:
|
|
|
|
# # .html needs to be appended
|
|
|
|
# without_scheme = split_url[0].split('://', 1)[-1].split('?', 1)[0]
|
|
|
|
# if without_scheme.endswith('/'):
|
|
|
|
# if query:
|
|
|
|
# return urlencode('#'.join([without_scheme + 'index.html' + query + '.html', *split_url[1:]]))
|
|
|
|
# return urlencode('#'.join([without_scheme + 'index.html', *split_url[1:]]))
|
|
|
|
# else:
|
|
|
|
# if query:
|
|
|
|
# return urlencode('#'.join([without_scheme + '/index.html' + query + '.html', *split_url[1:]]))
|
|
|
|
# elif '/' in without_scheme:
|
|
|
|
# return urlencode('#'.join([without_scheme + '.html', *split_url[1:]]))
|
|
|
|
# return urlencode(link['base_url'] + '/index.html')
|
2017-10-23 09:58:41 +00:00
|
|
|
|
|
|
|
|
|
|
|
def derived_link_info(link):
|
|
|
|
"""extend link info with the archive urls and other derived data"""
|
|
|
|
|
|
|
|
link_info = {
|
|
|
|
**link,
|
2019-01-11 10:19:07 +00:00
|
|
|
'date': datetime.fromtimestamp(Decimal(link['timestamp'])).strftime('%Y-%m-%d %H:%M'),
|
2017-10-23 09:58:41 +00:00
|
|
|
'google_favicon_url': 'https://www.google.com/s2/favicons?domain={domain}'.format(**link),
|
2018-04-17 11:01:09 +00:00
|
|
|
'favicon_url': 'archive/{timestamp}/favicon.ico'.format(**link),
|
|
|
|
'files_url': 'archive/{timestamp}/index.html'.format(**link),
|
2018-06-17 22:32:52 +00:00
|
|
|
'archive_url': 'archive/{}/{}'.format(link['timestamp'], wget_output_path(link) or 'index.html'),
|
2018-04-17 11:01:09 +00:00
|
|
|
'pdf_link': 'archive/{timestamp}/output.pdf'.format(**link),
|
|
|
|
'screenshot_link': 'archive/{timestamp}/screenshot.png'.format(**link),
|
2018-06-10 22:45:41 +00:00
|
|
|
'dom_link': 'archive/{timestamp}/output.html'.format(**link),
|
2017-10-23 09:58:41 +00:00
|
|
|
'archive_org_url': 'https://web.archive.org/web/{base_url}'.format(**link),
|
2019-02-19 07:40:02 +00:00
|
|
|
'title': link['title'] or link['url'],
|
2017-10-23 09:58:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
# PDF and images are handled slightly differently
|
|
|
|
# wget, screenshot, & pdf urls all point to the same file
|
|
|
|
if link['type'] in ('PDF', 'image'):
|
|
|
|
link_info.update({
|
|
|
|
'archive_url': 'archive/{timestamp}/{base_url}'.format(**link),
|
|
|
|
'pdf_link': 'archive/{timestamp}/{base_url}'.format(**link),
|
|
|
|
'screenshot_link': 'archive/{timestamp}/{base_url}'.format(**link),
|
2018-06-10 22:45:41 +00:00
|
|
|
'dom_link': 'archive/{timestamp}/{base_url}'.format(**link),
|
2019-02-19 06:44:54 +00:00
|
|
|
'title': link['title'] or basename(link['url']),
|
2017-10-23 09:58:41 +00:00
|
|
|
})
|
|
|
|
return link_info
|
2019-01-20 19:07:28 +00:00
|
|
|
|
|
|
|
|
|
|
|
def run(*popenargs, input=None, capture_output=False, timeout=None, check=False, **kwargs):
|
|
|
|
"""Patched of subprocess.run to fix blocking io making timeout=innefective"""
|
|
|
|
|
|
|
|
if input is not None:
|
|
|
|
if 'stdin' in kwargs:
|
|
|
|
raise ValueError('stdin and input arguments may not both be used.')
|
|
|
|
kwargs['stdin'] = PIPE
|
|
|
|
|
|
|
|
if capture_output:
|
|
|
|
if ('stdout' in kwargs) or ('stderr' in kwargs):
|
|
|
|
raise ValueError('stdout and stderr arguments may not be used '
|
|
|
|
'with capture_output.')
|
|
|
|
kwargs['stdout'] = PIPE
|
|
|
|
kwargs['stderr'] = PIPE
|
|
|
|
|
|
|
|
with Popen(*popenargs, **kwargs) as process:
|
|
|
|
try:
|
|
|
|
stdout, stderr = process.communicate(input, timeout=timeout)
|
|
|
|
except TimeoutExpired:
|
|
|
|
process.kill()
|
|
|
|
try:
|
|
|
|
stdout, stderr = process.communicate(input, timeout=2)
|
|
|
|
except:
|
|
|
|
pass
|
|
|
|
raise TimeoutExpired(popenargs[0][0], timeout)
|
|
|
|
except BaseException as err:
|
|
|
|
process.kill()
|
|
|
|
# We don't call process.wait() as .__exit__ does that for us.
|
|
|
|
raise
|
|
|
|
retcode = process.poll()
|
|
|
|
if check and retcode:
|
|
|
|
raise CalledProcessError(retcode, process.args,
|
|
|
|
output=stdout, stderr=stderr)
|
|
|
|
return CompletedProcess(process.args, retcode, stdout, stderr)
|