main.py 40 KB

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