main.py 52 KB

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