main.py 55 KB

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