main.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053
  1. __package__ = 'archivebox'
  2. import os
  3. import sys
  4. import shutil
  5. from typing import Dict, List, Optional, Iterable, IO
  6. from crontab import CronTab, CronSlices
  7. from .cli import (
  8. list_subcommands,
  9. run_subcommand,
  10. display_first,
  11. meta_cmds,
  12. main_cmds,
  13. archive_cmds,
  14. )
  15. from .parsers import (
  16. save_stdin_to_sources,
  17. save_file_to_sources,
  18. )
  19. from .index.schema import Link
  20. from .util import enforce_types, docstring
  21. from .system import get_dir_size, dedupe_cron_jobs, CRON_COMMENT
  22. from .index import (
  23. links_after_timestamp,
  24. load_main_index,
  25. import_new_links,
  26. write_main_index,
  27. link_matches_filter,
  28. get_indexed_folders,
  29. get_archived_folders,
  30. get_unarchived_folders,
  31. get_present_folders,
  32. get_valid_folders,
  33. get_invalid_folders,
  34. get_duplicate_folders,
  35. get_orphaned_folders,
  36. get_corrupted_folders,
  37. get_unrecognized_folders,
  38. fix_invalid_folder_locations,
  39. )
  40. from .index.json import (
  41. parse_json_main_index,
  42. parse_json_links_details,
  43. )
  44. from .index.sql import (
  45. parse_sql_main_index,
  46. get_admins,
  47. apply_migrations,
  48. )
  49. from .index.html import parse_html_main_index
  50. from .extractors import archive_link
  51. from .config import (
  52. stderr,
  53. ConfigDict,
  54. ANSI,
  55. IS_TTY,
  56. USER,
  57. ARCHIVEBOX_BINARY,
  58. ONLY_NEW,
  59. OUTPUT_DIR,
  60. SOURCES_DIR,
  61. ARCHIVE_DIR,
  62. LOGS_DIR,
  63. CONFIG_FILE,
  64. ARCHIVE_DIR_NAME,
  65. SOURCES_DIR_NAME,
  66. LOGS_DIR_NAME,
  67. STATIC_DIR_NAME,
  68. JSON_INDEX_FILENAME,
  69. HTML_INDEX_FILENAME,
  70. SQL_INDEX_FILENAME,
  71. ROBOTS_TXT_FILENAME,
  72. FAVICON_FILENAME,
  73. check_dependencies,
  74. check_data_folder,
  75. write_config_file,
  76. setup_django,
  77. VERSION,
  78. CODE_LOCATIONS,
  79. EXTERNAL_LOCATIONS,
  80. DATA_LOCATIONS,
  81. DEPENDENCIES,
  82. load_all_config,
  83. CONFIG,
  84. USER_CONFIG,
  85. get_real_name,
  86. )
  87. from .cli.logging import (
  88. TERM_WIDTH,
  89. TimedProgress,
  90. log_archiving_started,
  91. log_archiving_paused,
  92. log_archiving_finished,
  93. log_removal_started,
  94. log_removal_finished,
  95. log_list_started,
  96. log_list_finished,
  97. printable_config,
  98. printable_folders,
  99. printable_filesize,
  100. printable_folder_status,
  101. printable_dependency_version,
  102. )
  103. ALLOWED_IN_OUTPUT_DIR = {
  104. '.DS_Store',
  105. '.venv',
  106. 'venv',
  107. 'virtualenv',
  108. '.virtualenv',
  109. ARCHIVE_DIR_NAME,
  110. SOURCES_DIR_NAME,
  111. LOGS_DIR_NAME,
  112. STATIC_DIR_NAME,
  113. SQL_INDEX_FILENAME,
  114. JSON_INDEX_FILENAME,
  115. HTML_INDEX_FILENAME,
  116. ROBOTS_TXT_FILENAME,
  117. FAVICON_FILENAME,
  118. }
  119. @enforce_types
  120. def help(out_dir: str=OUTPUT_DIR) -> None:
  121. """Print the ArchiveBox help message and usage"""
  122. all_subcommands = list_subcommands()
  123. COMMANDS_HELP_TEXT = '\n '.join(
  124. f'{cmd.ljust(20)} {summary}'
  125. for cmd, summary in all_subcommands.items()
  126. if cmd in meta_cmds
  127. ) + '\n\n ' + '\n '.join(
  128. f'{cmd.ljust(20)} {summary}'
  129. for cmd, summary in all_subcommands.items()
  130. if cmd in main_cmds
  131. ) + '\n\n ' + '\n '.join(
  132. f'{cmd.ljust(20)} {summary}'
  133. for cmd, summary in all_subcommands.items()
  134. if cmd in archive_cmds
  135. ) + '\n\n ' + '\n '.join(
  136. f'{cmd.ljust(20)} {summary}'
  137. for cmd, summary in all_subcommands.items()
  138. if cmd not in display_first
  139. )
  140. if os.path.exists(os.path.join(out_dir, JSON_INDEX_FILENAME)):
  141. print('''{green}ArchiveBox v{}: The self-hosted internet archive.{reset}
  142. {lightred}Active data directory:{reset}
  143. {}
  144. {lightred}Usage:{reset}
  145. archivebox [command] [--help] [--version] [...args]
  146. {lightred}Commands:{reset}
  147. {}
  148. {lightred}Example Use:{reset}
  149. mkdir my-archive; cd my-archive/
  150. archivebox init
  151. archivebox status
  152. archivebox add https://example.com/some/page
  153. archivebox add --depth=1 ~/Downloads/bookmarks_export.html
  154. archivebox list --sort=timestamp --csv=timestamp,url,is_archived
  155. archivebox schedule --every=week https://example.com/some/feed.rss
  156. archivebox update --resume=15109948213.123
  157. {lightred}Documentation:{reset}
  158. https://github.com/pirate/ArchiveBox/wiki
  159. '''.format(VERSION, out_dir, COMMANDS_HELP_TEXT, **ANSI))
  160. else:
  161. print('{green}Welcome to ArchiveBox v{}!{reset}'.format(VERSION, **ANSI))
  162. print()
  163. print('To import an existing archive (from a previous version of ArchiveBox):')
  164. print(' 1. cd into your data dir OUTPUT_DIR (usually ArchiveBox/output) and run:')
  165. print(' 2. archivebox init')
  166. print()
  167. print('To start a new archive:')
  168. print(' 1. Create an empty directory, then cd into it and run:')
  169. print(' 2. archivebox init')
  170. print()
  171. print('For more information, see the documentation here:')
  172. print(' https://github.com/pirate/ArchiveBox/wiki')
  173. @enforce_types
  174. def version(quiet: bool=False,
  175. out_dir: str=OUTPUT_DIR) -> None:
  176. """Print the ArchiveBox version and dependency information"""
  177. if quiet:
  178. print(VERSION)
  179. else:
  180. print('ArchiveBox v{}'.format(VERSION))
  181. print()
  182. print('{white}[i] Dependency versions:{reset}'.format(**ANSI))
  183. for name, dependency in DEPENDENCIES.items():
  184. print(printable_dependency_version(name, dependency))
  185. print()
  186. print('{white}[i] Code locations:{reset}'.format(**ANSI))
  187. for name, folder in CODE_LOCATIONS.items():
  188. print(printable_folder_status(name, folder))
  189. print()
  190. print('{white}[i] External locations:{reset}'.format(**ANSI))
  191. for name, folder in EXTERNAL_LOCATIONS.items():
  192. print(printable_folder_status(name, folder))
  193. print()
  194. print('{white}[i] Data locations:{reset}'.format(**ANSI))
  195. for name, folder in DATA_LOCATIONS.items():
  196. print(printable_folder_status(name, folder))
  197. print()
  198. check_dependencies()
  199. @enforce_types
  200. def run(subcommand: str,
  201. subcommand_args: Optional[List[str]],
  202. stdin: Optional[IO]=None,
  203. out_dir: str=OUTPUT_DIR) -> None:
  204. """Run a given ArchiveBox subcommand with the given list of args"""
  205. run_subcommand(
  206. subcommand=subcommand,
  207. subcommand_args=subcommand_args,
  208. stdin=stdin,
  209. pwd=out_dir,
  210. )
  211. @enforce_types
  212. def init(force: bool=False, out_dir: str=OUTPUT_DIR) -> None:
  213. """Initialize a new ArchiveBox collection in the current directory"""
  214. os.makedirs(out_dir, exist_ok=True)
  215. is_empty = not len(set(os.listdir(out_dir)) - ALLOWED_IN_OUTPUT_DIR)
  216. existing_index = os.path.exists(os.path.join(out_dir, JSON_INDEX_FILENAME))
  217. if is_empty and not existing_index:
  218. print('{green}[+] Initializing a new ArchiveBox collection in this folder...{reset}'.format(**ANSI))
  219. print(f' {out_dir}')
  220. print('{green}------------------------------------------------------------------{reset}'.format(**ANSI))
  221. elif existing_index:
  222. print('{green}[*] Updating existing ArchiveBox collection in this folder...{reset}'.format(**ANSI))
  223. print(f' {out_dir}')
  224. print('{green}------------------------------------------------------------------{reset}'.format(**ANSI))
  225. else:
  226. if force:
  227. stderr('[!] This folder appears to already have files in it, but no index.json is present.', color='lightyellow')
  228. stderr(' Because --force was passed, ArchiveBox will initialize anyway (which may overwrite existing files).')
  229. else:
  230. stderr(
  231. ("{red}[X] This folder appears to already have files in it, but no index.json is present.{reset}\n\n"
  232. " You must run init in a completely empty directory, or an existing data folder.\n\n"
  233. " {lightred}Hint:{reset} To import an existing data folder make sure to cd into the folder first, \n"
  234. " then run and run 'archivebox init' to pick up where you left off.\n\n"
  235. " (Always make sure your data folder is backed up first before updating ArchiveBox)"
  236. ).format(out_dir, **ANSI)
  237. )
  238. raise SystemExit(2)
  239. if existing_index:
  240. print('\n{green}[*] Verifying archive folder structure...{reset}'.format(**ANSI))
  241. else:
  242. print('\n{green}[+] Building archive folder structure...{reset}'.format(**ANSI))
  243. os.makedirs(SOURCES_DIR, exist_ok=True)
  244. print(f' √ {SOURCES_DIR}')
  245. os.makedirs(ARCHIVE_DIR, exist_ok=True)
  246. print(f' √ {ARCHIVE_DIR}')
  247. os.makedirs(LOGS_DIR, exist_ok=True)
  248. print(f' √ {LOGS_DIR}')
  249. write_config_file({}, out_dir=out_dir)
  250. print(f' √ {CONFIG_FILE}')
  251. if os.path.exists(os.path.join(out_dir, SQL_INDEX_FILENAME)):
  252. print('\n{green}[*] Verifying main SQL index and running migrations...{reset}'.format(**ANSI))
  253. else:
  254. print('\n{green}[+] Building main SQL index and running migrations...{reset}'.format(**ANSI))
  255. setup_django(out_dir, check_db=False)
  256. from django.conf import settings
  257. DATABASE_FILE = os.path.join(out_dir, SQL_INDEX_FILENAME)
  258. print(f' √ {DATABASE_FILE}')
  259. print()
  260. for migration_line in apply_migrations(out_dir):
  261. print(f' {migration_line}')
  262. assert os.path.exists(DATABASE_FILE)
  263. # from django.contrib.auth.models import User
  264. # if IS_TTY and not User.objects.filter(is_superuser=True).exists():
  265. # print('{green}[+] Creating admin user account...{reset}'.format(**ANSI))
  266. # call_command("createsuperuser", interactive=True)
  267. print()
  268. print('{green}[*] Collecting links from any existing indexes and archive folders...{reset}'.format(**ANSI))
  269. all_links: Dict[str, Link] = {}
  270. if existing_index:
  271. all_links = {
  272. link.url: link
  273. for link in load_main_index(out_dir=out_dir, warn=False)
  274. }
  275. print(' √ Loaded {} links from existing main index.'.format(len(all_links)))
  276. # Links in data folders that dont match their timestamp
  277. fixed, cant_fix = fix_invalid_folder_locations(out_dir=out_dir)
  278. if fixed:
  279. print(' {lightyellow}√ Fixed {} data directory locations that didn\'t match their link timestamps.{reset}'.format(len(fixed), **ANSI))
  280. if cant_fix:
  281. print(' {lightyellow}! Could not fix {} data directory locations due to conflicts with existing folders.{reset}'.format(len(cant_fix), **ANSI))
  282. # Links in JSON index but not in main index
  283. orphaned_json_links = {
  284. link.url: link
  285. for link in parse_json_main_index(out_dir)
  286. if link.url not in all_links
  287. }
  288. if orphaned_json_links:
  289. all_links.update(orphaned_json_links)
  290. print(' {lightyellow}√ Added {} orphaned links from existing JSON index...{reset}'.format(len(orphaned_json_links), **ANSI))
  291. # Links in SQL index but not in main index
  292. orphaned_sql_links = {
  293. link.url: link
  294. for link in parse_sql_main_index(out_dir)
  295. if link.url not in all_links
  296. }
  297. if orphaned_sql_links:
  298. all_links.update(orphaned_sql_links)
  299. print(' {lightyellow}√ Added {} orphaned links from existing SQL index...{reset}'.format(len(orphaned_sql_links), **ANSI))
  300. # Links in data dir indexes but not in main index
  301. orphaned_data_dir_links = {
  302. link.url: link
  303. for link in parse_json_links_details(out_dir)
  304. if link.url not in all_links
  305. }
  306. if orphaned_data_dir_links:
  307. all_links.update(orphaned_data_dir_links)
  308. print(' {lightyellow}√ Added {} orphaned links from existing archive directories.{reset}'.format(len(orphaned_data_dir_links), **ANSI))
  309. # Links in invalid/duplicate data dirs
  310. invalid_folders = {
  311. folder: link
  312. for folder, link in get_invalid_folders(all_links.values(), out_dir=out_dir).items()
  313. }
  314. if invalid_folders:
  315. print(' {lightyellow}! Skipped adding {} invalid link data directories.{reset}'.format(len(invalid_folders), **ANSI))
  316. print(' X ' + '\n X '.join(f'{folder} {link}' for folder, link in invalid_folders.items()))
  317. print()
  318. print(' {lightred}Hint:{reset} For more information about the link data directories that were skipped, run:'.format(**ANSI))
  319. print(' archivebox status')
  320. print(' archivebox list --status=invalid')
  321. write_main_index(list(all_links.values()), out_dir=out_dir)
  322. print('\n{green}------------------------------------------------------------------{reset}'.format(**ANSI))
  323. if existing_index:
  324. print('{green}[√] Done. Verified and updated the existing ArchiveBox collection.{reset}'.format(**ANSI))
  325. else:
  326. print('{green}[√] Done. A new ArchiveBox collection was initialized ({} links).{reset}'.format(len(all_links), **ANSI))
  327. print()
  328. print(' {lightred}Hint:{reset} To view your archive index, run:'.format(**ANSI))
  329. print(' archivebox server # then visit http://127.0.0.1:8000')
  330. print()
  331. print(' To add new links, you can run:')
  332. print(" archivebox add ~/some/path/or/url/to/list_of_links.txt")
  333. print()
  334. print(' For more usage and examples, run:')
  335. print(' archivebox help')
  336. @enforce_types
  337. def status(out_dir: str=OUTPUT_DIR) -> None:
  338. """Print out some info and statistics about the archive collection"""
  339. check_data_folder(out_dir=out_dir)
  340. from core.models import Snapshot
  341. from django.contrib.auth import get_user_model
  342. User = get_user_model()
  343. print('{green}[*] Scanning archive main index...{reset}'.format(**ANSI))
  344. print(ANSI['lightyellow'], f' {out_dir}/*', ANSI['reset'])
  345. num_bytes, num_dirs, num_files = get_dir_size(out_dir, recursive=False, pattern='index.')
  346. size = printable_filesize(num_bytes)
  347. print(f' Index size: {size} across {num_files} files')
  348. print()
  349. links = list(load_main_index(out_dir=out_dir))
  350. num_json_links = len(links)
  351. num_sql_links = sum(1 for link in parse_sql_main_index(out_dir=out_dir))
  352. num_html_links = sum(1 for url in parse_html_main_index(out_dir=out_dir))
  353. num_link_details = sum(1 for link in parse_json_links_details(out_dir=out_dir))
  354. print(f' > JSON Main Index: {num_json_links} links'.ljust(36), f'(found in {JSON_INDEX_FILENAME})')
  355. print(f' > SQL Main Index: {num_sql_links} links'.ljust(36), f'(found in {SQL_INDEX_FILENAME})')
  356. print(f' > HTML Main Index: {num_html_links} links'.ljust(36), f'(found in {HTML_INDEX_FILENAME})')
  357. print(f' > JSON Link Details: {num_link_details} links'.ljust(36), f'(found in {ARCHIVE_DIR_NAME}/*/index.json)')
  358. if num_html_links != len(links) or num_sql_links != len(links):
  359. print()
  360. print(' {lightred}Hint:{reset} You can fix index count differences automatically by running:'.format(**ANSI))
  361. print(' archivebox init')
  362. print()
  363. print('{green}[*] Scanning archive data directories...{reset}'.format(**ANSI))
  364. print(ANSI['lightyellow'], f' {ARCHIVE_DIR}/*', ANSI['reset'])
  365. num_bytes, num_dirs, num_files = get_dir_size(ARCHIVE_DIR)
  366. size = printable_filesize(num_bytes)
  367. print(f' Size: {size} across {num_files} files in {num_dirs} directories')
  368. print(ANSI['black'])
  369. num_indexed = len(get_indexed_folders(links, out_dir=out_dir))
  370. num_archived = len(get_archived_folders(links, out_dir=out_dir))
  371. num_unarchived = len(get_unarchived_folders(links, out_dir=out_dir))
  372. print(f' > indexed: {num_indexed}'.ljust(36), f'({get_indexed_folders.__doc__})')
  373. print(f' > archived: {num_archived}'.ljust(36), f'({get_archived_folders.__doc__})')
  374. print(f' > unarchived: {num_unarchived}'.ljust(36), f'({get_unarchived_folders.__doc__})')
  375. num_present = len(get_present_folders(links, out_dir=out_dir))
  376. num_valid = len(get_valid_folders(links, out_dir=out_dir))
  377. print()
  378. print(f' > present: {num_present}'.ljust(36), f'({get_present_folders.__doc__})')
  379. print(f' > valid: {num_valid}'.ljust(36), f'({get_valid_folders.__doc__})')
  380. duplicate = get_duplicate_folders(links, out_dir=out_dir)
  381. orphaned = get_orphaned_folders(links, out_dir=out_dir)
  382. corrupted = get_corrupted_folders(links, out_dir=out_dir)
  383. unrecognized = get_unrecognized_folders(links, out_dir=out_dir)
  384. num_invalid = len({**duplicate, **orphaned, **corrupted, **unrecognized})
  385. print(f' > invalid: {num_invalid}'.ljust(36), f'({get_invalid_folders.__doc__})')
  386. print(f' > duplicate: {len(duplicate)}'.ljust(36), f'({get_duplicate_folders.__doc__})')
  387. print(f' > orphaned: {len(orphaned)}'.ljust(36), f'({get_orphaned_folders.__doc__})')
  388. print(f' > corrupted: {len(corrupted)}'.ljust(36), f'({get_corrupted_folders.__doc__})')
  389. print(f' > unrecognized: {len(unrecognized)}'.ljust(36), f'({get_unrecognized_folders.__doc__})')
  390. print(ANSI['reset'])
  391. if num_indexed:
  392. print(' {lightred}Hint:{reset} You can list link data directories by status like so:'.format(**ANSI))
  393. print(' archivebox list --status=<status> (e.g. indexed, corrupted, archived, etc.)')
  394. if orphaned:
  395. print(' {lightred}Hint:{reset} To automatically import orphaned data directories into the main index, run:'.format(**ANSI))
  396. print(' archivebox init')
  397. if num_invalid:
  398. print(' {lightred}Hint:{reset} You may need to manually remove or fix some invalid data directories, afterwards make sure to run:'.format(**ANSI))
  399. print(' archivebox init')
  400. print()
  401. print('{green}[*] Scanning recent archive changes and user logins:{reset}'.format(**ANSI))
  402. print(ANSI['lightyellow'], f' {LOGS_DIR}/*', ANSI['reset'])
  403. users = get_admins().values_list('username', flat=True)
  404. print(f' UI users {len(users)}: {", ".join(users)}')
  405. last_login = User.objects.order_by('last_login').last()
  406. print(f' Last UI login: {last_login.username} @ {str(last_login.last_login)[:16]}')
  407. last_updated = Snapshot.objects.order_by('updated').last()
  408. print(f' Last changes: {str(last_updated.updated)[:16]}')
  409. if not users:
  410. print()
  411. print(' {lightred}Hint:{reset} You can create an admin user by running:'.format(**ANSI))
  412. print(' archivebox manage createsuperuser')
  413. print()
  414. for snapshot in Snapshot.objects.order_by('-updated')[:10]:
  415. if not snapshot.updated:
  416. continue
  417. print(
  418. ANSI['black'],
  419. (
  420. f' > {str(snapshot.updated)[:16]} '
  421. f'[{snapshot.num_outputs} {("X", "√")[snapshot.is_archived]} {printable_filesize(snapshot.archive_size)}] '
  422. f'"{snapshot.title}": {snapshot.url}'
  423. )[:TERM_WIDTH()],
  424. ANSI['reset'],
  425. )
  426. print(ANSI['black'], ' ...', ANSI['reset'])
  427. @enforce_types
  428. def add(url: str,
  429. depth: int=0,
  430. update_all: bool=not ONLY_NEW,
  431. index_only: bool=False,
  432. out_dir: str=OUTPUT_DIR) -> List[Link]:
  433. """Add a new URL or list of URLs to your archive"""
  434. check_data_folder(out_dir=out_dir)
  435. base_path = save_stdin_to_sources(url, out_dir=out_dir)
  436. if depth == 1:
  437. depth_path = save_file_to_sources(url, out_dir=out_dir)
  438. check_dependencies()
  439. # Step 1: Load list of links from the existing index
  440. # merge in and dedupe new links from import_path
  441. all_links: List[Link] = []
  442. new_links: List[Link] = []
  443. all_links = load_main_index(out_dir=out_dir)
  444. all_links, new_links = import_new_links(all_links, base_path, out_dir=out_dir)
  445. if depth == 1:
  446. all_links, new_links_depth = import_new_links(all_links, depth_path, out_dir=out_dir)
  447. new_links = new_links + new_links_depth
  448. # Step 2: Write updated index with deduped old and new links back to disk
  449. write_main_index(links=all_links, out_dir=out_dir)
  450. if index_only:
  451. return all_links
  452. # Step 3: Run the archive methods for each link
  453. links = all_links if update_all else new_links
  454. log_archiving_started(len(links))
  455. idx: int = 0
  456. link: Link = None # type: ignore
  457. try:
  458. for idx, link in enumerate(links):
  459. archive_link(link, out_dir=link.link_dir)
  460. except KeyboardInterrupt:
  461. log_archiving_paused(len(links), idx, link.timestamp if link else '0')
  462. raise SystemExit(0)
  463. except:
  464. print()
  465. raise
  466. log_archiving_finished(len(links))
  467. # Step 4: Re-write links index with updated titles, icons, and resources
  468. all_links = load_main_index(out_dir=out_dir)
  469. write_main_index(links=list(all_links), out_dir=out_dir, finished=True)
  470. return all_links
  471. @enforce_types
  472. def remove(filter_str: Optional[str]=None,
  473. filter_patterns: Optional[List[str]]=None,
  474. filter_type: str='exact',
  475. after: Optional[float]=None,
  476. before: Optional[float]=None,
  477. yes: bool=False,
  478. delete: bool=False,
  479. out_dir: str=OUTPUT_DIR) -> List[Link]:
  480. """Remove the specified URLs from the archive"""
  481. check_data_folder(out_dir=out_dir)
  482. if filter_str and filter_patterns:
  483. stderr(
  484. '[X] You should pass either a pattern as an argument, '
  485. 'or pass a list of patterns via stdin, but not both.\n',
  486. color='red',
  487. )
  488. raise SystemExit(2)
  489. elif not (filter_str or filter_patterns):
  490. stderr(
  491. '[X] You should pass either a pattern as an argument, '
  492. 'or pass a list of patterns via stdin.',
  493. color='red',
  494. )
  495. stderr()
  496. stderr(' {lightred}Hint:{reset} To remove all urls you can run:'.format(**ANSI))
  497. stderr(" archivebox remove --filter-type=regex '.*'")
  498. stderr()
  499. raise SystemExit(2)
  500. elif filter_str:
  501. filter_patterns = [ptn.strip() for ptn in filter_str.split('\n')]
  502. log_list_started(filter_patterns, filter_type)
  503. timer = TimedProgress(360, prefix=' ')
  504. try:
  505. links = list(list_links(
  506. filter_patterns=filter_patterns,
  507. filter_type=filter_type,
  508. after=after,
  509. before=before,
  510. ))
  511. finally:
  512. timer.end()
  513. if not len(links):
  514. log_removal_finished(0, 0)
  515. raise SystemExit(1)
  516. log_list_finished(links)
  517. log_removal_started(links, yes=yes, delete=delete)
  518. timer = TimedProgress(360, prefix=' ')
  519. try:
  520. to_keep = []
  521. all_links = load_main_index(out_dir=out_dir)
  522. for link in all_links:
  523. should_remove = (
  524. (after is not None and float(link.timestamp) < after)
  525. or (before is not None and float(link.timestamp) > before)
  526. or link_matches_filter(link, filter_patterns, filter_type)
  527. )
  528. if not should_remove:
  529. to_keep.append(link)
  530. elif should_remove and delete:
  531. shutil.rmtree(link.link_dir, ignore_errors=True)
  532. finally:
  533. timer.end()
  534. write_main_index(links=to_keep, out_dir=out_dir, finished=True)
  535. log_removal_finished(len(all_links), len(to_keep))
  536. return to_keep
  537. @enforce_types
  538. def update(resume: Optional[float]=None,
  539. only_new: bool=ONLY_NEW,
  540. index_only: bool=False,
  541. overwrite: bool=False,
  542. filter_patterns_str: Optional[str]=None,
  543. filter_patterns: Optional[List[str]]=None,
  544. filter_type: Optional[str]=None,
  545. status: Optional[str]=None,
  546. after: Optional[str]=None,
  547. before: Optional[str]=None,
  548. out_dir: str=OUTPUT_DIR) -> List[Link]:
  549. """Import any new links from subscriptions and retry any previously failed/skipped links"""
  550. check_data_folder(out_dir=out_dir)
  551. check_dependencies()
  552. # Step 1: Load list of links from the existing index
  553. # merge in and dedupe new links from import_path
  554. all_links: List[Link] = []
  555. new_links: List[Link] = []
  556. all_links = load_main_index(out_dir=out_dir)
  557. # Step 2: Write updated index with deduped old and new links back to disk
  558. write_main_index(links=list(all_links), out_dir=out_dir)
  559. # Step 3: Filter for selected_links
  560. matching_links = list_links(
  561. filter_patterns=filter_patterns,
  562. filter_type=filter_type,
  563. before=before,
  564. after=after,
  565. )
  566. matching_folders = list_folders(
  567. links=list(matching_links),
  568. status=status,
  569. out_dir=out_dir,
  570. )
  571. all_links = [link for link in matching_folders.values() if link]
  572. if index_only:
  573. return all_links
  574. # Step 3: Run the archive methods for each link
  575. links = new_links if only_new else all_links
  576. log_archiving_started(len(links), resume)
  577. idx: int = 0
  578. link: Link = None # type: ignore
  579. try:
  580. for idx, link in enumerate(links_after_timestamp(links, resume)):
  581. archive_link(link, overwrite=overwrite, out_dir=link.link_dir)
  582. except KeyboardInterrupt:
  583. log_archiving_paused(len(links), idx, link.timestamp if link else '0')
  584. raise SystemExit(0)
  585. except:
  586. print()
  587. raise
  588. log_archiving_finished(len(links))
  589. # Step 4: Re-write links index with updated titles, icons, and resources
  590. all_links = load_main_index(out_dir=out_dir)
  591. write_main_index(links=list(all_links), out_dir=out_dir, finished=True)
  592. return all_links
  593. @enforce_types
  594. def list_all(filter_patterns_str: Optional[str]=None,
  595. filter_patterns: Optional[List[str]]=None,
  596. filter_type: str='exact',
  597. status: Optional[str]=None,
  598. after: Optional[float]=None,
  599. before: Optional[float]=None,
  600. sort: Optional[str]=None,
  601. csv: Optional[str]=None,
  602. json: bool=False,
  603. out_dir: str=OUTPUT_DIR) -> Iterable[Link]:
  604. """List, filter, and export information about archive entries"""
  605. check_data_folder(out_dir=out_dir)
  606. if filter_patterns and filter_patterns_str:
  607. stderr(
  608. '[X] You should either pass filter patterns as an arguments '
  609. 'or via stdin, but not both.\n',
  610. color='red',
  611. )
  612. raise SystemExit(2)
  613. elif filter_patterns_str:
  614. filter_patterns = filter_patterns_str.split('\n')
  615. links = list_links(
  616. filter_patterns=filter_patterns,
  617. filter_type=filter_type,
  618. before=before,
  619. after=after,
  620. )
  621. if sort:
  622. links = sorted(links, key=lambda link: getattr(link, sort))
  623. folders = list_folders(
  624. links=list(links),
  625. status=status,
  626. out_dir=out_dir,
  627. )
  628. print(printable_folders(folders, json=json, csv=csv))
  629. return folders
  630. @enforce_types
  631. def list_links(filter_patterns: Optional[List[str]]=None,
  632. filter_type: str='exact',
  633. after: Optional[float]=None,
  634. before: Optional[float]=None,
  635. out_dir: str=OUTPUT_DIR) -> Iterable[Link]:
  636. check_data_folder(out_dir=out_dir)
  637. all_links = load_main_index(out_dir=out_dir)
  638. for link in all_links:
  639. if after is not None and float(link.timestamp) < after:
  640. continue
  641. if before is not None and float(link.timestamp) > before:
  642. continue
  643. if filter_patterns:
  644. if link_matches_filter(link, filter_patterns, filter_type):
  645. yield link
  646. else:
  647. yield link
  648. @enforce_types
  649. def list_folders(links: List[Link],
  650. status: str,
  651. out_dir: str=OUTPUT_DIR) -> Dict[str, Optional[Link]]:
  652. check_data_folder(out_dir=out_dir)
  653. if status == 'indexed':
  654. return get_indexed_folders(links, out_dir=out_dir)
  655. elif status == 'archived':
  656. return get_archived_folders(links, out_dir=out_dir)
  657. elif status == 'unarchived':
  658. return get_unarchived_folders(links, out_dir=out_dir)
  659. elif status == 'present':
  660. return get_present_folders(links, out_dir=out_dir)
  661. elif status == 'valid':
  662. return get_valid_folders(links, out_dir=out_dir)
  663. elif status == 'invalid':
  664. return get_invalid_folders(links, out_dir=out_dir)
  665. elif status == 'duplicate':
  666. return get_duplicate_folders(links, out_dir=out_dir)
  667. elif status == 'orphaned':
  668. return get_orphaned_folders(links, out_dir=out_dir)
  669. elif status == 'corrupted':
  670. return get_corrupted_folders(links, out_dir=out_dir)
  671. elif status == 'unrecognized':
  672. return get_unrecognized_folders(links, out_dir=out_dir)
  673. raise ValueError('Status not recognized.')
  674. @enforce_types
  675. def config(config_options_str: Optional[str]=None,
  676. config_options: Optional[List[str]]=None,
  677. get: bool=False,
  678. set: bool=False,
  679. reset: bool=False,
  680. out_dir: str=OUTPUT_DIR) -> None:
  681. """Get and set your ArchiveBox project configuration values"""
  682. check_data_folder(out_dir=out_dir)
  683. if config_options and config_options_str:
  684. stderr(
  685. '[X] You should either pass config values as an arguments '
  686. 'or via stdin, but not both.\n',
  687. color='red',
  688. )
  689. raise SystemExit(2)
  690. elif config_options_str:
  691. config_options = config_options_str.split('\n')
  692. config_options = config_options or []
  693. no_args = not (get or set or reset or config_options)
  694. matching_config: ConfigDict = {}
  695. if get or no_args:
  696. if config_options:
  697. config_options = [get_real_name(key) for key in config_options]
  698. matching_config = {key: CONFIG[key] for key in config_options if key in CONFIG}
  699. failed_config = [key for key in config_options if key not in CONFIG]
  700. if failed_config:
  701. stderr()
  702. stderr('[X] These options failed to get', color='red')
  703. stderr(' {}'.format('\n '.join(config_options)))
  704. raise SystemExit(1)
  705. else:
  706. matching_config = CONFIG
  707. print(printable_config(matching_config))
  708. raise SystemExit(not matching_config)
  709. elif set:
  710. new_config = {}
  711. failed_options = []
  712. for line in config_options:
  713. if line.startswith('#') or not line.strip():
  714. continue
  715. if '=' not in line:
  716. stderr('[X] Config KEY=VALUE must have an = sign in it', color='red')
  717. stderr(f' {line}')
  718. raise SystemExit(2)
  719. raw_key, val = line.split('=')
  720. raw_key = raw_key.upper().strip()
  721. key = get_real_name(raw_key)
  722. if key != raw_key:
  723. stderr(f'[i] Note: The config option {raw_key} has been renamed to {key}, please use the new name going forwards.', color='lightyellow')
  724. if key in CONFIG:
  725. new_config[key] = val.strip()
  726. else:
  727. failed_options.append(line)
  728. if new_config:
  729. before = CONFIG
  730. matching_config = write_config_file(new_config, out_dir=OUTPUT_DIR)
  731. after = load_all_config()
  732. print(printable_config(matching_config))
  733. side_effect_changes: ConfigDict = {}
  734. for key, val in after.items():
  735. if key in USER_CONFIG and (before[key] != after[key]) and (key not in matching_config):
  736. side_effect_changes[key] = after[key]
  737. if side_effect_changes:
  738. stderr()
  739. stderr('[i] Note: This change also affected these other options that depended on it:', color='lightyellow')
  740. print(' {}'.format(printable_config(side_effect_changes, prefix=' ')))
  741. if failed_options:
  742. stderr()
  743. stderr('[X] These options failed to set (check for typos):', color='red')
  744. stderr(' {}'.format('\n '.join(failed_options)))
  745. raise SystemExit(bool(failed_options))
  746. elif reset:
  747. stderr('[X] This command is not implemented yet.', color='red')
  748. stderr(' Please manually remove the relevant lines from your config file:')
  749. stderr(f' {CONFIG_FILE}')
  750. raise SystemExit(2)
  751. else:
  752. stderr('[X] You must pass either --get or --set, or no arguments to get the whole config.', color='red')
  753. stderr(' archivebox config')
  754. stderr(' archivebox config --get SOME_KEY')
  755. stderr(' archivebox config --set SOME_KEY=SOME_VALUE')
  756. raise SystemExit(2)
  757. @enforce_types
  758. def schedule(add: bool=False,
  759. show: bool=False,
  760. clear: bool=False,
  761. foreground: bool=False,
  762. run_all: bool=False,
  763. quiet: bool=False,
  764. every: Optional[str]=None,
  765. import_path: Optional[str]=None,
  766. out_dir: str=OUTPUT_DIR):
  767. """Set ArchiveBox to regularly import URLs at specific times using cron"""
  768. check_data_folder(out_dir=out_dir)
  769. os.makedirs(os.path.join(out_dir, LOGS_DIR_NAME), exist_ok=True)
  770. cron = CronTab(user=True)
  771. cron = dedupe_cron_jobs(cron)
  772. existing_jobs = list(cron.find_comment(CRON_COMMENT))
  773. if foreground or run_all:
  774. if import_path or (not existing_jobs):
  775. stderr('{red}[X] You must schedule some jobs first before running in foreground mode.{reset}'.format(**ANSI))
  776. stderr(' archivebox schedule --every=hour https://example.com/some/rss/feed.xml')
  777. raise SystemExit(1)
  778. print('{green}[*] Running {} ArchiveBox jobs in foreground task scheduler...{reset}'.format(len(existing_jobs), **ANSI))
  779. if run_all:
  780. try:
  781. for job in existing_jobs:
  782. sys.stdout.write(f' > {job.command}')
  783. sys.stdout.flush()
  784. job.run()
  785. sys.stdout.write(f'\r √ {job.command}\n')
  786. except KeyboardInterrupt:
  787. print('\n{green}[√] Stopped.{reset}'.format(**ANSI))
  788. raise SystemExit(1)
  789. if foreground:
  790. try:
  791. for result in cron.run_scheduler():
  792. print(result)
  793. except KeyboardInterrupt:
  794. print('\n{green}[√] Stopped.{reset}'.format(**ANSI))
  795. raise SystemExit(1)
  796. elif show:
  797. if existing_jobs:
  798. print('\n'.join(str(cmd) for cmd in existing_jobs))
  799. else:
  800. stderr('{red}[X] There are no ArchiveBox cron jobs scheduled for your user ({}).{reset}'.format(USER, **ANSI))
  801. stderr(' To schedule a new job, run:')
  802. stderr(' archivebox schedule --every=[timeperiod] https://example.com/some/rss/feed.xml')
  803. raise SystemExit(0)
  804. elif clear:
  805. print(cron.remove_all(comment=CRON_COMMENT))
  806. cron.write()
  807. raise SystemExit(0)
  808. elif every:
  809. quoted = lambda s: f'"{s}"' if s and ' ' in s else s
  810. cmd = [
  811. 'cd',
  812. quoted(out_dir),
  813. '&&',
  814. quoted(ARCHIVEBOX_BINARY),
  815. *(['add', f'"{import_path}"'] if import_path else ['update']),
  816. '2>&1',
  817. '>',
  818. quoted(os.path.join(LOGS_DIR, 'archivebox.log')),
  819. ]
  820. new_job = cron.new(command=' '.join(cmd), comment=CRON_COMMENT)
  821. if every in ('minute', 'hour', 'day', 'week', 'month', 'year'):
  822. set_every = getattr(new_job.every(), every)
  823. set_every()
  824. elif CronSlices.is_valid(every):
  825. new_job.setall(every)
  826. else:
  827. stderr('{red}[X] Got invalid timeperiod for cron task.{reset}'.format(**ANSI))
  828. stderr(' It must be one of minute/hour/day/week/month')
  829. stderr(' or a quoted cron-format schedule like:')
  830. stderr(' archivebox init --every=day https://example.com/some/rss/feed.xml')
  831. stderr(' archivebox init --every="0/5 * * * *" https://example.com/some/rss/feed.xml')
  832. raise SystemExit(1)
  833. cron = dedupe_cron_jobs(cron)
  834. cron.write()
  835. total_runs = sum(j.frequency_per_year() for j in cron)
  836. existing_jobs = list(cron.find_comment(CRON_COMMENT))
  837. print()
  838. print('{green}[√] Scheduled new ArchiveBox cron job for user: {} ({} jobs are active).{reset}'.format(USER, len(existing_jobs), **ANSI))
  839. print('\n'.join(f' > {cmd}' if str(cmd) == str(new_job) else f' {cmd}' for cmd in existing_jobs))
  840. if total_runs > 60 and not quiet:
  841. stderr()
  842. stderr('{lightyellow}[!] With the current cron config, ArchiveBox is estimated to run >{} times per year.{reset}'.format(total_runs, **ANSI))
  843. stderr(' Congrats on being an enthusiastic internet archiver! 👌')
  844. stderr()
  845. stderr(' Make sure you have enough storage space available to hold all the data.')
  846. stderr(' Using a compressed/deduped filesystem like ZFS is recommended if you plan on archiving a lot.')
  847. raise SystemExit(0)
  848. @enforce_types
  849. def server(runserver_args: Optional[List[str]]=None,
  850. reload: bool=False,
  851. debug: bool=False,
  852. out_dir: str=OUTPUT_DIR) -> None:
  853. """Run the ArchiveBox HTTP server"""
  854. runserver_args = runserver_args or []
  855. check_data_folder(out_dir=out_dir)
  856. if debug:
  857. os.environ['DEBUG'] = 'True'
  858. else:
  859. runserver_args.append('--insecure')
  860. setup_django(out_dir)
  861. from django.core.management import call_command
  862. from django.contrib.auth.models import User
  863. if IS_TTY and not User.objects.filter(is_superuser=True).exists():
  864. print('{lightyellow}[!] No admin users exist yet, you will not be able to edit links in the UI.{reset}'.format(**ANSI))
  865. print()
  866. print(' To create an admin user, run:')
  867. print(' archivebox manage createsuperuser')
  868. print()
  869. print('{green}[+] Starting ArchiveBox webserver...{reset}'.format(**ANSI))
  870. if not reload:
  871. runserver_args.append('--noreload')
  872. call_command("runserver", *runserver_args)
  873. @enforce_types
  874. def manage(args: Optional[List[str]]=None, out_dir: str=OUTPUT_DIR) -> None:
  875. """Run an ArchiveBox Django management command"""
  876. check_data_folder(out_dir=out_dir)
  877. setup_django(out_dir)
  878. from django.core.management import execute_from_command_line
  879. execute_from_command_line([f'{ARCHIVEBOX_BINARY} manage', *(args or ['help'])])
  880. @enforce_types
  881. def shell(out_dir: str=OUTPUT_DIR) -> None:
  882. """Enter an interactive ArchiveBox Django shell"""
  883. check_data_folder(out_dir=out_dir)
  884. setup_django(OUTPUT_DIR)
  885. from django.core.management import call_command
  886. call_command("shell_plus")