main.py 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335
  1. __package__ = 'archivebox'
  2. import os
  3. import sys
  4. import shutil
  5. import platform
  6. from pathlib import Path
  7. from datetime import date
  8. from typing import Dict, List, Optional, Iterable, IO, Union
  9. from crontab import CronTab, CronSlices
  10. from django.db.models import QuerySet
  11. from .cli import (
  12. list_subcommands,
  13. run_subcommand,
  14. display_first,
  15. meta_cmds,
  16. main_cmds,
  17. archive_cmds,
  18. )
  19. from .parsers import (
  20. save_text_as_source,
  21. save_file_as_source,
  22. parse_links_memory,
  23. )
  24. from .index.schema import Link
  25. from .util import enforce_types # type: ignore
  26. from .system import get_dir_size, dedupe_cron_jobs, CRON_COMMENT
  27. from .system import run as run_shell
  28. from .index import (
  29. load_main_index,
  30. parse_links_from_source,
  31. dedupe_links,
  32. write_main_index,
  33. snapshot_filter,
  34. get_indexed_folders,
  35. get_archived_folders,
  36. get_unarchived_folders,
  37. get_present_folders,
  38. get_valid_folders,
  39. get_invalid_folders,
  40. get_duplicate_folders,
  41. get_orphaned_folders,
  42. get_corrupted_folders,
  43. get_unrecognized_folders,
  44. fix_invalid_folder_locations,
  45. write_link_details,
  46. )
  47. from .index.json import (
  48. parse_json_main_index,
  49. parse_json_links_details,
  50. generate_json_index_from_links,
  51. )
  52. from .index.sql import (
  53. get_admins,
  54. apply_migrations,
  55. remove_from_sql_main_index,
  56. )
  57. from .index.html import (
  58. generate_index_from_links,
  59. )
  60. from .index.csv import links_to_csv
  61. from .extractors import archive_links, archive_link, ignore_methods
  62. from .config import (
  63. stderr,
  64. hint,
  65. ConfigDict,
  66. ANSI,
  67. IS_TTY,
  68. DEBUG,
  69. IN_DOCKER,
  70. USER,
  71. PYTHON_BINARY,
  72. ARCHIVEBOX_BINARY,
  73. ONLY_NEW,
  74. OUTPUT_DIR,
  75. SOURCES_DIR,
  76. ARCHIVE_DIR,
  77. LOGS_DIR,
  78. PACKAGE_DIR,
  79. CONFIG_FILE,
  80. CONFIG_FILENAME,
  81. ARCHIVE_DIR_NAME,
  82. SOURCES_DIR_NAME,
  83. LOGS_DIR_NAME,
  84. JSON_INDEX_FILENAME,
  85. HTML_INDEX_FILENAME,
  86. SQL_INDEX_FILENAME,
  87. ROBOTS_TXT_FILENAME,
  88. FAVICON_FILENAME,
  89. SEARCH_BACKEND_ENGINE,
  90. check_dependencies,
  91. check_data_folder,
  92. write_config_file,
  93. VERSION,
  94. CODE_LOCATIONS,
  95. EXTERNAL_LOCATIONS,
  96. DATA_LOCATIONS,
  97. DEPENDENCIES,
  98. USE_CHROME,
  99. CHROME_BINARY,
  100. CHROME_VERSION,
  101. YOUTUBEDL_BINARY,
  102. YOUTUBEDL_VERSION,
  103. SINGLEFILE_VERSION,
  104. READABILITY_VERSION,
  105. MERCURY_VERSION,
  106. USE_YOUTUBEDL,
  107. USE_NODE,
  108. NODE_VERSION,
  109. load_all_config,
  110. CONFIG,
  111. USER_CONFIG,
  112. get_real_name,
  113. setup_django,
  114. )
  115. from .logging_util import (
  116. TERM_WIDTH,
  117. TimedProgress,
  118. log_importing_started,
  119. log_crawl_started,
  120. log_removal_started,
  121. log_removal_finished,
  122. log_list_started,
  123. log_list_finished,
  124. printable_config,
  125. printable_folders,
  126. printable_filesize,
  127. printable_folder_status,
  128. printable_dependency_version,
  129. )
  130. from .search import flush_search_index, index_links
  131. ALLOWED_IN_OUTPUT_DIR = {
  132. '.gitignore',
  133. 'lost+found',
  134. '.DS_Store',
  135. '.venv',
  136. 'venv',
  137. 'virtualenv',
  138. '.virtualenv',
  139. 'node_modules',
  140. 'package.json',
  141. 'package-lock.json',
  142. 'yarn.lock',
  143. 'static',
  144. 'sonic',
  145. ARCHIVE_DIR_NAME,
  146. SOURCES_DIR_NAME,
  147. LOGS_DIR_NAME,
  148. SQL_INDEX_FILENAME,
  149. f'{SQL_INDEX_FILENAME}-wal',
  150. f'{SQL_INDEX_FILENAME}-shm',
  151. JSON_INDEX_FILENAME,
  152. HTML_INDEX_FILENAME,
  153. ROBOTS_TXT_FILENAME,
  154. FAVICON_FILENAME,
  155. CONFIG_FILENAME,
  156. f'{CONFIG_FILENAME}.bak',
  157. }
  158. @enforce_types
  159. def help(out_dir: Path=OUTPUT_DIR) -> None:
  160. """Print the ArchiveBox help message and usage"""
  161. all_subcommands = list_subcommands()
  162. COMMANDS_HELP_TEXT = '\n '.join(
  163. f'{cmd.ljust(20)} {summary}'
  164. for cmd, summary in all_subcommands.items()
  165. if cmd in meta_cmds
  166. ) + '\n\n ' + '\n '.join(
  167. f'{cmd.ljust(20)} {summary}'
  168. for cmd, summary in all_subcommands.items()
  169. if cmd in main_cmds
  170. ) + '\n\n ' + '\n '.join(
  171. f'{cmd.ljust(20)} {summary}'
  172. for cmd, summary in all_subcommands.items()
  173. if cmd in archive_cmds
  174. ) + '\n\n ' + '\n '.join(
  175. f'{cmd.ljust(20)} {summary}'
  176. for cmd, summary in all_subcommands.items()
  177. if cmd not in display_first
  178. )
  179. if (Path(out_dir) / SQL_INDEX_FILENAME).exists():
  180. print('''{green}ArchiveBox v{}: The self-hosted internet archive.{reset}
  181. {lightred}Active data directory:{reset}
  182. {}
  183. {lightred}Usage:{reset}
  184. archivebox [command] [--help] [--version] [...args]
  185. {lightred}Commands:{reset}
  186. {}
  187. {lightred}Example Use:{reset}
  188. mkdir my-archive; cd my-archive/
  189. archivebox init
  190. archivebox status
  191. archivebox add https://example.com/some/page
  192. archivebox add --depth=1 ~/Downloads/bookmarks_export.html
  193. archivebox list --sort=timestamp --csv=timestamp,url,is_archived
  194. archivebox schedule --every=day https://example.com/some/feed.rss
  195. archivebox update --resume=15109948213.123
  196. {lightred}Documentation:{reset}
  197. https://github.com/ArchiveBox/ArchiveBox/wiki
  198. '''.format(VERSION, out_dir, COMMANDS_HELP_TEXT, **ANSI))
  199. else:
  200. print('{green}Welcome to ArchiveBox v{}!{reset}'.format(VERSION, **ANSI))
  201. print()
  202. if IN_DOCKER:
  203. print('When using Docker, you need to mount a volume to use as your data dir:')
  204. print(' docker run -v /some/path:/data archivebox ...')
  205. print()
  206. print('To import an existing archive (from a previous version of ArchiveBox):')
  207. print(' 1. cd into your data dir OUTPUT_DIR (usually ArchiveBox/output) and run:')
  208. print(' 2. archivebox init')
  209. print()
  210. print('To start a new archive:')
  211. print(' 1. Create an empty directory, then cd into it and run:')
  212. print(' 2. archivebox init')
  213. print()
  214. print('For more information, see the documentation here:')
  215. print(' https://github.com/ArchiveBox/ArchiveBox/wiki')
  216. @enforce_types
  217. def version(quiet: bool=False,
  218. out_dir: Path=OUTPUT_DIR) -> None:
  219. """Print the ArchiveBox version and dependency information"""
  220. if quiet:
  221. print(VERSION)
  222. else:
  223. # ArchiveBox v0.5.6
  224. # Cpython Linux Linux-4.19.121-linuxkit-x86_64-with-glibc2.28 x86_64 (in Docker) (in TTY)
  225. print('ArchiveBox v{}'.format(VERSION))
  226. p = platform.uname()
  227. print(
  228. sys.implementation.name.title(),
  229. p.system,
  230. platform.platform(),
  231. p.machine,
  232. )
  233. print(
  234. f'IN_DOCKER={IN_DOCKER}',
  235. f'DEBUG={DEBUG}',
  236. f'IS_TTY={IS_TTY}',
  237. f'TZ={os.environ.get("TZ", "UTC")}',
  238. f'SEARCH_BACKEND_ENGINE={SEARCH_BACKEND_ENGINE}',
  239. )
  240. print()
  241. print('{white}[i] Dependency versions:{reset}'.format(**ANSI))
  242. for name, dependency in DEPENDENCIES.items():
  243. print(printable_dependency_version(name, dependency))
  244. print()
  245. print('{white}[i] Source-code locations:{reset}'.format(**ANSI))
  246. for name, folder in CODE_LOCATIONS.items():
  247. print(printable_folder_status(name, folder))
  248. print()
  249. print('{white}[i] Secrets locations:{reset}'.format(**ANSI))
  250. for name, folder in EXTERNAL_LOCATIONS.items():
  251. print(printable_folder_status(name, folder))
  252. print()
  253. if DATA_LOCATIONS['OUTPUT_DIR']['is_valid']:
  254. print('{white}[i] Data locations:{reset}'.format(**ANSI))
  255. for name, folder in DATA_LOCATIONS.items():
  256. print(printable_folder_status(name, folder))
  257. else:
  258. print()
  259. print('{white}[i] Data locations:{reset}'.format(**ANSI))
  260. print()
  261. check_dependencies()
  262. @enforce_types
  263. def run(subcommand: str,
  264. subcommand_args: Optional[List[str]],
  265. stdin: Optional[IO]=None,
  266. out_dir: Path=OUTPUT_DIR) -> None:
  267. """Run a given ArchiveBox subcommand with the given list of args"""
  268. run_subcommand(
  269. subcommand=subcommand,
  270. subcommand_args=subcommand_args,
  271. stdin=stdin,
  272. pwd=out_dir,
  273. )
  274. @enforce_types
  275. def init(force: bool=False, quick: bool=False, setup: bool=False, out_dir: Path=OUTPUT_DIR) -> None:
  276. """Initialize a new ArchiveBox collection in the current directory"""
  277. from core.models import Snapshot
  278. out_dir.mkdir(exist_ok=True)
  279. is_empty = not len(set(os.listdir(out_dir)) - ALLOWED_IN_OUTPUT_DIR)
  280. if (out_dir / JSON_INDEX_FILENAME).exists():
  281. stderr("[!] This folder contains a JSON index. It is deprecated, and will no longer be kept up to date automatically.", color="lightyellow")
  282. stderr(" You can run `archivebox list --json --with-headers > index.json` to manually generate it.", color="lightyellow")
  283. existing_index = (out_dir / SQL_INDEX_FILENAME).exists()
  284. if is_empty and not existing_index:
  285. print('{green}[+] Initializing a new ArchiveBox v{} collection...{reset}'.format(VERSION, **ANSI))
  286. print('{green}----------------------------------------------------------------------{reset}'.format(**ANSI))
  287. elif existing_index:
  288. # TODO: properly detect and print the existing version in current index as well
  289. print('{green}[^] Verifying and updating existing ArchiveBox collection to v{}...{reset}'.format(VERSION, **ANSI))
  290. print('{green}----------------------------------------------------------------------{reset}'.format(**ANSI))
  291. else:
  292. if force:
  293. stderr('[!] This folder appears to already have files in it, but no index.sqlite3 is present.', color='lightyellow')
  294. stderr(' Because --force was passed, ArchiveBox will initialize anyway (which may overwrite existing files).')
  295. else:
  296. stderr(
  297. ("{red}[X] This folder appears to already have files in it, but no index.sqlite3 present.{reset}\n\n"
  298. " You must run init in a completely empty directory, or an existing data folder.\n\n"
  299. " {lightred}Hint:{reset} To import an existing data folder make sure to cd into the folder first, \n"
  300. " then run and run 'archivebox init' to pick up where you left off.\n\n"
  301. " (Always make sure your data folder is backed up first before updating ArchiveBox)"
  302. ).format(out_dir, **ANSI)
  303. )
  304. raise SystemExit(2)
  305. if existing_index:
  306. print('\n{green}[*] Verifying archive folder structure...{reset}'.format(**ANSI))
  307. else:
  308. print('\n{green}[+] Building archive folder structure...{reset}'.format(**ANSI))
  309. print(f' + ./{ARCHIVE_DIR.relative_to(OUTPUT_DIR)}, ./{SOURCES_DIR.relative_to(OUTPUT_DIR)}, ./{LOGS_DIR.relative_to(OUTPUT_DIR)}...')
  310. Path(SOURCES_DIR).mkdir(exist_ok=True)
  311. Path(ARCHIVE_DIR).mkdir(exist_ok=True)
  312. Path(LOGS_DIR).mkdir(exist_ok=True)
  313. print(f' + ./{CONFIG_FILE.relative_to(OUTPUT_DIR)}...')
  314. write_config_file({}, out_dir=out_dir)
  315. if (out_dir / SQL_INDEX_FILENAME).exists():
  316. print('\n{green}[*] Verifying main SQL index and running any migrations needed...{reset}'.format(**ANSI))
  317. else:
  318. print('\n{green}[+] Building main SQL index and running initial migrations...{reset}'.format(**ANSI))
  319. DATABASE_FILE = out_dir / SQL_INDEX_FILENAME
  320. for migration_line in apply_migrations(out_dir):
  321. print(f' {migration_line}')
  322. assert DATABASE_FILE.exists()
  323. print()
  324. print(f' √ ./{DATABASE_FILE.relative_to(OUTPUT_DIR)}')
  325. # from django.contrib.auth.models import User
  326. # if IS_TTY and not User.objects.filter(is_superuser=True).exists():
  327. # print('{green}[+] Creating admin user account...{reset}'.format(**ANSI))
  328. # call_command("createsuperuser", interactive=True)
  329. print()
  330. print('{green}[*] Checking links from indexes and archive folders (safe to Ctrl+C)...{reset}'.format(**ANSI))
  331. all_links = Snapshot.objects.none()
  332. pending_links: Dict[str, Link] = {}
  333. if existing_index:
  334. all_links = load_main_index(out_dir=out_dir, warn=False)
  335. print(' √ Loaded {} links from existing main index.'.format(all_links.count()))
  336. if quick:
  337. print(' > Skipping full snapshot directory check (quick mode)')
  338. else:
  339. try:
  340. # Links in data folders that dont match their timestamp
  341. fixed, cant_fix = fix_invalid_folder_locations(out_dir=out_dir)
  342. if fixed:
  343. print(' {lightyellow}√ Fixed {} data directory locations that didn\'t match their link timestamps.{reset}'.format(len(fixed), **ANSI))
  344. if cant_fix:
  345. print(' {lightyellow}! Could not fix {} data directory locations due to conflicts with existing folders.{reset}'.format(len(cant_fix), **ANSI))
  346. # Links in JSON index but not in main index
  347. orphaned_json_links = {
  348. link.url: link
  349. for link in parse_json_main_index(out_dir)
  350. if not all_links.filter(url=link.url).exists()
  351. }
  352. if orphaned_json_links:
  353. pending_links.update(orphaned_json_links)
  354. print(' {lightyellow}√ Added {} orphaned links from existing JSON index...{reset}'.format(len(orphaned_json_links), **ANSI))
  355. # Links in data dir indexes but not in main index
  356. orphaned_data_dir_links = {
  357. link.url: link
  358. for link in parse_json_links_details(out_dir)
  359. if not all_links.filter(url=link.url).exists()
  360. }
  361. if orphaned_data_dir_links:
  362. pending_links.update(orphaned_data_dir_links)
  363. print(' {lightyellow}√ Added {} orphaned links from existing archive directories.{reset}'.format(len(orphaned_data_dir_links), **ANSI))
  364. # Links in invalid/duplicate data dirs
  365. invalid_folders = {
  366. folder: link
  367. for folder, link in get_invalid_folders(all_links, out_dir=out_dir).items()
  368. }
  369. if invalid_folders:
  370. print(' {lightyellow}! Skipped adding {} invalid link data directories.{reset}'.format(len(invalid_folders), **ANSI))
  371. print(' X ' + '\n X '.join(f'./{Path(folder).relative_to(OUTPUT_DIR)} {link}' for folder, link in invalid_folders.items()))
  372. print()
  373. print(' {lightred}Hint:{reset} For more information about the link data directories that were skipped, run:'.format(**ANSI))
  374. print(' archivebox status')
  375. print(' archivebox list --status=invalid')
  376. except (KeyboardInterrupt, SystemExit):
  377. stderr()
  378. stderr('[x] Stopped checking archive directories due to Ctrl-C/SIGTERM', color='red')
  379. stderr(' Your archive data is safe, but you should re-run `archivebox init` to finish the process later.')
  380. stderr()
  381. stderr(' {lightred}Hint:{reset} In the future you can run a quick init without checking dirs like so:'.format(**ANSI))
  382. stderr(' archivebox init --quick')
  383. raise SystemExit(1)
  384. write_main_index(list(pending_links.values()), out_dir=out_dir)
  385. print('\n{green}----------------------------------------------------------------------{reset}'.format(**ANSI))
  386. if existing_index:
  387. print('{green}[√] Done. Verified and updated the existing ArchiveBox collection.{reset}'.format(**ANSI))
  388. else:
  389. print('{green}[√] Done. A new ArchiveBox collection was initialized ({} links).{reset}'.format(len(all_links) + len(pending_links), **ANSI))
  390. json_index = out_dir / JSON_INDEX_FILENAME
  391. html_index = out_dir / HTML_INDEX_FILENAME
  392. index_name = f"{date.today()}_index_old"
  393. if json_index.exists():
  394. json_index.rename(f"{index_name}.json")
  395. if html_index.exists():
  396. html_index.rename(f"{index_name}.html")
  397. if setup:
  398. run_subcommand('setup', pwd=out_dir)
  399. if Snapshot.objects.count() < 25: # hide the hints for experienced users
  400. print()
  401. print(' {lightred}Hint:{reset} To view your archive index, run:'.format(**ANSI))
  402. print(' archivebox server # then visit http://127.0.0.1:8000')
  403. print()
  404. print(' To add new links, you can run:')
  405. print(" archivebox add ~/some/path/or/url/to/list_of_links.txt")
  406. print()
  407. print(' For more usage and examples, run:')
  408. print(' archivebox help')
  409. @enforce_types
  410. def status(out_dir: Path=OUTPUT_DIR) -> None:
  411. """Print out some info and statistics about the archive collection"""
  412. check_data_folder(out_dir=out_dir)
  413. from core.models import Snapshot
  414. from django.contrib.auth import get_user_model
  415. User = get_user_model()
  416. print('{green}[*] Scanning archive main index...{reset}'.format(**ANSI))
  417. print(ANSI['lightyellow'], f' {out_dir}/*', ANSI['reset'])
  418. num_bytes, num_dirs, num_files = get_dir_size(out_dir, recursive=False, pattern='index.')
  419. size = printable_filesize(num_bytes)
  420. print(f' Index size: {size} across {num_files} files')
  421. print()
  422. links = load_main_index(out_dir=out_dir)
  423. num_sql_links = links.count()
  424. num_link_details = sum(1 for link in parse_json_links_details(out_dir=out_dir))
  425. print(f' > SQL Main Index: {num_sql_links} links'.ljust(36), f'(found in {SQL_INDEX_FILENAME})')
  426. print(f' > JSON Link Details: {num_link_details} links'.ljust(36), f'(found in {ARCHIVE_DIR_NAME}/*/index.json)')
  427. print()
  428. print('{green}[*] Scanning archive data directories...{reset}'.format(**ANSI))
  429. print(ANSI['lightyellow'], f' {ARCHIVE_DIR}/*', ANSI['reset'])
  430. num_bytes, num_dirs, num_files = get_dir_size(ARCHIVE_DIR)
  431. size = printable_filesize(num_bytes)
  432. print(f' Size: {size} across {num_files} files in {num_dirs} directories')
  433. print(ANSI['black'])
  434. num_indexed = len(get_indexed_folders(links, out_dir=out_dir))
  435. num_archived = len(get_archived_folders(links, out_dir=out_dir))
  436. num_unarchived = len(get_unarchived_folders(links, out_dir=out_dir))
  437. print(f' > indexed: {num_indexed}'.ljust(36), f'({get_indexed_folders.__doc__})')
  438. print(f' > archived: {num_archived}'.ljust(36), f'({get_archived_folders.__doc__})')
  439. print(f' > unarchived: {num_unarchived}'.ljust(36), f'({get_unarchived_folders.__doc__})')
  440. num_present = len(get_present_folders(links, out_dir=out_dir))
  441. num_valid = len(get_valid_folders(links, out_dir=out_dir))
  442. print()
  443. print(f' > present: {num_present}'.ljust(36), f'({get_present_folders.__doc__})')
  444. print(f' > valid: {num_valid}'.ljust(36), f'({get_valid_folders.__doc__})')
  445. duplicate = get_duplicate_folders(links, out_dir=out_dir)
  446. orphaned = get_orphaned_folders(links, out_dir=out_dir)
  447. corrupted = get_corrupted_folders(links, out_dir=out_dir)
  448. unrecognized = get_unrecognized_folders(links, out_dir=out_dir)
  449. num_invalid = len({**duplicate, **orphaned, **corrupted, **unrecognized})
  450. print(f' > invalid: {num_invalid}'.ljust(36), f'({get_invalid_folders.__doc__})')
  451. print(f' > duplicate: {len(duplicate)}'.ljust(36), f'({get_duplicate_folders.__doc__})')
  452. print(f' > orphaned: {len(orphaned)}'.ljust(36), f'({get_orphaned_folders.__doc__})')
  453. print(f' > corrupted: {len(corrupted)}'.ljust(36), f'({get_corrupted_folders.__doc__})')
  454. print(f' > unrecognized: {len(unrecognized)}'.ljust(36), f'({get_unrecognized_folders.__doc__})')
  455. print(ANSI['reset'])
  456. if num_indexed:
  457. print(' {lightred}Hint:{reset} You can list link data directories by status like so:'.format(**ANSI))
  458. print(' archivebox list --status=<status> (e.g. indexed, corrupted, archived, etc.)')
  459. if orphaned:
  460. print(' {lightred}Hint:{reset} To automatically import orphaned data directories into the main index, run:'.format(**ANSI))
  461. print(' archivebox init')
  462. if num_invalid:
  463. print(' {lightred}Hint:{reset} You may need to manually remove or fix some invalid data directories, afterwards make sure to run:'.format(**ANSI))
  464. print(' archivebox init')
  465. print()
  466. print('{green}[*] Scanning recent archive changes and user logins:{reset}'.format(**ANSI))
  467. print(ANSI['lightyellow'], f' {LOGS_DIR}/*', ANSI['reset'])
  468. users = get_admins().values_list('username', flat=True)
  469. print(f' UI users {len(users)}: {", ".join(users)}')
  470. last_login = User.objects.order_by('last_login').last()
  471. if last_login:
  472. print(f' Last UI login: {last_login.username} @ {str(last_login.last_login)[:16]}')
  473. last_updated = Snapshot.objects.order_by('updated').last()
  474. if last_updated:
  475. print(f' Last changes: {str(last_updated.updated)[:16]}')
  476. if not users:
  477. print()
  478. print(' {lightred}Hint:{reset} You can create an admin user by running:'.format(**ANSI))
  479. print(' archivebox manage createsuperuser')
  480. print()
  481. for snapshot in links.order_by('-updated')[:10]:
  482. if not snapshot.updated:
  483. continue
  484. print(
  485. ANSI['black'],
  486. (
  487. f' > {str(snapshot.updated)[:16]} '
  488. f'[{snapshot.num_outputs} {("X", "√")[snapshot.is_archived]} {printable_filesize(snapshot.archive_size)}] '
  489. f'"{snapshot.title}": {snapshot.url}'
  490. )[:TERM_WIDTH()],
  491. ANSI['reset'],
  492. )
  493. print(ANSI['black'], ' ...', ANSI['reset'])
  494. @enforce_types
  495. def oneshot(url: str, extractors: str="", out_dir: Path=OUTPUT_DIR):
  496. """
  497. Create a single URL archive folder with an index.json and index.html, and all the archive method outputs.
  498. You can run this to archive single pages without needing to create a whole collection with archivebox init.
  499. """
  500. oneshot_link, _ = parse_links_memory([url])
  501. if len(oneshot_link) > 1:
  502. stderr(
  503. '[X] You should pass a single url to the oneshot command',
  504. color='red'
  505. )
  506. raise SystemExit(2)
  507. methods = extractors.split(",") if extractors else ignore_methods(['title'])
  508. archive_link(oneshot_link[0], out_dir=out_dir, methods=methods)
  509. return oneshot_link
  510. @enforce_types
  511. def add(urls: Union[str, List[str]],
  512. tag: str='',
  513. depth: int=0,
  514. update_all: bool=not ONLY_NEW,
  515. index_only: bool=False,
  516. overwrite: bool=False,
  517. init: bool=False,
  518. extractors: str="",
  519. parser: str="auto",
  520. out_dir: Path=OUTPUT_DIR) -> List[Link]:
  521. """Add a new URL or list of URLs to your archive"""
  522. from core.models import Tag
  523. assert depth in (0, 1), 'Depth must be 0 or 1 (depth >1 is not supported yet)'
  524. extractors = extractors.split(",") if extractors else []
  525. if init:
  526. run_subcommand('init', stdin=None, pwd=out_dir)
  527. # Load list of links from the existing index
  528. check_data_folder(out_dir=out_dir)
  529. check_dependencies()
  530. new_links: List[Link] = []
  531. all_links = load_main_index(out_dir=out_dir)
  532. log_importing_started(urls=urls, depth=depth, index_only=index_only)
  533. if isinstance(urls, str):
  534. # save verbatim stdin to sources
  535. write_ahead_log = save_text_as_source(urls, filename='{ts}-import.txt', out_dir=out_dir)
  536. elif isinstance(urls, list):
  537. # save verbatim args to sources
  538. write_ahead_log = save_text_as_source('\n'.join(urls), filename='{ts}-import.txt', out_dir=out_dir)
  539. new_links += parse_links_from_source(write_ahead_log, root_url=None, parser=parser)
  540. # If we're going one level deeper, download each link and look for more links
  541. new_links_depth = []
  542. if new_links and depth == 1:
  543. log_crawl_started(new_links)
  544. for new_link in new_links:
  545. downloaded_file = save_file_as_source(new_link.url, filename=f'{new_link.timestamp}-crawl-{new_link.domain}.txt', out_dir=out_dir)
  546. new_links_depth += parse_links_from_source(downloaded_file, root_url=new_link.url)
  547. imported_links = list({link.url: link for link in (new_links + new_links_depth)}.values())
  548. new_links = dedupe_links(all_links, imported_links)
  549. write_main_index(links=new_links, out_dir=out_dir)
  550. all_links = load_main_index(out_dir=out_dir)
  551. if index_only:
  552. # mock archive all the links using the fake index_only extractor method in order to update their state
  553. if overwrite:
  554. archive_links(imported_links, overwrite=overwrite, methods=['index_only'], out_dir=out_dir)
  555. else:
  556. archive_links(new_links, overwrite=False, methods=['index_only'], out_dir=out_dir)
  557. else:
  558. # fully run the archive extractor methods for each link
  559. archive_kwargs = {
  560. "out_dir": out_dir,
  561. }
  562. if extractors:
  563. archive_kwargs["methods"] = extractors
  564. if update_all:
  565. archive_links(all_links, overwrite=overwrite, **archive_kwargs)
  566. elif overwrite:
  567. archive_links(imported_links, overwrite=True, **archive_kwargs)
  568. elif new_links:
  569. archive_links(new_links, overwrite=False, **archive_kwargs)
  570. # add any tags to imported links
  571. tags = [
  572. Tag.objects.get_or_create(name=name.strip())[0]
  573. for name in tag.split(',')
  574. if name.strip()
  575. ]
  576. if tags:
  577. for link in imported_links:
  578. snapshot = link.as_snapshot()
  579. snapshot.tags.add(*tags)
  580. snapshot.tags_str(nocache=True)
  581. snapshot.save()
  582. # print(f' √ Tagged {len(imported_links)} Snapshots with {len(tags)} tags {tags_str}')
  583. return all_links
  584. @enforce_types
  585. def remove(filter_str: Optional[str]=None,
  586. filter_patterns: Optional[List[str]]=None,
  587. filter_type: str='exact',
  588. snapshots: Optional[QuerySet]=None,
  589. after: Optional[float]=None,
  590. before: Optional[float]=None,
  591. yes: bool=False,
  592. delete: bool=False,
  593. out_dir: Path=OUTPUT_DIR) -> List[Link]:
  594. """Remove the specified URLs from the archive"""
  595. check_data_folder(out_dir=out_dir)
  596. if snapshots is None:
  597. if filter_str and filter_patterns:
  598. stderr(
  599. '[X] You should pass either a pattern as an argument, '
  600. 'or pass a list of patterns via stdin, but not both.\n',
  601. color='red',
  602. )
  603. raise SystemExit(2)
  604. elif not (filter_str or filter_patterns):
  605. stderr(
  606. '[X] You should pass either a pattern as an argument, '
  607. 'or pass a list of patterns via stdin.',
  608. color='red',
  609. )
  610. stderr()
  611. hint(('To remove all urls you can run:',
  612. 'archivebox remove --filter-type=regex ".*"'))
  613. stderr()
  614. raise SystemExit(2)
  615. elif filter_str:
  616. filter_patterns = [ptn.strip() for ptn in filter_str.split('\n')]
  617. list_kwargs = {
  618. "filter_patterns": filter_patterns,
  619. "filter_type": filter_type,
  620. "after": after,
  621. "before": before,
  622. }
  623. if snapshots:
  624. list_kwargs["snapshots"] = snapshots
  625. log_list_started(filter_patterns, filter_type)
  626. timer = TimedProgress(360, prefix=' ')
  627. try:
  628. snapshots = list_links(**list_kwargs)
  629. finally:
  630. timer.end()
  631. if not snapshots.exists():
  632. log_removal_finished(0, 0)
  633. raise SystemExit(1)
  634. log_links = [link.as_link() for link in snapshots]
  635. log_list_finished(log_links)
  636. log_removal_started(log_links, yes=yes, delete=delete)
  637. timer = TimedProgress(360, prefix=' ')
  638. try:
  639. for snapshot in snapshots:
  640. if delete:
  641. shutil.rmtree(snapshot.as_link().link_dir, ignore_errors=True)
  642. finally:
  643. timer.end()
  644. to_remove = snapshots.count()
  645. flush_search_index(snapshots=snapshots)
  646. remove_from_sql_main_index(snapshots=snapshots, out_dir=out_dir)
  647. all_snapshots = load_main_index(out_dir=out_dir)
  648. log_removal_finished(all_snapshots.count(), to_remove)
  649. return all_snapshots
  650. @enforce_types
  651. def update(resume: Optional[float]=None,
  652. only_new: bool=ONLY_NEW,
  653. index_only: bool=False,
  654. overwrite: bool=False,
  655. filter_patterns_str: Optional[str]=None,
  656. filter_patterns: Optional[List[str]]=None,
  657. filter_type: Optional[str]=None,
  658. status: Optional[str]=None,
  659. after: Optional[str]=None,
  660. before: Optional[str]=None,
  661. extractors: str="",
  662. out_dir: Path=OUTPUT_DIR) -> List[Link]:
  663. """Import any new links from subscriptions and retry any previously failed/skipped links"""
  664. check_data_folder(out_dir=out_dir)
  665. check_dependencies()
  666. new_links: List[Link] = [] # TODO: Remove input argument: only_new
  667. extractors = extractors.split(",") if extractors else []
  668. # Step 1: Filter for selected_links
  669. matching_snapshots = list_links(
  670. filter_patterns=filter_patterns,
  671. filter_type=filter_type,
  672. before=before,
  673. after=after,
  674. )
  675. matching_folders = list_folders(
  676. links=matching_snapshots,
  677. status=status,
  678. out_dir=out_dir,
  679. )
  680. all_links = [link for link in matching_folders.values() if link]
  681. if index_only:
  682. for link in all_links:
  683. write_link_details(link, out_dir=out_dir, skip_sql_index=True)
  684. index_links(all_links, out_dir=out_dir)
  685. return all_links
  686. # Step 2: Run the archive methods for each link
  687. to_archive = new_links if only_new else all_links
  688. if resume:
  689. to_archive = [
  690. link for link in to_archive
  691. if link.timestamp >= str(resume)
  692. ]
  693. if not to_archive:
  694. stderr('')
  695. stderr(f'[√] Nothing found to resume after {resume}', color='green')
  696. return all_links
  697. archive_kwargs = {
  698. "out_dir": out_dir,
  699. }
  700. if extractors:
  701. archive_kwargs["methods"] = extractors
  702. archive_links(to_archive, overwrite=overwrite, **archive_kwargs)
  703. # Step 4: Re-write links index with updated titles, icons, and resources
  704. all_links = load_main_index(out_dir=out_dir)
  705. return all_links
  706. @enforce_types
  707. def list_all(filter_patterns_str: Optional[str]=None,
  708. filter_patterns: Optional[List[str]]=None,
  709. filter_type: str='exact',
  710. status: Optional[str]=None,
  711. after: Optional[float]=None,
  712. before: Optional[float]=None,
  713. sort: Optional[str]=None,
  714. csv: Optional[str]=None,
  715. json: bool=False,
  716. html: bool=False,
  717. with_headers: bool=False,
  718. out_dir: Path=OUTPUT_DIR) -> Iterable[Link]:
  719. """List, filter, and export information about archive entries"""
  720. check_data_folder(out_dir=out_dir)
  721. if filter_patterns and filter_patterns_str:
  722. stderr(
  723. '[X] You should either pass filter patterns as an arguments '
  724. 'or via stdin, but not both.\n',
  725. color='red',
  726. )
  727. raise SystemExit(2)
  728. elif filter_patterns_str:
  729. filter_patterns = filter_patterns_str.split('\n')
  730. snapshots = list_links(
  731. filter_patterns=filter_patterns,
  732. filter_type=filter_type,
  733. before=before,
  734. after=after,
  735. )
  736. if sort:
  737. snapshots = snapshots.order_by(sort)
  738. folders = list_folders(
  739. links=snapshots,
  740. status=status,
  741. out_dir=out_dir,
  742. )
  743. if json:
  744. output = generate_json_index_from_links(folders.values(), with_headers)
  745. elif html:
  746. output = generate_index_from_links(folders.values(), with_headers)
  747. elif csv:
  748. output = links_to_csv(folders.values(), cols=csv.split(','), header=with_headers)
  749. else:
  750. output = printable_folders(folders, with_headers=with_headers)
  751. print(output)
  752. return folders
  753. @enforce_types
  754. def list_links(snapshots: Optional[QuerySet]=None,
  755. filter_patterns: Optional[List[str]]=None,
  756. filter_type: str='exact',
  757. after: Optional[float]=None,
  758. before: Optional[float]=None,
  759. out_dir: Path=OUTPUT_DIR) -> Iterable[Link]:
  760. check_data_folder(out_dir=out_dir)
  761. if snapshots:
  762. all_snapshots = snapshots
  763. else:
  764. all_snapshots = load_main_index(out_dir=out_dir)
  765. if after is not None:
  766. all_snapshots = all_snapshots.filter(timestamp__gte=after)
  767. if before is not None:
  768. all_snapshots = all_snapshots.filter(timestamp__lt=before)
  769. if filter_patterns:
  770. all_snapshots = snapshot_filter(all_snapshots, filter_patterns, filter_type)
  771. if not all_snapshots:
  772. stderr('[!] No Snapshots matched your filters:', filter_patterns, f'({filter_type})', color='lightyellow')
  773. return all_snapshots
  774. @enforce_types
  775. def list_folders(links: List[Link],
  776. status: str,
  777. out_dir: Path=OUTPUT_DIR) -> Dict[str, Optional[Link]]:
  778. check_data_folder(out_dir=out_dir)
  779. STATUS_FUNCTIONS = {
  780. "indexed": get_indexed_folders,
  781. "archived": get_archived_folders,
  782. "unarchived": get_unarchived_folders,
  783. "present": get_present_folders,
  784. "valid": get_valid_folders,
  785. "invalid": get_invalid_folders,
  786. "duplicate": get_duplicate_folders,
  787. "orphaned": get_orphaned_folders,
  788. "corrupted": get_corrupted_folders,
  789. "unrecognized": get_unrecognized_folders,
  790. }
  791. try:
  792. return STATUS_FUNCTIONS[status](links, out_dir=out_dir)
  793. except KeyError:
  794. raise ValueError('Status not recognized.')
  795. @enforce_types
  796. def setup(out_dir: Path=OUTPUT_DIR) -> None:
  797. """Automatically install all ArchiveBox dependencies and extras"""
  798. if not (out_dir / ARCHIVE_DIR_NAME).exists():
  799. run_subcommand('init', stdin=None, pwd=out_dir)
  800. setup_django(out_dir=out_dir, check_db=True)
  801. from core.models import User
  802. if not User.objects.filter(is_superuser=True).exists():
  803. stderr('\n[+] Creating new admin user for the Web UI...', color='green')
  804. run_subcommand('manage', subcommand_args=['createsuperuser'], pwd=out_dir)
  805. stderr('\n[+] Installing enabled ArchiveBox dependencies automatically...', color='green')
  806. stderr('\n Installing YOUTUBEDL_BINARY automatically using pip...')
  807. if USE_YOUTUBEDL:
  808. if YOUTUBEDL_VERSION:
  809. print(f'{YOUTUBEDL_VERSION} is already installed', YOUTUBEDL_BINARY)
  810. else:
  811. try:
  812. run_shell([
  813. PYTHON_BINARY, '-m', 'pip',
  814. 'install',
  815. '--upgrade',
  816. '--no-cache-dir',
  817. '--no-warn-script-location',
  818. 'youtube_dl',
  819. ], capture_output=False, cwd=out_dir)
  820. pkg_path = run_shell([
  821. PYTHON_BINARY, '-m', 'pip',
  822. 'show',
  823. 'youtube_dl',
  824. ], capture_output=True, text=True, cwd=out_dir).stdout.split('Location: ')[-1].split('\n', 1)[0]
  825. NEW_YOUTUBEDL_BINARY = Path(pkg_path) / 'youtube_dl' / '__main__.py'
  826. os.chmod(NEW_YOUTUBEDL_BINARY, 0o777)
  827. assert NEW_YOUTUBEDL_BINARY.exists(), f'youtube_dl must exist inside {pkg_path}'
  828. config(f'YOUTUBEDL_BINARY={NEW_YOUTUBEDL_BINARY}', set=True, out_dir=out_dir)
  829. except BaseException as e:
  830. stderr(f'[X] Failed to install python packages: {e}', color='red')
  831. raise SystemExit(1)
  832. stderr('\n Installing CHROME_BINARY automatically using playwright...')
  833. if USE_CHROME:
  834. if CHROME_VERSION:
  835. print(f'{CHROME_VERSION} is already installed', CHROME_BINARY)
  836. else:
  837. try:
  838. run_shell([
  839. PYTHON_BINARY, '-m', 'pip',
  840. 'install',
  841. '--upgrade',
  842. '--no-cache-dir',
  843. '--no-warn-script-location',
  844. 'playwright',
  845. ], capture_output=False, cwd=out_dir)
  846. run_shell([PYTHON_BINARY, '-m', 'playwright', 'install', 'chromium'], capture_output=False, cwd=out_dir)
  847. proc = run_shell([PYTHON_BINARY, '-c', 'from playwright.sync_api import sync_playwright; print(sync_playwright().start().chromium.executable_path)'], capture_output=True, text=True, cwd=out_dir)
  848. NEW_CHROME_BINARY = proc.stdout.strip()
  849. assert NEW_CHROME_BINARY and len(NEW_CHROME_BINARY), 'CHROME_BINARY must contain a path'
  850. config(f'CHROME_BINARY={NEW_CHROME_BINARY}', set=True, out_dir=out_dir)
  851. except BaseException as e:
  852. stderr(f'[X] Failed to install chromium using playwright: {e.__class__.__name__} {e}', color='red')
  853. raise SystemExit(1)
  854. stderr('\n Installing SINGLEFILE_BINARY, READABILITY_BINARY, MERCURY_BINARY automatically using npm...')
  855. if USE_NODE:
  856. if not NODE_VERSION:
  857. stderr('[X] You must first install node using your system package manager', color='red')
  858. hint([
  859. 'curl -sL https://deb.nodesource.com/setup_15.x | sudo -E bash -',
  860. 'or to disable all node-based modules run: archivebox config --set USE_NODE=False',
  861. ])
  862. raise SystemExit(1)
  863. if all((SINGLEFILE_VERSION, READABILITY_VERSION, MERCURY_VERSION)):
  864. print('SINGLEFILE_BINARY, READABILITY_BINARY, and MERCURURY_BINARY are already installed')
  865. else:
  866. try:
  867. # clear out old npm package locations
  868. paths = (
  869. out_dir / 'package.json',
  870. out_dir / 'package_lock.json',
  871. out_dir / 'node_modules',
  872. )
  873. for path in paths:
  874. if path.is_dir():
  875. shutil.rmtree(path, ignore_errors=True)
  876. elif path.is_file():
  877. os.remove(path)
  878. shutil.copyfile(PACKAGE_DIR / 'package.json', out_dir / 'package.json')
  879. run_shell([
  880. 'npm',
  881. 'install',
  882. '--prefix', str(out_dir),
  883. '--force',
  884. '--no-save',
  885. '--no-audit',
  886. '--no-fund',
  887. '--loglevel', 'error',
  888. ], capture_output=False, cwd=out_dir)
  889. os.remove(out_dir / 'package.json')
  890. except BaseException as e:
  891. stderr(f'[X] Failed to install npm packages: {e}', color='red')
  892. hint(f'Try deleting {out_dir}/node_modules and running it again')
  893. raise SystemExit(1)
  894. stderr('\n[√] Set up ArchiveBox and its dependencies successfully.', color='green')
  895. run_shell([ARCHIVEBOX_BINARY, '--version'], capture_output=False, cwd=out_dir)
  896. @enforce_types
  897. def config(config_options_str: Optional[str]=None,
  898. config_options: Optional[List[str]]=None,
  899. get: bool=False,
  900. set: bool=False,
  901. reset: bool=False,
  902. out_dir: Path=OUTPUT_DIR) -> None:
  903. """Get and set your ArchiveBox project configuration values"""
  904. check_data_folder(out_dir=out_dir)
  905. if config_options and config_options_str:
  906. stderr(
  907. '[X] You should either pass config values as an arguments '
  908. 'or via stdin, but not both.\n',
  909. color='red',
  910. )
  911. raise SystemExit(2)
  912. elif config_options_str:
  913. config_options = config_options_str.split('\n')
  914. config_options = config_options or []
  915. no_args = not (get or set or reset or config_options)
  916. matching_config: ConfigDict = {}
  917. if get or no_args:
  918. if config_options:
  919. config_options = [get_real_name(key) for key in config_options]
  920. matching_config = {key: CONFIG[key] for key in config_options if key in CONFIG}
  921. failed_config = [key for key in config_options if key not in CONFIG]
  922. if failed_config:
  923. stderr()
  924. stderr('[X] These options failed to get', color='red')
  925. stderr(' {}'.format('\n '.join(config_options)))
  926. raise SystemExit(1)
  927. else:
  928. matching_config = CONFIG
  929. print(printable_config(matching_config))
  930. raise SystemExit(not matching_config)
  931. elif set:
  932. new_config = {}
  933. failed_options = []
  934. for line in config_options:
  935. if line.startswith('#') or not line.strip():
  936. continue
  937. if '=' not in line:
  938. stderr('[X] Config KEY=VALUE must have an = sign in it', color='red')
  939. stderr(f' {line}')
  940. raise SystemExit(2)
  941. raw_key, val = line.split('=', 1)
  942. raw_key = raw_key.upper().strip()
  943. key = get_real_name(raw_key)
  944. if key != raw_key:
  945. stderr(f'[i] Note: The config option {raw_key} has been renamed to {key}, please use the new name going forwards.', color='lightyellow')
  946. if key in CONFIG:
  947. new_config[key] = val.strip()
  948. else:
  949. failed_options.append(line)
  950. if new_config:
  951. before = CONFIG
  952. matching_config = write_config_file(new_config, out_dir=OUTPUT_DIR)
  953. after = load_all_config()
  954. print(printable_config(matching_config))
  955. side_effect_changes: ConfigDict = {}
  956. for key, val in after.items():
  957. if key in USER_CONFIG and (before[key] != after[key]) and (key not in matching_config):
  958. side_effect_changes[key] = after[key]
  959. if side_effect_changes:
  960. stderr()
  961. stderr('[i] Note: This change also affected these other options that depended on it:', color='lightyellow')
  962. print(' {}'.format(printable_config(side_effect_changes, prefix=' ')))
  963. if failed_options:
  964. stderr()
  965. stderr('[X] These options failed to set (check for typos):', color='red')
  966. stderr(' {}'.format('\n '.join(failed_options)))
  967. raise SystemExit(1)
  968. elif reset:
  969. stderr('[X] This command is not implemented yet.', color='red')
  970. stderr(' Please manually remove the relevant lines from your config file:')
  971. stderr(f' {CONFIG_FILE}')
  972. raise SystemExit(2)
  973. else:
  974. stderr('[X] You must pass either --get or --set, or no arguments to get the whole config.', color='red')
  975. stderr(' archivebox config')
  976. stderr(' archivebox config --get SOME_KEY')
  977. stderr(' archivebox config --set SOME_KEY=SOME_VALUE')
  978. raise SystemExit(2)
  979. @enforce_types
  980. def schedule(add: bool=False,
  981. show: bool=False,
  982. clear: bool=False,
  983. foreground: bool=False,
  984. run_all: bool=False,
  985. quiet: bool=False,
  986. every: Optional[str]=None,
  987. depth: int=0,
  988. overwrite: bool=False,
  989. import_path: Optional[str]=None,
  990. out_dir: Path=OUTPUT_DIR):
  991. """Set ArchiveBox to regularly import URLs at specific times using cron"""
  992. check_data_folder(out_dir=out_dir)
  993. Path(LOGS_DIR).mkdir(exist_ok=True)
  994. cron = CronTab(user=True)
  995. cron = dedupe_cron_jobs(cron)
  996. if clear:
  997. print(cron.remove_all(comment=CRON_COMMENT))
  998. cron.write()
  999. raise SystemExit(0)
  1000. existing_jobs = list(cron.find_comment(CRON_COMMENT))
  1001. if every or add:
  1002. every = every or 'day'
  1003. quoted = lambda s: f'"{s}"' if (s and ' ' in str(s)) else str(s)
  1004. cmd = [
  1005. 'cd',
  1006. quoted(out_dir),
  1007. '&&',
  1008. quoted(ARCHIVEBOX_BINARY),
  1009. *([
  1010. 'add',
  1011. *(['--overwrite'] if overwrite else []),
  1012. f'--depth={depth}',
  1013. f'"{import_path}"',
  1014. ] if import_path else ['update']),
  1015. '>>',
  1016. quoted(Path(LOGS_DIR) / 'schedule.log'),
  1017. '2>&1',
  1018. ]
  1019. new_job = cron.new(command=' '.join(cmd), comment=CRON_COMMENT)
  1020. if every in ('minute', 'hour', 'day', 'month', 'year'):
  1021. set_every = getattr(new_job.every(), every)
  1022. set_every()
  1023. elif CronSlices.is_valid(every):
  1024. new_job.setall(every)
  1025. else:
  1026. stderr('{red}[X] Got invalid timeperiod for cron task.{reset}'.format(**ANSI))
  1027. stderr(' It must be one of minute/hour/day/month')
  1028. stderr(' or a quoted cron-format schedule like:')
  1029. stderr(' archivebox init --every=day --depth=1 https://example.com/some/rss/feed.xml')
  1030. stderr(' archivebox init --every="0/5 * * * *" --depth=1 https://example.com/some/rss/feed.xml')
  1031. raise SystemExit(1)
  1032. cron = dedupe_cron_jobs(cron)
  1033. cron.write()
  1034. total_runs = sum(j.frequency_per_year() for j in cron)
  1035. existing_jobs = list(cron.find_comment(CRON_COMMENT))
  1036. print()
  1037. print('{green}[√] Scheduled new ArchiveBox cron job for user: {} ({} jobs are active).{reset}'.format(USER, len(existing_jobs), **ANSI))
  1038. print('\n'.join(f' > {cmd}' if str(cmd) == str(new_job) else f' {cmd}' for cmd in existing_jobs))
  1039. if total_runs > 60 and not quiet:
  1040. stderr()
  1041. stderr('{lightyellow}[!] With the current cron config, ArchiveBox is estimated to run >{} times per year.{reset}'.format(total_runs, **ANSI))
  1042. stderr(' Congrats on being an enthusiastic internet archiver! 👌')
  1043. stderr()
  1044. stderr(' Make sure you have enough storage space available to hold all the data.')
  1045. stderr(' Using a compressed/deduped filesystem like ZFS is recommended if you plan on archiving a lot.')
  1046. stderr('')
  1047. elif show:
  1048. if existing_jobs:
  1049. print('\n'.join(str(cmd) for cmd in existing_jobs))
  1050. else:
  1051. stderr('{red}[X] There are no ArchiveBox cron jobs scheduled for your user ({}).{reset}'.format(USER, **ANSI))
  1052. stderr(' To schedule a new job, run:')
  1053. stderr(' archivebox schedule --every=[timeperiod] --depth=1 https://example.com/some/rss/feed.xml')
  1054. raise SystemExit(0)
  1055. cron = CronTab(user=True)
  1056. cron = dedupe_cron_jobs(cron)
  1057. existing_jobs = list(cron.find_comment(CRON_COMMENT))
  1058. if foreground or run_all:
  1059. if not existing_jobs:
  1060. stderr('{red}[X] You must schedule some jobs first before running in foreground mode.{reset}'.format(**ANSI))
  1061. stderr(' archivebox schedule --every=hour --depth=1 https://example.com/some/rss/feed.xml')
  1062. raise SystemExit(1)
  1063. print('{green}[*] Running {} ArchiveBox jobs in foreground task scheduler...{reset}'.format(len(existing_jobs), **ANSI))
  1064. if run_all:
  1065. try:
  1066. for job in existing_jobs:
  1067. sys.stdout.write(f' > {job.command.split("/archivebox ")[0].split(" && ")[0]}\n')
  1068. sys.stdout.write(f' > {job.command.split("/archivebox ")[-1].split(" >> ")[0]}')
  1069. sys.stdout.flush()
  1070. job.run()
  1071. sys.stdout.write(f'\r √ {job.command.split("/archivebox ")[-1]}\n')
  1072. except KeyboardInterrupt:
  1073. print('\n{green}[√] Stopped.{reset}'.format(**ANSI))
  1074. raise SystemExit(1)
  1075. if foreground:
  1076. try:
  1077. for job in existing_jobs:
  1078. print(f' > {job.command.split("/archivebox ")[-1].split(" >> ")[0]}')
  1079. for result in cron.run_scheduler():
  1080. print(result)
  1081. except KeyboardInterrupt:
  1082. print('\n{green}[√] Stopped.{reset}'.format(**ANSI))
  1083. raise SystemExit(1)
  1084. @enforce_types
  1085. def server(runserver_args: Optional[List[str]]=None,
  1086. reload: bool=False,
  1087. debug: bool=False,
  1088. init: bool=False,
  1089. quick_init: bool=False,
  1090. createsuperuser: bool=False,
  1091. out_dir: Path=OUTPUT_DIR) -> None:
  1092. """Run the ArchiveBox HTTP server"""
  1093. runserver_args = runserver_args or []
  1094. if init:
  1095. run_subcommand('init', stdin=None, pwd=out_dir)
  1096. print()
  1097. elif quick_init:
  1098. run_subcommand('init', subcommand_args=['--quick'], stdin=None, pwd=out_dir)
  1099. print()
  1100. if createsuperuser:
  1101. run_subcommand('manage', subcommand_args=['createsuperuser'], pwd=out_dir)
  1102. print()
  1103. # setup config for django runserver
  1104. from . import config
  1105. config.SHOW_PROGRESS = False
  1106. config.DEBUG = config.DEBUG or debug
  1107. check_data_folder(out_dir=out_dir)
  1108. from django.core.management import call_command
  1109. from django.contrib.auth.models import User
  1110. print('{green}[+] Starting ArchiveBox webserver...{reset}'.format(**ANSI))
  1111. print(' > Logging errors to ./logs/errors.log')
  1112. if not User.objects.filter(is_superuser=True).exists():
  1113. print('{lightyellow}[!] No admin users exist yet, you will not be able to edit links in the UI.{reset}'.format(**ANSI))
  1114. print()
  1115. print(' To create an admin user, run:')
  1116. print(' archivebox manage createsuperuser')
  1117. print()
  1118. # fallback to serving staticfiles insecurely with django when DEBUG=False
  1119. if not config.DEBUG:
  1120. runserver_args.append('--insecure') # TODO: serve statics w/ nginx instead
  1121. # toggle autoreloading when archivebox code changes (it's on by default)
  1122. if not reload:
  1123. runserver_args.append('--noreload')
  1124. config.SHOW_PROGRESS = False
  1125. config.DEBUG = config.DEBUG or debug
  1126. call_command("runserver", *runserver_args)
  1127. @enforce_types
  1128. def manage(args: Optional[List[str]]=None, out_dir: Path=OUTPUT_DIR) -> None:
  1129. """Run an ArchiveBox Django management command"""
  1130. check_data_folder(out_dir=out_dir)
  1131. from django.core.management import execute_from_command_line
  1132. if (args and "createsuperuser" in args) and (IN_DOCKER and not IS_TTY):
  1133. stderr('[!] Warning: you need to pass -it to use interactive commands in docker', color='lightyellow')
  1134. stderr(' docker run -it archivebox manage {}'.format(' '.join(args or ['...'])), color='lightyellow')
  1135. stderr()
  1136. execute_from_command_line([f'{ARCHIVEBOX_BINARY} manage', *(args or ['help'])])
  1137. @enforce_types
  1138. def shell(out_dir: Path=OUTPUT_DIR) -> None:
  1139. """Enter an interactive ArchiveBox Django shell"""
  1140. check_data_folder(out_dir=out_dir)
  1141. from django.core.management import call_command
  1142. call_command("shell_plus")