2
0

main.py 41 KB

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