1
0
Fork 0
mirror of synced 2024-07-02 21:10:25 +12:00
ArchiveBox/archivebox/archive.py

204 lines
6.3 KiB
Python
Raw Normal View History

2017-05-05 21:00:30 +12:00
#!/usr/bin/env python3
# ArchiveBox
2017-06-30 20:23:19 +12:00
# Nick Sweeting 2017 | MIT License
# https://github.com/pirate/ArchiveBox
2017-05-05 21:00:30 +12:00
2017-10-31 00:09:33 +13:00
import os
2017-05-05 21:00:30 +12:00
import sys
2017-06-30 20:23:19 +12:00
from datetime import datetime
from subprocess import run
2017-10-23 22:56:21 +13:00
from parse import parse_links
from links import (
new_links,
validate_links
)
from archive_methods import archive_links, _RESULTS_TOTALS
from index import (
write_links_index,
write_link_index,
parse_json_links_index,
parse_json_link_index,
)
from config import (
ONLY_NEW,
2018-06-11 13:12:55 +12:00
OUTPUT_PERMISSIONS,
OUTPUT_DIR,
2017-07-06 09:33:51 +12:00
ANSI,
TIMEOUT,
2018-06-11 14:02:33 +12:00
GIT_SHA,
)
from util import (
download_url,
2019-01-15 12:11:48 +13:00
save_source,
progress,
2017-10-23 22:56:21 +13:00
cleanup_archive,
2018-06-11 13:58:48 +12:00
pretty_path,
migrate_data,
)
2017-06-16 10:33:01 +12:00
2018-06-11 14:02:33 +12:00
__AUTHOR__ = 'Nick Sweeting <git@nicksweeting.com>'
__VERSION__ = GIT_SHA
2019-01-15 12:11:48 +13:00
__DESCRIPTION__ = 'ArchiveBox Usage: Create a browsable html archive of a list of links.'
__DOCUMENTATION__ = 'https://github.com/pirate/ArchiveBox/wiki'
2017-05-05 23:27:05 +12:00
2017-10-31 00:09:33 +13:00
def print_help():
print(__DESCRIPTION__)
print("Documentation: {}\n".format(__DOCUMENTATION__))
print("Usage:")
print(" ./bin/archivebox ~/Downloads/bookmarks_export.html\n")
2019-01-15 12:11:48 +13:00
print("")
print(" ./bin/archivebox https://example.com/feed.rss\n")
print("")
print(" echo 'https://examplecom' | ./bin/archivebox\n")
2017-06-30 20:23:19 +12:00
2017-10-31 00:09:33 +13:00
def merge_links(archive_path=OUTPUT_DIR, import_path=None, only_new=False):
2017-10-31 00:09:33 +13:00
"""get new links from file and optionally append them to links in existing archive"""
2018-04-17 23:00:06 +12:00
all_links = []
if import_path:
# parse and validate the import file
2019-02-05 15:45:18 +13:00
raw_links, parser_name = parse_links(import_path)
2018-04-17 23:00:06 +12:00
all_links = validate_links(raw_links)
2017-10-31 00:09:33 +13:00
# merge existing links in archive_path and new links
existing_links = []
if archive_path:
existing_links = parse_json_links_index(archive_path)
2018-04-17 23:00:06 +12:00
all_links = validate_links(existing_links + all_links)
2017-10-31 00:09:33 +13:00
2018-04-17 23:00:06 +12:00
num_new_links = len(all_links) - len(existing_links)
if num_new_links and not only_new:
2019-02-05 15:53:54 +13:00
print('[{green}+{reset}] [{}] Adding {} new links from {} to {}/index.json (detected {} format)'.format(
2018-04-17 23:00:06 +12:00
datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
num_new_links,
pretty_path(import_path),
pretty_path(archive_path),
2019-02-05 15:45:18 +13:00
parser_name,
2018-04-18 01:11:27 +12:00
**ANSI,
2018-04-17 23:00:06 +12:00
))
2018-04-18 13:23:26 +12:00
# else:
# print('[*] [{}] No new links added to {}/index.json{}'.format(
# datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
# archive_path,
# ' from {}'.format(import_path) if import_path else '',
# **ANSI,
# ))
2017-10-31 00:09:33 +13:00
if only_new:
return new_links(all_links, existing_links)
2018-04-17 23:00:06 +12:00
return all_links
2017-10-31 00:09:33 +13:00
def update_archive(archive_path, links, source=None, resume=None, append=True):
2017-10-23 22:56:21 +13:00
"""update or create index.html+json given a path to an export file containing new links"""
2017-06-30 20:23:19 +12:00
start_ts = datetime.now().timestamp()
2018-04-17 23:30:06 +12:00
if resume:
2018-04-18 01:11:27 +12:00
print('{green}[▶] [{}] Resuming archive downloading from {}...{reset}'.format(
2018-04-17 23:30:06 +12:00
datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
resume,
**ANSI,
))
else:
2018-04-18 01:11:27 +12:00
print('{green}[▶] [{}] Updating files for {} links in archive...{reset}'.format(
2018-04-17 23:30:06 +12:00
datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
2018-04-18 01:11:27 +12:00
len(links),
2018-04-17 23:30:06 +12:00
**ANSI,
))
2017-10-23 22:56:21 +13:00
# loop over links and archive them
2017-10-31 00:09:33 +13:00
archive_links(archive_path, links, source=source, resume=resume)
2017-10-23 22:56:21 +13:00
# print timing information & summary
end_ts = datetime.now().timestamp()
2017-10-31 00:09:33 +13:00
seconds = end_ts - start_ts
if seconds > 60:
duration = '{0:.2f} min'.format(seconds / 60, 2)
else:
duration = '{0:.2f} sec'.format(seconds, 2)
2018-04-18 01:11:27 +12:00
print('{}[√] [{}] Update of {} links complete ({}){}'.format(
2017-10-23 22:56:21 +13:00
ANSI['green'],
datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
2018-04-18 01:11:27 +12:00
len(links),
2017-10-23 22:56:21 +13:00
duration,
ANSI['reset'],
))
print(' - {} entries skipped'.format(_RESULTS_TOTALS['skipped']))
print(' - {} entries updated'.format(_RESULTS_TOTALS['succeded']))
print(' - {} errors'.format(_RESULTS_TOTALS['failed']))
2017-05-05 21:00:30 +12:00
if __name__ == '__main__':
2017-05-07 00:23:49 +12:00
argc = len(sys.argv)
2017-06-30 20:23:19 +12:00
if set(sys.argv).intersection(('-h', '--help', 'help')):
2017-10-31 00:09:33 +13:00
print_help()
2017-06-30 20:23:19 +12:00
raise SystemExit(0)
migrate_data()
2018-04-17 23:00:06 +12:00
source = sys.argv[1] if argc > 1 else None # path of links file to import
2017-10-31 00:09:33 +13:00
resume = sys.argv[2] if argc > 2 else None # timestamp to resume dowloading from
2019-01-15 12:11:48 +13:00
stdin_raw_text = []
if not sys.stdin.isatty():
stdin_raw_text = sys.stdin.read()
if source and stdin_raw_text:
print(
'[X] You should pass either a path as an argument, '
'or pass a list of links via stdin, but not both.\n'
)
print_help()
raise SystemExit(1)
2018-04-17 23:00:06 +12:00
if argc == 1:
source, resume = None, None
elif argc == 2:
if all(d.isdigit() for d in sys.argv[1].split('.')):
# argv[1] is a resume timestamp
source, resume = None, sys.argv[1]
else:
# argv[1] is a path to a file to import
source, resume = sys.argv[1].strip(), None
elif argc == 3:
2018-04-17 23:30:06 +12:00
source, resume = sys.argv[1].strip(), sys.argv[2]
2018-04-17 23:00:06 +12:00
else:
print_help()
raise SystemExit(1)
2017-10-31 00:09:33 +13:00
# See if archive folder already exists
for out_dir in (OUTPUT_DIR, 'bookmarks', 'pocket', 'pinboard', 'html'):
2018-04-17 23:00:06 +12:00
if os.path.exists(out_dir):
2017-10-31 00:09:33 +13:00
break
else:
out_dir = OUTPUT_DIR
2017-10-31 00:09:33 +13:00
# Step 0: Download url to local file (only happens if a URL is specified instead of local path)
2018-04-17 23:00:06 +12:00
if source and any(source.startswith(s) for s in ('http://', 'https://', 'ftp://')):
2017-10-31 00:09:33 +13:00
source = download_url(source)
2019-01-15 12:11:48 +13:00
elif stdin_raw_text:
source = save_source(stdin_raw_text)
2017-10-31 00:09:33 +13:00
# Step 1: Parse the links and dedupe them with existing archive
links = merge_links(archive_path=out_dir, import_path=source, only_new=False)
new_links = merge_links(archive_path=out_dir, import_path=source, only_new=True)
2017-10-31 00:09:33 +13:00
# Step 2: Write new index
2018-04-17 23:00:06 +12:00
write_links_index(out_dir=out_dir, links=links)
2017-10-31 00:09:33 +13:00
# Step 3: Verify folder structure is 1:1 with index
2018-04-17 23:00:06 +12:00
# cleanup_archive(out_dir, links)
2017-10-31 00:09:33 +13:00
# Step 4: Run the archive methods for each link
if ONLY_NEW:
update_archive(out_dir, new_links, source=source, resume=resume, append=True)
else:
update_archive(out_dir, links, source=source, resume=resume, append=True)