main.py 52 KB

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