2
0

main.py 50 KB

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