main.py 40 KB

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