main.py 53 KB

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