2019-04-19 01:09:54 +00:00
|
|
|
__package__ = 'archivebox.legacy'
|
|
|
|
|
2017-07-04 10:38:07 +00:00
|
|
|
import os
|
2017-10-18 22:38:17 +00:00
|
|
|
import json
|
|
|
|
|
2019-04-17 06:25:28 +00:00
|
|
|
from typing import List, Tuple, Optional, Iterable
|
2019-04-03 04:27:37 +00:00
|
|
|
from collections import OrderedDict
|
2019-04-19 01:09:54 +00:00
|
|
|
from contextlib import contextmanager
|
2019-03-26 07:20:41 +00:00
|
|
|
|
2019-04-02 22:53:21 +00:00
|
|
|
from .schema import Link, ArchiveResult
|
|
|
|
from .config import (
|
2019-04-19 01:09:54 +00:00
|
|
|
SQL_INDEX_FILENAME,
|
|
|
|
JSON_INDEX_FILENAME,
|
|
|
|
HTML_INDEX_FILENAME,
|
2019-02-21 22:45:28 +00:00
|
|
|
OUTPUT_DIR,
|
2019-03-27 14:31:22 +00:00
|
|
|
TIMEOUT,
|
2019-04-03 04:27:37 +00:00
|
|
|
URL_BLACKLIST_PTN,
|
2019-04-11 11:00:26 +00:00
|
|
|
ANSI,
|
|
|
|
stderr,
|
2017-07-05 21:33:51 +00:00
|
|
|
)
|
2019-04-17 06:25:28 +00:00
|
|
|
from .storage.html import write_html_main_index, write_html_link_details
|
|
|
|
from .storage.json import (
|
|
|
|
parse_json_main_index,
|
|
|
|
write_json_main_index,
|
|
|
|
parse_json_link_details,
|
|
|
|
write_json_link_details,
|
|
|
|
)
|
2019-04-17 07:49:18 +00:00
|
|
|
from .storage.sql import (
|
|
|
|
write_sql_main_index,
|
|
|
|
parse_sql_main_index,
|
|
|
|
)
|
2019-04-02 22:53:21 +00:00
|
|
|
from .util import (
|
2019-04-03 04:27:37 +00:00
|
|
|
scheme,
|
2019-03-27 02:26:21 +00:00
|
|
|
enforce_types,
|
2019-03-27 14:31:22 +00:00
|
|
|
TimedProgress,
|
2019-03-27 22:24:57 +00:00
|
|
|
atomic_write,
|
2019-04-11 07:41:25 +00:00
|
|
|
ExtendedEncoder,
|
2017-10-23 09:58:41 +00:00
|
|
|
)
|
2019-04-02 22:53:21 +00:00
|
|
|
from .parse import parse_links
|
|
|
|
from .logs import (
|
2019-03-22 19:09:39 +00:00
|
|
|
log_indexing_process_started,
|
2019-04-19 01:09:54 +00:00
|
|
|
log_indexing_process_finished,
|
2019-03-21 05:28:12 +00:00
|
|
|
log_indexing_started,
|
|
|
|
log_indexing_finished,
|
|
|
|
log_parsing_started,
|
|
|
|
log_parsing_finished,
|
|
|
|
)
|
2017-10-18 22:38:17 +00:00
|
|
|
|
2019-04-03 04:27:37 +00:00
|
|
|
### Link filtering and checking
|
|
|
|
|
|
|
|
@enforce_types
|
|
|
|
def merge_links(a: Link, b: Link) -> Link:
|
|
|
|
"""deterministially merge two links, favoring longer field values over shorter,
|
|
|
|
and "cleaner" values over worse ones.
|
|
|
|
"""
|
|
|
|
assert a.base_url == b.base_url, 'Cannot merge two links with different URLs'
|
|
|
|
|
2019-04-17 06:25:28 +00:00
|
|
|
# longest url wins (because a fuzzy url will always be shorter)
|
2019-04-03 04:27:37 +00:00
|
|
|
url = a.url if len(a.url) > len(b.url) else b.url
|
|
|
|
|
2019-04-17 06:25:28 +00:00
|
|
|
# best title based on length and quality
|
2019-04-03 04:27:37 +00:00
|
|
|
possible_titles = [
|
|
|
|
title
|
|
|
|
for title in (a.title, b.title)
|
|
|
|
if title and title.strip() and '://' not in title
|
|
|
|
]
|
|
|
|
title = None
|
|
|
|
if len(possible_titles) == 2:
|
|
|
|
title = max(possible_titles, key=lambda t: len(t))
|
|
|
|
elif len(possible_titles) == 1:
|
|
|
|
title = possible_titles[0]
|
|
|
|
|
2019-04-17 06:25:28 +00:00
|
|
|
# earliest valid timestamp
|
2019-04-03 04:27:37 +00:00
|
|
|
timestamp = (
|
|
|
|
a.timestamp
|
|
|
|
if float(a.timestamp or 0) < float(b.timestamp or 0) else
|
|
|
|
b.timestamp
|
|
|
|
)
|
|
|
|
|
2019-04-17 06:25:28 +00:00
|
|
|
# all unique, truthy tags
|
2019-04-03 04:27:37 +00:00
|
|
|
tags_set = (
|
|
|
|
set(tag.strip() for tag in (a.tags or '').split(','))
|
|
|
|
| set(tag.strip() for tag in (b.tags or '').split(','))
|
|
|
|
)
|
|
|
|
tags = ','.join(tags_set) or None
|
|
|
|
|
2019-04-17 06:25:28 +00:00
|
|
|
# all unique source entries
|
2019-04-03 04:27:37 +00:00
|
|
|
sources = list(set(a.sources + b.sources))
|
|
|
|
|
2019-04-17 06:25:28 +00:00
|
|
|
# all unique history entries for the combined archive methods
|
2019-04-03 04:27:37 +00:00
|
|
|
all_methods = set(list(a.history.keys()) + list(a.history.keys()))
|
|
|
|
history = {
|
|
|
|
method: (a.history.get(method) or []) + (b.history.get(method) or [])
|
|
|
|
for method in all_methods
|
|
|
|
}
|
2019-04-11 07:41:25 +00:00
|
|
|
for method in all_methods:
|
|
|
|
deduped_jsons = {
|
|
|
|
json.dumps(result, sort_keys=True, cls=ExtendedEncoder)
|
|
|
|
for result in history[method]
|
|
|
|
}
|
|
|
|
history[method] = list(reversed(sorted(
|
|
|
|
(ArchiveResult.from_json(json.loads(result)) for result in deduped_jsons),
|
|
|
|
key=lambda result: result.start_ts,
|
|
|
|
)))
|
|
|
|
|
2019-04-03 04:27:37 +00:00
|
|
|
return Link(
|
|
|
|
url=url,
|
|
|
|
timestamp=timestamp,
|
|
|
|
title=title,
|
|
|
|
tags=tags,
|
|
|
|
sources=sources,
|
|
|
|
history=history,
|
|
|
|
)
|
|
|
|
|
2019-04-17 06:25:28 +00:00
|
|
|
|
|
|
|
@enforce_types
|
2019-04-03 04:27:37 +00:00
|
|
|
def validate_links(links: Iterable[Link]) -> Iterable[Link]:
|
|
|
|
links = archivable_links(links) # remove chrome://, about:, mailto: etc.
|
|
|
|
links = sorted_links(links) # deterministically sort the links based on timstamp, url
|
|
|
|
links = uniquefied_links(links) # merge/dedupe duplicate timestamps & urls
|
|
|
|
|
|
|
|
if not links:
|
2019-04-19 01:09:54 +00:00
|
|
|
stderr('{red}[X] No links found in index.{reset}'.format(**ANSI))
|
2019-04-11 11:00:34 +00:00
|
|
|
stderr(' To add a link to your archive, run:')
|
|
|
|
stderr(" archivebox add 'https://example.com'")
|
|
|
|
stderr()
|
|
|
|
stderr(' For more usage and examples, run:')
|
|
|
|
stderr(' archivebox help')
|
2019-04-03 04:27:37 +00:00
|
|
|
raise SystemExit(1)
|
|
|
|
|
|
|
|
return links
|
|
|
|
|
2019-04-17 06:25:28 +00:00
|
|
|
|
|
|
|
@enforce_types
|
2019-04-03 04:27:37 +00:00
|
|
|
def archivable_links(links: Iterable[Link]) -> Iterable[Link]:
|
|
|
|
"""remove chrome://, about:// or other schemed links that cant be archived"""
|
|
|
|
for link in links:
|
|
|
|
scheme_is_valid = scheme(link.url) in ('http', 'https', 'ftp')
|
|
|
|
not_blacklisted = (not URL_BLACKLIST_PTN.match(link.url)) if URL_BLACKLIST_PTN else True
|
|
|
|
if scheme_is_valid and not_blacklisted:
|
|
|
|
yield link
|
|
|
|
|
|
|
|
|
2019-04-17 06:25:28 +00:00
|
|
|
@enforce_types
|
2019-04-03 04:27:37 +00:00
|
|
|
def uniquefied_links(sorted_links: Iterable[Link]) -> Iterable[Link]:
|
|
|
|
"""
|
|
|
|
ensures that all non-duplicate links have monotonically increasing timestamps
|
|
|
|
"""
|
|
|
|
|
|
|
|
unique_urls: OrderedDict[str, Link] = OrderedDict()
|
|
|
|
|
|
|
|
for link in sorted_links:
|
2019-04-17 03:19:44 +00:00
|
|
|
if link.base_url in unique_urls:
|
2019-04-03 04:27:37 +00:00
|
|
|
# merge with any other links that share the same url
|
2019-04-17 03:19:44 +00:00
|
|
|
link = merge_links(unique_urls[link.base_url], link)
|
|
|
|
unique_urls[link.base_url] = link
|
2019-04-03 04:27:37 +00:00
|
|
|
|
|
|
|
unique_timestamps: OrderedDict[str, Link] = OrderedDict()
|
|
|
|
for link in unique_urls.values():
|
|
|
|
new_link = link.overwrite(
|
|
|
|
timestamp=lowest_uniq_timestamp(unique_timestamps, link.timestamp),
|
|
|
|
)
|
|
|
|
unique_timestamps[new_link.timestamp] = new_link
|
|
|
|
|
|
|
|
return unique_timestamps.values()
|
|
|
|
|
|
|
|
|
2019-04-17 06:25:28 +00:00
|
|
|
@enforce_types
|
2019-04-03 04:27:37 +00:00
|
|
|
def sorted_links(links: Iterable[Link]) -> Iterable[Link]:
|
|
|
|
sort_func = lambda link: (link.timestamp.split('.', 1)[0], link.url)
|
|
|
|
return sorted(links, key=sort_func, reverse=True)
|
|
|
|
|
|
|
|
|
2019-04-17 06:25:28 +00:00
|
|
|
@enforce_types
|
|
|
|
def links_after_timestamp(links: Iterable[Link], resume: Optional[float]=None) -> Iterable[Link]:
|
2019-04-03 04:27:37 +00:00
|
|
|
if not resume:
|
|
|
|
yield from links
|
|
|
|
return
|
|
|
|
|
|
|
|
for link in links:
|
|
|
|
try:
|
|
|
|
if float(link.timestamp) <= resume:
|
|
|
|
yield link
|
|
|
|
except (ValueError, TypeError):
|
|
|
|
print('Resume value and all timestamp values must be valid numbers.')
|
|
|
|
|
|
|
|
|
2019-04-17 06:25:28 +00:00
|
|
|
@enforce_types
|
2019-04-03 04:27:37 +00:00
|
|
|
def lowest_uniq_timestamp(used_timestamps: OrderedDict, timestamp: str) -> str:
|
|
|
|
"""resolve duplicate timestamps by appending a decimal 1234, 1234 -> 1234.1, 1234.2"""
|
|
|
|
|
|
|
|
timestamp = timestamp.split('.')[0]
|
|
|
|
nonce = 0
|
|
|
|
|
|
|
|
# first try 152323423 before 152323423.0
|
|
|
|
if timestamp not in used_timestamps:
|
|
|
|
return timestamp
|
|
|
|
|
|
|
|
new_timestamp = '{}.{}'.format(timestamp, nonce)
|
|
|
|
while new_timestamp in used_timestamps:
|
|
|
|
nonce += 1
|
|
|
|
new_timestamp = '{}.{}'.format(timestamp, nonce)
|
|
|
|
|
|
|
|
return new_timestamp
|
|
|
|
|
|
|
|
|
2019-03-27 22:24:30 +00:00
|
|
|
|
2019-04-17 06:25:28 +00:00
|
|
|
### Main Links Index
|
2017-10-18 22:38:17 +00:00
|
|
|
|
2019-04-19 01:09:54 +00:00
|
|
|
@contextmanager
|
2019-03-27 02:26:21 +00:00
|
|
|
@enforce_types
|
2019-04-19 01:09:54 +00:00
|
|
|
def timed_index_update(out_path: str):
|
|
|
|
log_indexing_started(out_path)
|
2019-04-17 07:49:18 +00:00
|
|
|
timer = TimedProgress(TIMEOUT * 2, prefix=' ')
|
|
|
|
try:
|
2019-04-19 01:09:54 +00:00
|
|
|
yield
|
2019-04-17 07:49:18 +00:00
|
|
|
finally:
|
|
|
|
timer.end()
|
|
|
|
|
2019-04-19 01:09:54 +00:00
|
|
|
assert os.path.exists(out_path), f'Failed to write index file: {out_path}'
|
|
|
|
log_indexing_finished(out_path)
|
|
|
|
|
|
|
|
|
|
|
|
@enforce_types
|
|
|
|
def write_main_index(links: List[Link], out_dir: str=OUTPUT_DIR, finished: bool=False) -> None:
|
|
|
|
"""create index.html file for a given list of links"""
|
|
|
|
|
|
|
|
log_indexing_process_started(len(links))
|
|
|
|
|
|
|
|
with timed_index_update(os.path.join(out_dir, SQL_INDEX_FILENAME)):
|
|
|
|
write_sql_main_index(links, out_dir=out_dir)
|
|
|
|
|
|
|
|
with timed_index_update(os.path.join(out_dir, JSON_INDEX_FILENAME)):
|
2019-04-17 06:25:28 +00:00
|
|
|
write_json_main_index(links, out_dir=out_dir)
|
2019-04-19 01:09:54 +00:00
|
|
|
|
|
|
|
with timed_index_update(os.path.join(out_dir, HTML_INDEX_FILENAME)):
|
2019-04-17 06:25:28 +00:00
|
|
|
write_html_main_index(links, out_dir=out_dir, finished=finished)
|
2019-04-19 01:09:54 +00:00
|
|
|
|
|
|
|
log_indexing_process_finished()
|
2019-03-26 09:33:34 +00:00
|
|
|
|
2019-03-27 02:26:21 +00:00
|
|
|
|
|
|
|
@enforce_types
|
2019-04-22 23:08:01 +00:00
|
|
|
def load_main_index(out_dir: str=OUTPUT_DIR, warn: bool=True) -> List[Link]:
|
2019-03-21 05:28:12 +00:00
|
|
|
"""parse and load existing index with any new links from import_path merged in"""
|
|
|
|
|
2019-04-19 01:09:54 +00:00
|
|
|
all_links: List[Link] = []
|
|
|
|
all_links = list(parse_json_main_index(out_dir))
|
|
|
|
links_from_sql = list(parse_sql_main_index())
|
2019-04-22 23:08:01 +00:00
|
|
|
|
|
|
|
if warn and not set(l.url for l in all_links) == set(l['url'] for l in links_from_sql):
|
|
|
|
stderr('{red}[!] Warning: SQL index does not match JSON index!{reset}'.format(**ANSI))
|
2019-04-19 01:09:54 +00:00
|
|
|
|
|
|
|
return all_links
|
2019-03-21 05:28:12 +00:00
|
|
|
|
2019-04-22 23:08:01 +00:00
|
|
|
@enforce_types
|
|
|
|
def load_main_index_meta(out_dir: str=OUTPUT_DIR) -> Optional[dict]:
|
|
|
|
index_path = os.path.join(out_dir, JSON_INDEX_FILENAME)
|
|
|
|
if os.path.exists(index_path):
|
|
|
|
with open(index_path, 'r', encoding='utf-8') as f:
|
|
|
|
meta_dict = json.load(f)
|
|
|
|
meta_dict.pop('links')
|
|
|
|
return meta_dict
|
|
|
|
|
|
|
|
return None
|
2019-04-19 01:09:54 +00:00
|
|
|
|
|
|
|
@enforce_types
|
|
|
|
def import_new_links(existing_links: List[Link], import_path: str) -> Tuple[List[Link], List[Link]]:
|
2019-03-26 07:20:41 +00:00
|
|
|
new_links: List[Link] = []
|
2019-04-19 01:09:54 +00:00
|
|
|
|
|
|
|
# parse and validate the import file
|
|
|
|
log_parsing_started(import_path)
|
|
|
|
raw_links, parser_name = parse_links(import_path)
|
|
|
|
new_links = list(validate_links(raw_links))
|
2019-03-21 05:28:12 +00:00
|
|
|
|
|
|
|
# merge existing links in out_dir and new links
|
2019-03-26 23:21:34 +00:00
|
|
|
all_links = list(validate_links(existing_links + new_links))
|
2019-03-21 05:28:12 +00:00
|
|
|
|
2019-04-19 01:09:54 +00:00
|
|
|
if parser_name:
|
2019-03-27 19:16:53 +00:00
|
|
|
num_parsed = len(raw_links)
|
|
|
|
num_new_links = len(all_links) - len(existing_links)
|
|
|
|
log_parsing_finished(num_parsed, num_new_links, parser_name)
|
2019-03-21 05:28:12 +00:00
|
|
|
|
|
|
|
return all_links, new_links
|
2017-07-04 10:38:07 +00:00
|
|
|
|
2019-03-26 09:33:34 +00:00
|
|
|
|
2019-03-27 02:26:21 +00:00
|
|
|
@enforce_types
|
2019-04-17 06:25:28 +00:00
|
|
|
def patch_main_index(link: Link, out_dir: str=OUTPUT_DIR) -> None:
|
|
|
|
"""hack to in-place update one row's info in the generated index files"""
|
2017-07-04 10:38:07 +00:00
|
|
|
|
2019-04-17 06:25:28 +00:00
|
|
|
# TODO: remove this ASAP, it's ugly, error-prone, and potentially dangerous
|
2017-07-04 10:38:07 +00:00
|
|
|
|
2019-04-17 06:25:28 +00:00
|
|
|
title = link.title or link.latest_outputs(status='succeeded')['title']
|
2019-03-26 23:21:34 +00:00
|
|
|
successful = link.num_outputs
|
2019-02-21 22:45:28 +00:00
|
|
|
|
2019-04-17 06:25:28 +00:00
|
|
|
# Patch JSON main index
|
|
|
|
json_file_links = parse_json_main_index(out_dir)
|
2019-03-26 23:21:34 +00:00
|
|
|
patched_links = []
|
2019-03-21 05:28:12 +00:00
|
|
|
for saved_link in json_file_links:
|
2019-03-26 23:21:34 +00:00
|
|
|
if saved_link.url == link.url:
|
2019-03-27 07:49:39 +00:00
|
|
|
patched_links.append(saved_link.overwrite(
|
|
|
|
title=title,
|
|
|
|
history=link.history,
|
|
|
|
updated=link.updated,
|
|
|
|
))
|
2019-03-26 23:21:34 +00:00
|
|
|
else:
|
|
|
|
patched_links.append(saved_link)
|
|
|
|
|
2019-04-17 06:25:28 +00:00
|
|
|
write_json_main_index(patched_links, out_dir=out_dir)
|
2019-02-21 22:45:28 +00:00
|
|
|
|
2019-04-17 06:25:28 +00:00
|
|
|
# Patch HTML main index
|
2019-03-21 05:28:12 +00:00
|
|
|
html_path = os.path.join(out_dir, 'index.html')
|
2019-04-17 06:25:28 +00:00
|
|
|
with open(html_path, 'r') as f:
|
|
|
|
html = f.read().split('\n')
|
2019-03-19 22:09:46 +00:00
|
|
|
for idx, line in enumerate(html):
|
2019-03-26 23:21:34 +00:00
|
|
|
if title and ('<span data-title-for="{}"'.format(link.url) in line):
|
2019-03-19 22:09:46 +00:00
|
|
|
html[idx] = '<span>{}</span>'.format(title)
|
2019-03-26 23:21:34 +00:00
|
|
|
elif successful and ('<span data-number-for="{}"'.format(link.url) in line):
|
2019-03-19 22:09:46 +00:00
|
|
|
html[idx] = '<span>{}</span>'.format(successful)
|
|
|
|
break
|
|
|
|
|
2019-03-27 22:24:57 +00:00
|
|
|
atomic_write('\n'.join(html), html_path)
|
2019-02-21 22:45:28 +00:00
|
|
|
|
2019-03-21 05:28:12 +00:00
|
|
|
|
2019-04-17 06:25:28 +00:00
|
|
|
### Link Details Index
|
2019-03-26 09:33:34 +00:00
|
|
|
|
2019-03-27 02:26:21 +00:00
|
|
|
@enforce_types
|
2019-04-17 06:25:28 +00:00
|
|
|
def write_link_details(link: Link, out_dir: Optional[str]=None) -> None:
|
|
|
|
out_dir = out_dir or link.link_dir
|
2017-10-18 22:38:17 +00:00
|
|
|
|
2019-04-17 06:25:28 +00:00
|
|
|
write_json_link_details(link, out_dir=out_dir)
|
|
|
|
write_html_link_details(link, out_dir=out_dir)
|
2017-10-23 09:58:41 +00:00
|
|
|
|
2019-03-26 09:33:34 +00:00
|
|
|
|
2019-03-27 02:26:21 +00:00
|
|
|
@enforce_types
|
2019-04-17 06:25:28 +00:00
|
|
|
def load_link_details(link: Link, out_dir: Optional[str]=None) -> Link:
|
2019-03-21 05:28:12 +00:00
|
|
|
"""check for an existing link archive in the given directory,
|
|
|
|
and load+merge it into the given link dict
|
|
|
|
"""
|
2019-04-17 06:25:28 +00:00
|
|
|
out_dir = out_dir or link.link_dir
|
|
|
|
|
|
|
|
existing_link = parse_json_link_details(out_dir)
|
2019-03-27 02:26:21 +00:00
|
|
|
if existing_link:
|
|
|
|
return merge_links(existing_link, link)
|
2019-04-17 06:25:28 +00:00
|
|
|
|
2019-03-27 02:26:21 +00:00
|
|
|
return link
|