main.py 41 KB

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