main.py 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488
  1. __package__ = 'archivebox'
  2. import os
  3. import sys
  4. import shutil
  5. import platform
  6. from typing import Dict, List, Optional, Iterable, IO, Union
  7. from pathlib import Path
  8. from datetime import date, datetime
  9. from crontab import CronTab, CronSlices
  10. from django.db.models import QuerySet
  11. from django.utils import timezone
  12. from archivebox.config import CONSTANTS, VERSION, DATA_DIR, ARCHIVE_DIR
  13. from archivebox.config.common import SHELL_CONFIG, SEARCH_BACKEND_CONFIG, STORAGE_CONFIG, SERVER_CONFIG, ARCHIVING_CONFIG
  14. from archivebox.config.permissions import SudoPermission, IN_DOCKER
  15. from .cli import (
  16. CLI_SUBCOMMANDS,
  17. run_subcommand,
  18. display_first,
  19. meta_cmds,
  20. setup_cmds,
  21. archive_cmds,
  22. )
  23. from .parsers import (
  24. save_text_as_source,
  25. save_file_as_source,
  26. parse_links_memory,
  27. )
  28. from archivebox.misc.util import enforce_types # type: ignore
  29. from archivebox.misc.system import get_dir_size, dedupe_cron_jobs, CRON_COMMENT
  30. from archivebox.misc.system import run as run_shell
  31. from .index.schema import Link
  32. from .index import (
  33. load_main_index,
  34. parse_links_from_source,
  35. dedupe_links,
  36. write_main_index,
  37. snapshot_filter,
  38. get_indexed_folders,
  39. get_archived_folders,
  40. get_unarchived_folders,
  41. get_present_folders,
  42. get_valid_folders,
  43. get_invalid_folders,
  44. get_duplicate_folders,
  45. get_orphaned_folders,
  46. get_corrupted_folders,
  47. get_unrecognized_folders,
  48. fix_invalid_folder_locations,
  49. write_link_details,
  50. )
  51. from .index.json import (
  52. parse_json_main_index,
  53. parse_json_links_details,
  54. generate_json_index_from_links,
  55. )
  56. from .index.sql import (
  57. get_admins,
  58. apply_migrations,
  59. remove_from_sql_main_index,
  60. )
  61. from .index.html import generate_index_from_links
  62. from .index.csv import links_to_csv
  63. from .extractors import archive_links, archive_link, ignore_methods
  64. from archivebox.misc.logging import stderr, hint
  65. from archivebox.misc.checks import check_data_folder
  66. from archivebox.config.legacy import (
  67. write_config_file,
  68. load_all_config,
  69. get_real_name,
  70. )
  71. from .logging_util import (
  72. TimedProgress,
  73. log_importing_started,
  74. log_crawl_started,
  75. log_removal_started,
  76. log_removal_finished,
  77. log_list_started,
  78. log_list_finished,
  79. printable_config,
  80. printable_folders,
  81. printable_filesize,
  82. printable_folder_status,
  83. )
  84. @enforce_types
  85. def help(out_dir: Path=DATA_DIR) -> None:
  86. """Print the ArchiveBox help message and usage"""
  87. from rich import print
  88. from rich.panel import Panel
  89. all_subcommands = CLI_SUBCOMMANDS
  90. COMMANDS_HELP_TEXT = '\n '.join(
  91. f'[green]{cmd.ljust(20)}[/green] {func.__doc__}'
  92. for cmd, func in all_subcommands.items()
  93. if cmd in meta_cmds
  94. ) + '\n\n ' + '\n '.join(
  95. f'[green]{cmd.ljust(20)}[/green] {func.__doc__}'
  96. for cmd, func in all_subcommands.items()
  97. if cmd in setup_cmds
  98. ) + '\n\n ' + '\n '.join(
  99. f'[green]{cmd.ljust(20)}[/green] {func.__doc__}'
  100. for cmd, func in all_subcommands.items()
  101. if cmd in archive_cmds
  102. ) + '\n\n ' + '\n '.join(
  103. f'[green]{cmd.ljust(20)}[/green] {func.__doc__}'
  104. for cmd, func in all_subcommands.items()
  105. if cmd not in display_first
  106. )
  107. DOCKER_USAGE = '''
  108. [dodger_blue3]Docker Usage:[/dodger_blue3]
  109. [grey53]# using Docker Compose:[/grey53]
  110. [blue]docker compose run[/blue] [dark_green]archivebox[/dark_green] [green]\\[command][/green] [green3][...args][/green3] [violet][--help][/violet] [grey53][--version][/grey53]
  111. [grey53]# using Docker:[/grey53]
  112. [blue]docker run[/blue] -v [light_slate_blue]$PWD:/data[/light_slate_blue] [grey53]-p 8000:8000[/grey53] -it [dark_green]archivebox/archivebox[/dark_green] [green]\\[command][/green] [green3][...args][/green3] [violet][--help][/violet] [grey53][--version][/grey53]
  113. ''' if IN_DOCKER else ''
  114. DOCKER_DOCS = '\n [link=https://github.com/ArchiveBox/ArchiveBox/wiki/Docker#usage]https://github.com/ArchiveBox/ArchiveBox/wiki/Docker[/link]' if IN_DOCKER else ''
  115. DOCKER_OUTSIDE_HINT = "\n [grey53]# outside of Docker:[/grey53]" if IN_DOCKER else ''
  116. DOCKER_CMD_PREFIX = "[blue]docker ... [/blue]" if IN_DOCKER else ''
  117. print(f'''{DOCKER_USAGE}
  118. [deep_sky_blue4]Usage:[/deep_sky_blue4]{DOCKER_OUTSIDE_HINT}
  119. [dark_green]archivebox[/dark_green] [green]\\[command][/green] [green3][...args][/green3] [violet][--help][/violet] [grey53][--version][/grey53]
  120. [deep_sky_blue4]Commands:[/deep_sky_blue4]
  121. {COMMANDS_HELP_TEXT}
  122. [deep_sky_blue4]Documentation:[/deep_sky_blue4]
  123. [link=https://github.com/ArchiveBox/ArchiveBox/wiki]https://github.com/ArchiveBox/ArchiveBox/wiki[/link]{DOCKER_DOCS}
  124. [link=https://github.com/ArchiveBox/ArchiveBox/wiki/Usage#cli-usage]https://github.com/ArchiveBox/ArchiveBox/wiki/Usage[/link]
  125. [link=https://github.com/ArchiveBox/ArchiveBox/wiki/Configuration]https://github.com/ArchiveBox/ArchiveBox/wiki/Configuration[/link]
  126. ''')
  127. if os.access(CONSTANTS.ARCHIVE_DIR, os.R_OK) and CONSTANTS.ARCHIVE_DIR.is_dir():
  128. pretty_out_dir = str(out_dir).replace(str(Path('~').expanduser()), '~')
  129. EXAMPLE_USAGE = f'''
  130. [light_slate_blue]DATA DIR[/light_slate_blue]: [yellow]{pretty_out_dir}[/yellow]
  131. [violet]Hint:[/violet] [i]Common maintenance tasks:[/i]
  132. [dark_green]archivebox[/dark_green] [green]init[/green] [grey53]# make sure database is up-to-date (safe to run multiple times)[/grey53]
  133. [dark_green]archivebox[/dark_green] [green]install[/green] [grey53]# make sure plugins are up-to-date (wget, chrome, singlefile, etc.)[/grey53]
  134. [dark_green]archivebox[/dark_green] [green]status[/green] [grey53]# get a health checkup report on your collection[/grey53]
  135. [dark_green]archivebox[/dark_green] [green]update[/green] [grey53]# retry any previously failed or interrupted archiving tasks[/grey53]
  136. [violet]Hint:[/violet] [i]More example usage:[/i]
  137. [dark_green]archivebox[/dark_green] [green]add[/green] --depth=1 "https://example.com/some/page"
  138. [dark_green]archivebox[/dark_green] [green]list[/green] --sort=timestamp --csv=timestamp,downloaded_at,url,title
  139. [dark_green]archivebox[/dark_green] [green]schedule[/green] --every=day --depth=1 "https://example.com/some/feed.rss"
  140. [dark_green]archivebox[/dark_green] [green]server[/green] [blue]0.0.0.0:8000[/blue] [grey53]# Start the Web UI / API server[/grey53]
  141. '''
  142. print(Panel(EXAMPLE_USAGE, expand=False, border_style='grey53', title='[green3]:white_check_mark: A collection [light_slate_blue]DATA DIR[/light_slate_blue] is currently active[/green3]', subtitle='Commands run inside this dir will only apply to this collection.'))
  143. else:
  144. DATA_SETUP_HELP = '\n'
  145. if IN_DOCKER:
  146. DATA_SETUP_HELP += '[violet]Hint:[/violet] When using Docker, you need to mount a volume to use as your data dir:\n'
  147. DATA_SETUP_HELP += ' docker run [violet]-v /some/path/data:/data[/violet] archivebox/archivebox ...\n\n'
  148. DATA_SETUP_HELP += 'To load an [dark_blue]existing[/dark_blue] collection:\n'
  149. DATA_SETUP_HELP += ' 1. [green]cd[/green] ~/archivebox/data [grey53]# go into existing [light_slate_blue]DATA DIR[/light_slate_blue] (can be anywhere)[/grey53]\n'
  150. DATA_SETUP_HELP += f' 2. {DOCKER_CMD_PREFIX}[dark_green]archivebox[/dark_green] [green]init[/green] [grey53]# migrate to latest version (safe to run multiple times)[/grey53]\n'
  151. DATA_SETUP_HELP += f' 3. {DOCKER_CMD_PREFIX}[dark_green]archivebox[/dark_green] [green]install[/green] [grey53]# auto-update all plugins (wget, chrome, singlefile, etc.)[/grey53]\n'
  152. DATA_SETUP_HELP += f' 4. {DOCKER_CMD_PREFIX}[dark_green]archivebox[/dark_green] [green]help[/green] [grey53]# ...get help with next steps... [/grey53]\n\n'
  153. DATA_SETUP_HELP += 'To start a [sea_green1]new[/sea_green1] collection:\n'
  154. DATA_SETUP_HELP += ' 1. [green]mkdir[/green] ~/archivebox/data [grey53]# create a new, empty [light_slate_blue]DATA DIR[/light_slate_blue] (can be anywhere)[/grey53]\n'
  155. DATA_SETUP_HELP += ' 2. [green]cd[/green] ~/archivebox/data [grey53]# cd into the new directory[/grey53]\n'
  156. DATA_SETUP_HELP += f' 3. {DOCKER_CMD_PREFIX}[dark_green]archivebox[/dark_green] [green]init[/green] [grey53]# initialize ArchiveBox in the new data dir[/grey53]\n'
  157. DATA_SETUP_HELP += f' 4. {DOCKER_CMD_PREFIX}[dark_green]archivebox[/dark_green] [green]install[/green] [grey53]# auto-install all plugins (wget, chrome, singlefile, etc.)[/grey53]\n'
  158. DATA_SETUP_HELP += f' 5. {DOCKER_CMD_PREFIX}[dark_green]archivebox[/dark_green] [green]help[/green] [grey53]# ... get help with next steps... [/grey53]\n'
  159. print(Panel(DATA_SETUP_HELP, expand=False, border_style='grey53', title='[red]:cross_mark: No collection is currently active[/red]', subtitle='All archivebox [green]commands[/green] should be run from inside a collection [light_slate_blue]DATA DIR[/light_slate_blue]'))
  160. @enforce_types
  161. def version(quiet: bool=False,
  162. out_dir: Path=DATA_DIR,
  163. binproviders: Optional[List[str]]=None,
  164. binaries: Optional[List[str]]=None,
  165. ) -> None:
  166. """Print the ArchiveBox version and dependency information"""
  167. print(VERSION)
  168. if quiet or '--version' in sys.argv:
  169. return
  170. from rich.panel import Panel
  171. from rich.console import Console
  172. console = Console()
  173. prnt = console.print
  174. from plugins_auth.ldap.config import LDAP_CONFIG
  175. from django.conf import settings
  176. from archivebox.config.version import get_COMMIT_HASH, get_BUILD_TIME
  177. from archivebox.config.permissions import ARCHIVEBOX_USER, ARCHIVEBOX_GROUP, RUNNING_AS_UID, RUNNING_AS_GID
  178. from archivebox.config.paths import get_data_locations, get_code_locations
  179. from abx.archivebox.base_binary import BaseBinary, apt, brew, env
  180. # 0.7.1
  181. # ArchiveBox v0.7.1+editable COMMIT_HASH=951bba5 BUILD_TIME=2023-12-17 16:46:05 1702860365
  182. # IN_DOCKER=False IN_QEMU=False ARCH=arm64 OS=Darwin PLATFORM=macOS-14.2-arm64-arm-64bit PYTHON=Cpython
  183. # FS_ATOMIC=True FS_REMOTE=False FS_USER=501:20 FS_PERMS=644
  184. # DEBUG=False IS_TTY=True TZ=UTC SEARCH_BACKEND=ripgrep LDAP=False
  185. p = platform.uname()
  186. COMMIT_HASH = get_COMMIT_HASH()
  187. prnt(
  188. '[dark_green]ArchiveBox[/dark_green] [dark_goldenrod]v{}[/dark_goldenrod]'.format(CONSTANTS.VERSION),
  189. f'COMMIT_HASH={COMMIT_HASH[:7] if COMMIT_HASH else "unknown"}',
  190. f'BUILD_TIME={get_BUILD_TIME()}',
  191. )
  192. prnt(
  193. f'IN_DOCKER={IN_DOCKER}',
  194. f'IN_QEMU={SHELL_CONFIG.IN_QEMU}',
  195. f'ARCH={p.machine}',
  196. f'OS={p.system}',
  197. f'PLATFORM={platform.platform()}',
  198. f'PYTHON={sys.implementation.name.title()}' + (' (venv)' if CONSTANTS.IS_INSIDE_VENV else ''),
  199. )
  200. OUTPUT_IS_REMOTE_FS = get_data_locations().DATA_DIR.is_mount or get_data_locations().ARCHIVE_DIR.is_mount
  201. DATA_DIR_STAT = CONSTANTS.DATA_DIR.stat()
  202. prnt(
  203. f'EUID={os.geteuid()}:{os.getegid()} UID={RUNNING_AS_UID}:{RUNNING_AS_GID} PUID={ARCHIVEBOX_USER}:{ARCHIVEBOX_GROUP}',
  204. f'FS_UID={DATA_DIR_STAT.st_uid}:{DATA_DIR_STAT.st_gid}',
  205. f'FS_PERMS={STORAGE_CONFIG.OUTPUT_PERMISSIONS}',
  206. f'FS_ATOMIC={STORAGE_CONFIG.ENFORCE_ATOMIC_WRITES}',
  207. f'FS_REMOTE={OUTPUT_IS_REMOTE_FS}',
  208. )
  209. prnt(
  210. f'DEBUG={SHELL_CONFIG.DEBUG}',
  211. f'IS_TTY={SHELL_CONFIG.IS_TTY}',
  212. f'SUDO={CONSTANTS.IS_ROOT}',
  213. f'ID={CONSTANTS.MACHINE_ID}:{CONSTANTS.COLLECTION_ID}',
  214. f'SEARCH_BACKEND={SEARCH_BACKEND_CONFIG.SEARCH_BACKEND_ENGINE}',
  215. f'LDAP={LDAP_CONFIG.LDAP_ENABLED}',
  216. #f'DB=django.db.backends.sqlite3 (({CONFIG["SQLITE_JOURNAL_MODE"]})', # add this if we have more useful info to show eventually
  217. )
  218. prnt()
  219. if not (os.access(CONSTANTS.ARCHIVE_DIR, os.R_OK) and os.access(CONSTANTS.CONFIG_FILE, os.R_OK)):
  220. PANEL_TEXT = '\n'.join((
  221. # '',
  222. # f'[yellow]CURRENT DIR =[/yellow] [red]{os.getcwd()}[/red]',
  223. '',
  224. '[violet]Hint:[/violet] [green]cd[/green] into a collection [blue]DATA_DIR[/blue] and run [green]archivebox version[/green] again...',
  225. ' [grey53]OR[/grey53] run [green]archivebox init[/green] to create a new collection in the current dir.',
  226. '',
  227. ' [i][grey53](this is [red]REQUIRED[/red] if you are opening a Github Issue to get help)[/grey53][/i]',
  228. '',
  229. ))
  230. prnt(Panel(PANEL_TEXT, expand=False, border_style='grey53', title='[red]:exclamation: No collection [blue]DATA_DIR[/blue] is currently active[/red]', subtitle='Full version info is only available when inside a collection [light_slate_blue]DATA DIR[/light_slate_blue]'))
  231. prnt()
  232. return
  233. prnt('[pale_green1][i] Binary Dependencies:[/pale_green1]')
  234. failures = []
  235. for name, binary in reversed(list(settings.BINARIES.items())):
  236. if binary.name == 'archivebox':
  237. continue
  238. # skip if the binary is not in the requested list of binaries
  239. if binaries and binary.name not in binaries:
  240. continue
  241. # skip if the binary is not supported by any of the requested binproviders
  242. if binproviders and binary.binproviders_supported and not any(provider.name in binproviders for provider in binary.binproviders_supported):
  243. continue
  244. err = None
  245. try:
  246. loaded_bin = binary.load()
  247. except Exception as e:
  248. err = e
  249. loaded_bin = binary
  250. provider_summary = f'[dark_sea_green3]{loaded_bin.binprovider.name.ljust(10)}[/dark_sea_green3]' if loaded_bin.binprovider else '[grey23]not found[/grey23] '
  251. if loaded_bin.abspath:
  252. abspath = str(loaded_bin.abspath).replace(str(DATA_DIR), '[light_slate_blue].[/light_slate_blue]').replace(str(Path('~').expanduser()), '~')
  253. if ' ' in abspath:
  254. abspath = abspath.replace(' ', r'\ ')
  255. else:
  256. abspath = f'[red]{err}[/red]'
  257. prnt('', '[green]√[/green]' if loaded_bin.is_valid else '[red]X[/red]', '', loaded_bin.name.ljust(21), str(loaded_bin.version).ljust(12), provider_summary, abspath, overflow='ignore', crop=False)
  258. if not loaded_bin.is_valid:
  259. failures.append(loaded_bin.name)
  260. prnt()
  261. prnt('[gold3][i] Package Managers:[/gold3]')
  262. for name, binprovider in reversed(list(settings.BINPROVIDERS.items())):
  263. err = None
  264. if binproviders and binprovider.name not in binproviders:
  265. continue
  266. # TODO: implement a BinProvider.BINARY() method that gets the loaded binary for a binprovider's INSTALLER_BIN
  267. loaded_bin = binprovider.INSTALLER_BINARY or BaseBinary(name=binprovider.INSTALLER_BIN, binproviders=[env, apt, brew])
  268. abspath = None
  269. if loaded_bin.abspath:
  270. abspath = str(loaded_bin.abspath).replace(str(DATA_DIR), '.').replace(str(Path('~').expanduser()), '~')
  271. if ' ' in abspath:
  272. abspath = abspath.replace(' ', r'\ ')
  273. PATH = str(binprovider.PATH).replace(str(DATA_DIR), '[light_slate_blue].[/light_slate_blue]').replace(str(Path('~').expanduser()), '~')
  274. ownership_summary = f'UID=[blue]{str(binprovider.EUID).ljust(4)}[/blue]'
  275. provider_summary = f'[dark_sea_green3]{str(abspath).ljust(52)}[/dark_sea_green3]' if abspath else f'[grey23]{"not available".ljust(52)}[/grey23]'
  276. prnt('', '[green]√[/green]' if binprovider.is_valid else '[grey53]-[/grey53]', '', binprovider.name.ljust(11), provider_summary, ownership_summary, f'PATH={PATH}', overflow='ellipsis', soft_wrap=True)
  277. if not (binaries or binproviders):
  278. # dont show source code / data dir info if we just want to get version info for a binary or binprovider
  279. prnt()
  280. prnt('[deep_sky_blue3][i] Code locations:[/deep_sky_blue3]')
  281. for name, path in get_code_locations().items():
  282. prnt(printable_folder_status(name, path), overflow='ignore', crop=False)
  283. prnt()
  284. if os.access(CONSTANTS.ARCHIVE_DIR, os.R_OK) or os.access(CONSTANTS.CONFIG_FILE, os.R_OK):
  285. prnt('[bright_yellow][i] Data locations:[/bright_yellow]')
  286. for name, path in get_data_locations().items():
  287. prnt(printable_folder_status(name, path), overflow='ignore', crop=False)
  288. from archivebox.misc.checks import check_data_dir_permissions
  289. check_data_dir_permissions()
  290. else:
  291. prnt()
  292. prnt('[red][i] Data locations:[/red] (not in a data directory)')
  293. prnt()
  294. if failures:
  295. raise SystemExit(1)
  296. raise SystemExit(0)
  297. @enforce_types
  298. def run(subcommand: str,
  299. subcommand_args: Optional[List[str]],
  300. stdin: Optional[IO]=None,
  301. out_dir: Path=DATA_DIR) -> None:
  302. """Run a given ArchiveBox subcommand with the given list of args"""
  303. run_subcommand(
  304. subcommand=subcommand,
  305. subcommand_args=subcommand_args,
  306. stdin=stdin,
  307. pwd=out_dir,
  308. )
  309. @enforce_types
  310. def init(force: bool=False, quick: bool=False, install: bool=False, out_dir: Path=DATA_DIR) -> None:
  311. """Initialize a new ArchiveBox collection in the current directory"""
  312. from core.models import Snapshot
  313. from rich import print
  314. # if os.access(out_dir / CONSTANTS.JSON_INDEX_FILENAME, os.F_OK):
  315. # print("[red]:warning: This folder contains a JSON index. It is deprecated, and will no longer be kept up to date automatically.[/red]", file=sys.stderr)
  316. # print("[red] You can run `archivebox list --json --with-headers > static_index.json` to manually generate it.[/red]", file=sys.stderr)
  317. is_empty = not len(set(os.listdir(out_dir)) - CONSTANTS.ALLOWED_IN_DATA_DIR)
  318. existing_index = os.path.isfile(CONSTANTS.DATABASE_FILE)
  319. if is_empty and not existing_index:
  320. print(f'[turquoise4][+] Initializing a new ArchiveBox v{VERSION} collection...[/turquoise4]')
  321. print('[green]----------------------------------------------------------------------[/green]')
  322. elif existing_index:
  323. # TODO: properly detect and print the existing version in current index as well
  324. print(f'[green][*] Verifying and updating existing ArchiveBox collection to v{VERSION}...[/green]')
  325. print('[green]----------------------------------------------------------------------[/green]')
  326. else:
  327. if force:
  328. print('[red][!] This folder appears to already have files in it, but no index.sqlite3 is present.[/red]')
  329. print('[red] Because --force was passed, ArchiveBox will initialize anyway (which may overwrite existing files).[/red]')
  330. else:
  331. print(
  332. ("[red][X] This folder appears to already have files in it, but no index.sqlite3 present.[/red]\n\n"
  333. " You must run init in a completely empty directory, or an existing data folder.\n\n"
  334. " [violet]Hint:[/violet] To import an existing data folder make sure to cd into the folder first, \n"
  335. " then run and run 'archivebox init' to pick up where you left off.\n\n"
  336. " (Always make sure your data folder is backed up first before updating ArchiveBox)"
  337. )
  338. )
  339. raise SystemExit(2)
  340. if existing_index:
  341. print('\n[green][*] Verifying archive folder structure...[/green]')
  342. else:
  343. print('\n[green][+] Building archive folder structure...[/green]')
  344. print(f' + ./{CONSTANTS.ARCHIVE_DIR.relative_to(DATA_DIR)}, ./{CONSTANTS.SOURCES_DIR.relative_to(DATA_DIR)}, ./{CONSTANTS.LOGS_DIR.relative_to(DATA_DIR)}...')
  345. Path(CONSTANTS.SOURCES_DIR).mkdir(exist_ok=True)
  346. Path(CONSTANTS.ARCHIVE_DIR).mkdir(exist_ok=True)
  347. Path(CONSTANTS.LOGS_DIR).mkdir(exist_ok=True)
  348. print(f' + ./{CONSTANTS.CONFIG_FILE.relative_to(DATA_DIR)}...')
  349. write_config_file({}, out_dir=str(out_dir))
  350. if os.access(CONSTANTS.DATABASE_FILE, os.F_OK):
  351. print('\n[green][*] Verifying main SQL index and running any migrations needed...[/green]')
  352. else:
  353. print('\n[green][+] Building main SQL index and running initial migrations...[/green]')
  354. for migration_line in apply_migrations(out_dir):
  355. sys.stdout.write(f' {migration_line}\n')
  356. assert os.path.isfile(CONSTANTS.DATABASE_FILE) and os.access(CONSTANTS.DATABASE_FILE, os.R_OK)
  357. print()
  358. print(f' √ ./{CONSTANTS.DATABASE_FILE.relative_to(DATA_DIR)}')
  359. # from django.contrib.auth.models import User
  360. # if SHELL_CONFIG.IS_TTY and not User.objects.filter(is_superuser=True).exclude(username='system').exists():
  361. # print('{green}[+] Creating admin user account...{reset}'.format(**SHELL_CONFIG.ANSI))
  362. # call_command("createsuperuser", interactive=True)
  363. print()
  364. print('[dodger_blue3][*] Checking links from indexes and archive folders (safe to Ctrl+C)...[/dodger_blue3]')
  365. all_links = Snapshot.objects.none()
  366. pending_links: Dict[str, Link] = {}
  367. if existing_index:
  368. all_links = load_main_index(out_dir=out_dir, warn=False)
  369. print(f' √ Loaded {all_links.count()} links from existing main index.')
  370. if quick:
  371. print(' > Skipping full snapshot directory check (quick mode)')
  372. else:
  373. try:
  374. # Links in data folders that dont match their timestamp
  375. fixed, cant_fix = fix_invalid_folder_locations(out_dir=out_dir)
  376. if fixed:
  377. print(f' [yellow]√ Fixed {len(fixed)} data directory locations that didn\'t match their link timestamps.[/yellow]')
  378. if cant_fix:
  379. print(f' [red]! Could not fix {len(cant_fix)} data directory locations due to conflicts with existing folders.[/red]')
  380. # Links in JSON index but not in main index
  381. orphaned_json_links = {
  382. link.url: link
  383. for link in parse_json_main_index(out_dir)
  384. if not all_links.filter(url=link.url).exists()
  385. }
  386. if orphaned_json_links:
  387. pending_links.update(orphaned_json_links)
  388. print(f' [yellow]√ Added {len(orphaned_json_links)} orphaned links from existing JSON index...[/yellow]')
  389. # Links in data dir indexes but not in main index
  390. orphaned_data_dir_links = {
  391. link.url: link
  392. for link in parse_json_links_details(out_dir)
  393. if not all_links.filter(url=link.url).exists()
  394. }
  395. if orphaned_data_dir_links:
  396. pending_links.update(orphaned_data_dir_links)
  397. print(f' [yellow]√ Added {len(orphaned_data_dir_links)} orphaned links from existing archive directories.[/yellow]')
  398. # Links in invalid/duplicate data dirs
  399. invalid_folders = {
  400. folder: link
  401. for folder, link in get_invalid_folders(all_links, out_dir=out_dir).items()
  402. }
  403. if invalid_folders:
  404. print(f' [red]! Skipped adding {len(invalid_folders)} invalid link data directories.[/red]')
  405. print(' X ' + '\n X '.join(f'./{Path(folder).relative_to(DATA_DIR)} {link}' for folder, link in invalid_folders.items()))
  406. print()
  407. print(' [violet]Hint:[/violet] For more information about the link data directories that were skipped, run:')
  408. print(' archivebox status')
  409. print(' archivebox list --status=invalid')
  410. except (KeyboardInterrupt, SystemExit):
  411. print(file=sys.stderr)
  412. print('[yellow]:stop_sign: Stopped checking archive directories due to Ctrl-C/SIGTERM[/yellow]', file=sys.stderr)
  413. print(' Your archive data is safe, but you should re-run `archivebox init` to finish the process later.', file=sys.stderr)
  414. print(file=sys.stderr)
  415. print(' [violet]Hint:[/violet] In the future you can run a quick init without checking dirs like so:', file=sys.stderr)
  416. print(' archivebox init --quick', file=sys.stderr)
  417. raise SystemExit(1)
  418. write_main_index(list(pending_links.values()), out_dir=out_dir)
  419. print('\n[green]----------------------------------------------------------------------[/green]')
  420. from django.contrib.auth.models import User
  421. if (SERVER_CONFIG.ADMIN_USERNAME and SERVER_CONFIG.ADMIN_PASSWORD) and not User.objects.filter(username=SERVER_CONFIG.ADMIN_USERNAME).exists():
  422. print('[green][+] Found ADMIN_USERNAME and ADMIN_PASSWORD configuration options, creating new admin user.[/green]')
  423. User.objects.create_superuser(username=SERVER_CONFIG.ADMIN_USERNAME, password=SERVER_CONFIG.ADMIN_PASSWORD)
  424. if existing_index:
  425. print('[green][√] Done. Verified and updated the existing ArchiveBox collection.[/green]')
  426. else:
  427. print(f'[green][√] Done. A new ArchiveBox collection was initialized ({len(all_links) + len(pending_links)} links).[/green]')
  428. json_index = out_dir / CONSTANTS.JSON_INDEX_FILENAME
  429. html_index = out_dir / CONSTANTS.HTML_INDEX_FILENAME
  430. index_name = f"{date.today()}_index_old"
  431. if os.access(json_index, os.F_OK):
  432. json_index.rename(f"{index_name}.json")
  433. if os.access(html_index, os.F_OK):
  434. html_index.rename(f"{index_name}.html")
  435. CONSTANTS.PERSONAS_DIR.mkdir(parents=True, exist_ok=True)
  436. CONSTANTS.DEFAULT_TMP_DIR.mkdir(parents=True, exist_ok=True)
  437. CONSTANTS.DEFAULT_LIB_DIR.mkdir(parents=True, exist_ok=True)
  438. from archivebox.config.common import STORAGE_CONFIG
  439. STORAGE_CONFIG.TMP_DIR.mkdir(parents=True, exist_ok=True)
  440. STORAGE_CONFIG.LIB_DIR.mkdir(parents=True, exist_ok=True)
  441. if install:
  442. run_subcommand('install', pwd=out_dir)
  443. if Snapshot.objects.count() < 25: # hide the hints for experienced users
  444. print()
  445. print(' [violet]Hint:[/violet] To view your archive index, run:')
  446. print(' archivebox server # then visit [deep_sky_blue4][link=http://127.0.0.1:8000]http://127.0.0.1:8000[/link][/deep_sky_blue4]')
  447. print()
  448. print(' To add new links, you can run:')
  449. print(" archivebox add < ~/some/path/to/list_of_links.txt")
  450. print()
  451. print(' For more usage and examples, run:')
  452. print(' archivebox help')
  453. @enforce_types
  454. def status(out_dir: Path=DATA_DIR) -> None:
  455. """Print out some info and statistics about the archive collection"""
  456. check_data_folder()
  457. from core.models import Snapshot
  458. from django.contrib.auth import get_user_model
  459. User = get_user_model()
  460. print('{green}[*] Scanning archive main index...{reset}'.format(**SHELL_CONFIG.ANSI))
  461. print(SHELL_CONFIG.ANSI['lightyellow'], f' {out_dir}/*', SHELL_CONFIG.ANSI['reset'])
  462. num_bytes, num_dirs, num_files = get_dir_size(out_dir, recursive=False, pattern='index.')
  463. size = printable_filesize(num_bytes)
  464. print(f' Index size: {size} across {num_files} files')
  465. print()
  466. links = load_main_index(out_dir=out_dir)
  467. num_sql_links = links.count()
  468. num_link_details = sum(1 for link in parse_json_links_details(out_dir=out_dir))
  469. print(f' > SQL Main Index: {num_sql_links} links'.ljust(36), f'(found in {CONSTANTS.SQL_INDEX_FILENAME})')
  470. print(f' > JSON Link Details: {num_link_details} links'.ljust(36), f'(found in {ARCHIVE_DIR.name}/*/index.json)')
  471. print()
  472. print('{green}[*] Scanning archive data directories...{reset}'.format(**SHELL_CONFIG.ANSI))
  473. print(SHELL_CONFIG.ANSI['lightyellow'], f' {ARCHIVE_DIR}/*', SHELL_CONFIG.ANSI['reset'])
  474. num_bytes, num_dirs, num_files = get_dir_size(ARCHIVE_DIR)
  475. size = printable_filesize(num_bytes)
  476. print(f' Size: {size} across {num_files} files in {num_dirs} directories')
  477. print(SHELL_CONFIG.ANSI['black'])
  478. num_indexed = len(get_indexed_folders(links, out_dir=out_dir))
  479. num_archived = len(get_archived_folders(links, out_dir=out_dir))
  480. num_unarchived = len(get_unarchived_folders(links, out_dir=out_dir))
  481. print(f' > indexed: {num_indexed}'.ljust(36), f'({get_indexed_folders.__doc__})')
  482. print(f' > archived: {num_archived}'.ljust(36), f'({get_archived_folders.__doc__})')
  483. print(f' > unarchived: {num_unarchived}'.ljust(36), f'({get_unarchived_folders.__doc__})')
  484. num_present = len(get_present_folders(links, out_dir=out_dir))
  485. num_valid = len(get_valid_folders(links, out_dir=out_dir))
  486. print()
  487. print(f' > present: {num_present}'.ljust(36), f'({get_present_folders.__doc__})')
  488. print(f' > valid: {num_valid}'.ljust(36), f'({get_valid_folders.__doc__})')
  489. duplicate = get_duplicate_folders(links, out_dir=out_dir)
  490. orphaned = get_orphaned_folders(links, out_dir=out_dir)
  491. corrupted = get_corrupted_folders(links, out_dir=out_dir)
  492. unrecognized = get_unrecognized_folders(links, out_dir=out_dir)
  493. num_invalid = len({**duplicate, **orphaned, **corrupted, **unrecognized})
  494. print(f' > invalid: {num_invalid}'.ljust(36), f'({get_invalid_folders.__doc__})')
  495. print(f' > duplicate: {len(duplicate)}'.ljust(36), f'({get_duplicate_folders.__doc__})')
  496. print(f' > orphaned: {len(orphaned)}'.ljust(36), f'({get_orphaned_folders.__doc__})')
  497. print(f' > corrupted: {len(corrupted)}'.ljust(36), f'({get_corrupted_folders.__doc__})')
  498. print(f' > unrecognized: {len(unrecognized)}'.ljust(36), f'({get_unrecognized_folders.__doc__})')
  499. print(SHELL_CONFIG.ANSI['reset'])
  500. if num_indexed:
  501. print(' {lightred}Hint:{reset} You can list link data directories by status like so:'.format(**SHELL_CONFIG.ANSI))
  502. print(' archivebox list --status=<status> (e.g. indexed, corrupted, archived, etc.)')
  503. if orphaned:
  504. print(' {lightred}Hint:{reset} To automatically import orphaned data directories into the main index, run:'.format(**SHELL_CONFIG.ANSI))
  505. print(' archivebox init')
  506. if num_invalid:
  507. print(' {lightred}Hint:{reset} You may need to manually remove or fix some invalid data directories, afterwards make sure to run:'.format(**SHELL_CONFIG.ANSI))
  508. print(' archivebox init')
  509. print()
  510. print('{green}[*] Scanning recent archive changes and user logins:{reset}'.format(**SHELL_CONFIG.ANSI))
  511. print(SHELL_CONFIG.ANSI['lightyellow'], f' {CONSTANTS.LOGS_DIR}/*', SHELL_CONFIG.ANSI['reset'])
  512. users = get_admins().values_list('username', flat=True)
  513. print(f' UI users {len(users)}: {", ".join(users)}')
  514. last_login = User.objects.order_by('last_login').last()
  515. if last_login:
  516. print(f' Last UI login: {last_login.username} @ {str(last_login.last_login)[:16]}')
  517. last_downloaded = Snapshot.objects.order_by('downloaded_at').last()
  518. if last_downloaded:
  519. print(f' Last changes: {str(last_downloaded.downloaded_at)[:16]}')
  520. if not users:
  521. print()
  522. print(' {lightred}Hint:{reset} You can create an admin user by running:'.format(**SHELL_CONFIG.ANSI))
  523. print(' archivebox manage createsuperuser')
  524. print()
  525. for snapshot in links.order_by('-downloaded_at')[:10]:
  526. if not snapshot.downloaded_at:
  527. continue
  528. print(
  529. SHELL_CONFIG.ANSI['black'],
  530. (
  531. f' > {str(snapshot.downloaded_at)[:16]} '
  532. f'[{snapshot.num_outputs} {("X", "√")[snapshot.is_archived]} {printable_filesize(snapshot.archive_size)}] '
  533. f'"{snapshot.title}": {snapshot.url}'
  534. )[:SHELL_CONFIG.TERM_WIDTH],
  535. SHELL_CONFIG.ANSI['reset'],
  536. )
  537. print(SHELL_CONFIG.ANSI['black'], ' ...', SHELL_CONFIG.ANSI['reset'])
  538. @enforce_types
  539. def oneshot(url: str, extractors: str="", out_dir: Path=DATA_DIR, created_by_id: int | None=None) -> List[Link]:
  540. """
  541. Create a single URL archive folder with an index.json and index.html, and all the archive method outputs.
  542. You can run this to archive single pages without needing to create a whole collection with archivebox init.
  543. """
  544. oneshot_link, _ = parse_links_memory([url])
  545. if len(oneshot_link) > 1:
  546. stderr(
  547. '[X] You should pass a single url to the oneshot command',
  548. color='red'
  549. )
  550. raise SystemExit(2)
  551. methods = extractors.split(",") if extractors else ignore_methods(['title'])
  552. archive_link(oneshot_link[0], out_dir=out_dir, methods=methods, created_by_id=created_by_id)
  553. return oneshot_link
  554. @enforce_types
  555. def add(urls: Union[str, List[str]],
  556. tag: str='',
  557. depth: int=0,
  558. update: bool=not ARCHIVING_CONFIG.ONLY_NEW,
  559. update_all: bool=False,
  560. index_only: bool=False,
  561. overwrite: bool=False,
  562. # duplicate: bool=False, # TODO: reuse the logic from admin.py resnapshot to allow adding multiple snapshots by appending timestamp automatically
  563. init: bool=False,
  564. extractors: str="",
  565. parser: str="auto",
  566. created_by_id: int | None=None,
  567. out_dir: Path=DATA_DIR) -> List[Link]:
  568. """Add a new URL or list of URLs to your archive"""
  569. from core.models import Snapshot, Tag
  570. # from queues.supervisor_util import start_cli_workers, tail_worker_logs
  571. # from queues.tasks import bg_archive_link
  572. assert depth in (0, 1), 'Depth must be 0 or 1 (depth >1 is not supported yet)'
  573. extractors = extractors.split(",") if extractors else []
  574. if init:
  575. run_subcommand('init', stdin=None, pwd=out_dir)
  576. # Load list of links from the existing index
  577. check_data_folder()
  578. # worker = start_cli_workers()
  579. new_links: List[Link] = []
  580. all_links = load_main_index(out_dir=out_dir)
  581. log_importing_started(urls=urls, depth=depth, index_only=index_only)
  582. if isinstance(urls, str):
  583. # save verbatim stdin to sources
  584. write_ahead_log = save_text_as_source(urls, filename='{ts}-import.txt', out_dir=out_dir)
  585. elif isinstance(urls, list):
  586. # save verbatim args to sources
  587. write_ahead_log = save_text_as_source('\n'.join(urls), filename='{ts}-import.txt', out_dir=out_dir)
  588. new_links += parse_links_from_source(write_ahead_log, root_url=None, parser=parser)
  589. # If we're going one level deeper, download each link and look for more links
  590. new_links_depth = []
  591. if new_links and depth == 1:
  592. log_crawl_started(new_links)
  593. for new_link in new_links:
  594. try:
  595. downloaded_file = save_file_as_source(new_link.url, filename=f'{new_link.timestamp}-crawl-{new_link.domain}.txt', out_dir=out_dir)
  596. new_links_depth += parse_links_from_source(downloaded_file, root_url=new_link.url)
  597. except Exception as err:
  598. stderr('[!] Failed to get contents of URL {new_link.url}', err, color='red')
  599. imported_links = list({link.url: link for link in (new_links + new_links_depth)}.values())
  600. new_links = dedupe_links(all_links, imported_links)
  601. write_main_index(links=new_links, out_dir=out_dir, created_by_id=created_by_id)
  602. all_links = load_main_index(out_dir=out_dir)
  603. tags = [
  604. Tag.objects.get_or_create(name=name.strip(), defaults={'created_by_id': created_by_id})[0]
  605. for name in tag.split(',')
  606. if name.strip()
  607. ]
  608. if tags:
  609. for link in imported_links:
  610. snapshot = Snapshot.objects.get(url=link.url)
  611. snapshot.tags.add(*tags)
  612. snapshot.tags_str(nocache=True)
  613. snapshot.save()
  614. # print(f' √ Tagged {len(imported_links)} Snapshots with {len(tags)} tags {tags_str}')
  615. if index_only:
  616. # mock archive all the links using the fake index_only extractor method in order to update their state
  617. if overwrite:
  618. archive_links(imported_links, overwrite=overwrite, methods=['index_only'], out_dir=out_dir, created_by_id=created_by_id)
  619. else:
  620. archive_links(new_links, overwrite=False, methods=['index_only'], out_dir=out_dir, created_by_id=created_by_id)
  621. else:
  622. # fully run the archive extractor methods for each link
  623. archive_kwargs = {
  624. "out_dir": out_dir,
  625. "created_by_id": created_by_id,
  626. }
  627. if extractors:
  628. archive_kwargs["methods"] = extractors
  629. stderr()
  630. ts = datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S')
  631. if update:
  632. stderr(f'[*] [{ts}] Archiving + updating {len(imported_links)}/{len(all_links)}', len(imported_links), 'URLs from added set...', color='green')
  633. archive_links(imported_links, overwrite=overwrite, **archive_kwargs)
  634. elif update_all:
  635. stderr(f'[*] [{ts}] Archiving + updating {len(all_links)}/{len(all_links)}', len(all_links), 'URLs from entire library...', color='green')
  636. archive_links(all_links, overwrite=overwrite, **archive_kwargs)
  637. elif overwrite:
  638. stderr(f'[*] [{ts}] Archiving + overwriting {len(imported_links)}/{len(all_links)}', len(imported_links), 'URLs from added set...', color='green')
  639. archive_links(imported_links, overwrite=True, **archive_kwargs)
  640. elif new_links:
  641. stderr(f'[*] [{ts}] Archiving {len(new_links)}/{len(all_links)} URLs from added set...', color='green')
  642. archive_links(new_links, overwrite=False, **archive_kwargs)
  643. # tail_worker_logs(worker['stdout_logfile'])
  644. # if CAN_UPGRADE:
  645. # hint(f"There's a new version of ArchiveBox available! Your current version is {VERSION}. You can upgrade to {VERSIONS_AVAILABLE['recommended_version']['tag_name']} ({VERSIONS_AVAILABLE['recommended_version']['html_url']}). For more on how to upgrade: https://github.com/ArchiveBox/ArchiveBox/wiki/Upgrading-or-Merging-Archives\n")
  646. return new_links
  647. @enforce_types
  648. def remove(filter_str: Optional[str]=None,
  649. filter_patterns: Optional[List[str]]=None,
  650. filter_type: str='exact',
  651. snapshots: Optional[QuerySet]=None,
  652. after: Optional[float]=None,
  653. before: Optional[float]=None,
  654. yes: bool=False,
  655. delete: bool=False,
  656. out_dir: Path=DATA_DIR) -> List[Link]:
  657. """Remove the specified URLs from the archive"""
  658. check_data_folder()
  659. if snapshots is None:
  660. if filter_str and filter_patterns:
  661. stderr(
  662. '[X] You should pass either a pattern as an argument, '
  663. 'or pass a list of patterns via stdin, but not both.\n',
  664. color='red',
  665. )
  666. raise SystemExit(2)
  667. elif not (filter_str or filter_patterns):
  668. stderr(
  669. '[X] You should pass either a pattern as an argument, '
  670. 'or pass a list of patterns via stdin.',
  671. color='red',
  672. )
  673. stderr()
  674. hint(('To remove all urls you can run:',
  675. 'archivebox remove --filter-type=regex ".*"'))
  676. stderr()
  677. raise SystemExit(2)
  678. elif filter_str:
  679. filter_patterns = [ptn.strip() for ptn in filter_str.split('\n')]
  680. list_kwargs = {
  681. "filter_patterns": filter_patterns,
  682. "filter_type": filter_type,
  683. "after": after,
  684. "before": before,
  685. }
  686. if snapshots:
  687. list_kwargs["snapshots"] = snapshots
  688. log_list_started(filter_patterns, filter_type)
  689. timer = TimedProgress(360, prefix=' ')
  690. try:
  691. snapshots = list_links(**list_kwargs)
  692. finally:
  693. timer.end()
  694. if not snapshots.exists():
  695. log_removal_finished(0, 0)
  696. raise SystemExit(1)
  697. log_links = [link.as_link() for link in snapshots]
  698. log_list_finished(log_links)
  699. log_removal_started(log_links, yes=yes, delete=delete)
  700. timer = TimedProgress(360, prefix=' ')
  701. try:
  702. for snapshot in snapshots:
  703. if delete:
  704. shutil.rmtree(snapshot.as_link().link_dir, ignore_errors=True)
  705. finally:
  706. timer.end()
  707. to_remove = snapshots.count()
  708. from .search import flush_search_index
  709. flush_search_index(snapshots=snapshots)
  710. remove_from_sql_main_index(snapshots=snapshots, out_dir=out_dir)
  711. all_snapshots = load_main_index(out_dir=out_dir)
  712. log_removal_finished(all_snapshots.count(), to_remove)
  713. return all_snapshots
  714. @enforce_types
  715. def update(resume: Optional[float]=None,
  716. only_new: bool=ARCHIVING_CONFIG.ONLY_NEW,
  717. index_only: bool=False,
  718. overwrite: bool=False,
  719. filter_patterns_str: Optional[str]=None,
  720. filter_patterns: Optional[List[str]]=None,
  721. filter_type: Optional[str]=None,
  722. status: Optional[str]=None,
  723. after: Optional[str]=None,
  724. before: Optional[str]=None,
  725. extractors: str="",
  726. out_dir: Path=DATA_DIR) -> List[Link]:
  727. """Import any new links from subscriptions and retry any previously failed/skipped links"""
  728. from core.models import ArchiveResult
  729. from .search import index_links
  730. # from .queues.supervisor_util import start_cli_workers
  731. check_data_folder()
  732. # start_cli_workers()
  733. new_links: List[Link] = [] # TODO: Remove input argument: only_new
  734. extractors = extractors.split(",") if extractors else []
  735. # Step 1: Filter for selected_links
  736. print('[*] Finding matching Snapshots to update...')
  737. print(f' - Filtering by {" ".join(filter_patterns)} ({filter_type}) {before=} {after=} {status=}...')
  738. matching_snapshots = list_links(
  739. filter_patterns=filter_patterns,
  740. filter_type=filter_type,
  741. before=before,
  742. after=after,
  743. )
  744. print(f' - Checking {matching_snapshots.count()} snapshot folders for existing data with {status=}...')
  745. matching_folders = list_folders(
  746. links=matching_snapshots,
  747. status=status,
  748. out_dir=out_dir,
  749. )
  750. all_links = (link for link in matching_folders.values() if link)
  751. print(' - Sorting by most unfinished -> least unfinished + date archived...')
  752. all_links = sorted(all_links, key=lambda link: (ArchiveResult.objects.filter(snapshot__url=link.url).count(), link.timestamp))
  753. if index_only:
  754. for link in all_links:
  755. write_link_details(link, out_dir=out_dir, skip_sql_index=True)
  756. index_links(all_links, out_dir=out_dir)
  757. return all_links
  758. # Step 2: Run the archive methods for each link
  759. to_archive = new_links if only_new else all_links
  760. if resume:
  761. to_archive = [
  762. link for link in to_archive
  763. if link.timestamp >= str(resume)
  764. ]
  765. if not to_archive:
  766. stderr('')
  767. stderr(f'[√] Nothing found to resume after {resume}', color='green')
  768. return all_links
  769. archive_kwargs = {
  770. "out_dir": out_dir,
  771. }
  772. if extractors:
  773. archive_kwargs["methods"] = extractors
  774. archive_links(to_archive, overwrite=overwrite, **archive_kwargs)
  775. # Step 4: Re-write links index with updated titles, icons, and resources
  776. all_links = load_main_index(out_dir=out_dir)
  777. return all_links
  778. @enforce_types
  779. def list_all(filter_patterns_str: Optional[str]=None,
  780. filter_patterns: Optional[List[str]]=None,
  781. filter_type: str='exact',
  782. status: Optional[str]=None,
  783. after: Optional[float]=None,
  784. before: Optional[float]=None,
  785. sort: Optional[str]=None,
  786. csv: Optional[str]=None,
  787. json: bool=False,
  788. html: bool=False,
  789. with_headers: bool=False,
  790. out_dir: Path=DATA_DIR) -> Iterable[Link]:
  791. """List, filter, and export information about archive entries"""
  792. check_data_folder()
  793. if filter_patterns and filter_patterns_str:
  794. stderr(
  795. '[X] You should either pass filter patterns as an arguments '
  796. 'or via stdin, but not both.\n',
  797. color='red',
  798. )
  799. raise SystemExit(2)
  800. elif filter_patterns_str:
  801. filter_patterns = filter_patterns_str.split('\n')
  802. snapshots = list_links(
  803. filter_patterns=filter_patterns,
  804. filter_type=filter_type,
  805. before=before,
  806. after=after,
  807. )
  808. if sort:
  809. snapshots = snapshots.order_by(sort)
  810. folders = list_folders(
  811. links=snapshots,
  812. status=status,
  813. out_dir=out_dir,
  814. )
  815. if json:
  816. output = generate_json_index_from_links(folders.values(), with_headers)
  817. elif html:
  818. output = generate_index_from_links(folders.values(), with_headers)
  819. elif csv:
  820. output = links_to_csv(folders.values(), cols=csv.split(','), header=with_headers)
  821. else:
  822. output = printable_folders(folders, with_headers=with_headers)
  823. print(output)
  824. return folders
  825. @enforce_types
  826. def list_links(snapshots: Optional[QuerySet]=None,
  827. filter_patterns: Optional[List[str]]=None,
  828. filter_type: str='exact',
  829. after: Optional[float]=None,
  830. before: Optional[float]=None,
  831. out_dir: Path=DATA_DIR) -> Iterable[Link]:
  832. check_data_folder()
  833. if snapshots:
  834. all_snapshots = snapshots
  835. else:
  836. all_snapshots = load_main_index(out_dir=out_dir)
  837. if after is not None:
  838. all_snapshots = all_snapshots.filter(timestamp__gte=after)
  839. if before is not None:
  840. all_snapshots = all_snapshots.filter(timestamp__lt=before)
  841. if filter_patterns:
  842. all_snapshots = snapshot_filter(all_snapshots, filter_patterns, filter_type)
  843. if not all_snapshots:
  844. stderr('[!] No Snapshots matched your filters:', filter_patterns, f'({filter_type})', color='lightyellow')
  845. return all_snapshots
  846. @enforce_types
  847. def list_folders(links: List[Link],
  848. status: str,
  849. out_dir: Path=DATA_DIR) -> Dict[str, Optional[Link]]:
  850. check_data_folder()
  851. STATUS_FUNCTIONS = {
  852. "indexed": get_indexed_folders,
  853. "archived": get_archived_folders,
  854. "unarchived": get_unarchived_folders,
  855. "present": get_present_folders,
  856. "valid": get_valid_folders,
  857. "invalid": get_invalid_folders,
  858. "duplicate": get_duplicate_folders,
  859. "orphaned": get_orphaned_folders,
  860. "corrupted": get_corrupted_folders,
  861. "unrecognized": get_unrecognized_folders,
  862. }
  863. try:
  864. return STATUS_FUNCTIONS[status](links, out_dir=out_dir)
  865. except KeyError:
  866. raise ValueError('Status not recognized.')
  867. @enforce_types
  868. def install(out_dir: Path=DATA_DIR, binproviders: Optional[List[str]]=None, binaries: Optional[List[str]]=None, dry_run: bool=False) -> None:
  869. """Automatically install all ArchiveBox dependencies and extras"""
  870. # if running as root:
  871. # - run init to create index + lib dir
  872. # - chown -R 911 DATA_DIR
  873. # - install all binaries as root
  874. # - chown -R 911 LIB_DIR
  875. # else:
  876. # - run init to create index + lib dir as current user
  877. # - install all binaries as current user
  878. # - recommend user re-run with sudo if any deps need to be installed as root
  879. from rich import print
  880. from django.conf import settings
  881. from archivebox import CONSTANTS
  882. from archivebox.config.permissions import IS_ROOT, ARCHIVEBOX_USER, ARCHIVEBOX_GROUP
  883. if not (os.access(ARCHIVE_DIR, os.R_OK) and ARCHIVE_DIR.is_dir()):
  884. run_subcommand('init', stdin=None, pwd=out_dir) # must init full index because we need a db to store InstalledBinary entries in
  885. print('\n[green][+] Installing ArchiveBox dependencies automatically...[/green]')
  886. # we never want the data dir to be owned by root, detect owner of existing owner of DATA_DIR to try and guess desired non-root UID
  887. if IS_ROOT:
  888. EUID = os.geteuid()
  889. # if we have sudo/root permissions, take advantage of them just while installing dependencies
  890. print()
  891. print(f'[yellow]:warning: Running as UID=[blue]{EUID}[/blue] with [red]sudo[/red] only for dependencies that need it.[/yellow]')
  892. print(f' DATA_DIR, LIB_DIR, and TMP_DIR will be owned by [blue]{ARCHIVEBOX_USER}:{ARCHIVEBOX_GROUP}[/blue].')
  893. print()
  894. package_manager_names = ', '.join(
  895. f'[yellow]{binprovider.name}[/yellow]'
  896. for binprovider in reversed(list(settings.BINPROVIDERS.values()))
  897. if not binproviders or (binproviders and binprovider.name in binproviders)
  898. )
  899. print(f'[+] Setting up package managers {package_manager_names}...')
  900. for binprovider in reversed(list(settings.BINPROVIDERS.values())):
  901. if binproviders and binprovider.name not in binproviders:
  902. continue
  903. try:
  904. binprovider.setup()
  905. except Exception:
  906. # it's ok, installing binaries below will automatically set up package managers as needed
  907. # e.g. if user does not have npm available we cannot set it up here yet, but once npm Binary is installed
  908. # the next package that depends on npm will automatically call binprovider.setup() during its own install
  909. pass
  910. print()
  911. for binary in reversed(list(settings.BINARIES.values())):
  912. if binary.name in ('archivebox', 'django', 'sqlite', 'python'):
  913. # obviously must already be installed if we are running
  914. continue
  915. if binaries and binary.name not in binaries:
  916. continue
  917. providers = ' [grey53]or[/grey53] '.join(
  918. provider.name for provider in binary.binproviders_supported
  919. if not binproviders or (binproviders and provider.name in binproviders)
  920. )
  921. if not providers:
  922. continue
  923. print(f'[+] Detecting / Installing [yellow]{binary.name.ljust(22)}[/yellow] using [red]{providers}[/red]...')
  924. try:
  925. with SudoPermission(uid=0, fallback=True):
  926. # print(binary.load_or_install(fresh=True).model_dump(exclude={'overrides', 'bin_dir', 'hook_type'}))
  927. if binproviders:
  928. providers_supported_by_binary = [provider.name for provider in binary.binproviders_supported]
  929. for binprovider_name in binproviders:
  930. if binprovider_name not in providers_supported_by_binary:
  931. continue
  932. try:
  933. if dry_run:
  934. # always show install commands when doing a dry run
  935. sys.stderr.write("\033[2;49;90m") # grey53
  936. result = binary.install(binproviders=[binprovider_name], dry_run=dry_run).model_dump(exclude={'overrides', 'bin_dir', 'hook_type'})
  937. sys.stderr.write("\033[00m\n") # reset
  938. else:
  939. result = binary.load_or_install(binproviders=[binprovider_name], fresh=True, dry_run=dry_run, quiet=False).model_dump(exclude={'overrides', 'bin_dir', 'hook_type'})
  940. if result and result['loaded_version']:
  941. break
  942. except Exception as e:
  943. print(f'[red]:cross_mark: Failed to install {binary.name} as using {binprovider_name} as user {ARCHIVEBOX_USER}: {e}[/red]')
  944. else:
  945. if dry_run:
  946. sys.stderr.write("\033[2;49;90m") # grey53
  947. binary.install(dry_run=dry_run).model_dump(exclude={'overrides', 'bin_dir', 'hook_type'})
  948. sys.stderr.write("\033[00m\n") # reset
  949. else:
  950. binary.load_or_install(fresh=True, dry_run=dry_run).model_dump(exclude={'overrides', 'bin_dir', 'hook_type'})
  951. if IS_ROOT:
  952. with SudoPermission(uid=0):
  953. if ARCHIVEBOX_USER == 0:
  954. os.system(f'chmod -R 777 "{CONSTANTS.LIB_DIR.resolve()}"')
  955. else:
  956. os.system(f'chown -R {ARCHIVEBOX_USER} "{CONSTANTS.LIB_DIR.resolve()}"')
  957. except Exception as e:
  958. print(f'[red]:cross_mark: Failed to install {binary.name} as user {ARCHIVEBOX_USER}: {e}[/red]')
  959. if binaries and len(binaries) == 1:
  960. # if we are only installing a single binary, raise the exception so the user can see what went wrong
  961. raise
  962. from django.contrib.auth import get_user_model
  963. User = get_user_model()
  964. if not User.objects.filter(is_superuser=True).exclude(username='system').exists():
  965. stderr('\n[+] Don\'t forget to create a new admin user for the Web UI...', color='green')
  966. stderr(' archivebox manage createsuperuser')
  967. # run_subcommand('manage', subcommand_args=['createsuperuser'], pwd=out_dir)
  968. print('\n[green][√] Set up ArchiveBox and its dependencies successfully.[/green]\n', file=sys.stderr)
  969. from plugins_pkg.pip.binaries import ARCHIVEBOX_BINARY
  970. extra_args = []
  971. if binproviders:
  972. extra_args.append(f'--binproviders={",".join(binproviders)}')
  973. if binaries:
  974. extra_args.append(f'--binaries={",".join(binaries)}')
  975. proc = run_shell([ARCHIVEBOX_BINARY.load().abspath, 'version', *extra_args], capture_output=False, cwd=out_dir)
  976. raise SystemExit(proc.returncode)
  977. # backwards-compatibility:
  978. setup = install
  979. @enforce_types
  980. def config(config_options_str: Optional[str]=None,
  981. config_options: Optional[List[str]]=None,
  982. get: bool=False,
  983. set: bool=False,
  984. reset: bool=False,
  985. out_dir: Path=DATA_DIR) -> None:
  986. """Get and set your ArchiveBox project configuration values"""
  987. from rich import print
  988. check_data_folder()
  989. if config_options and config_options_str:
  990. stderr(
  991. '[X] You should either pass config values as an arguments '
  992. 'or via stdin, but not both.\n',
  993. color='red',
  994. )
  995. raise SystemExit(2)
  996. elif config_options_str:
  997. config_options = config_options_str.split('\n')
  998. from django.conf import settings
  999. config_options = config_options or []
  1000. no_args = not (get or set or reset or config_options)
  1001. matching_config = {}
  1002. if get or no_args:
  1003. if config_options:
  1004. config_options = [get_real_name(key) for key in config_options]
  1005. matching_config = {key: settings.FLAT_CONFIG[key] for key in config_options if key in settings.FLAT_CONFIG}
  1006. failed_config = [key for key in config_options if key not in settings.FLAT_CONFIG]
  1007. if failed_config:
  1008. stderr()
  1009. stderr('[X] These options failed to get', color='red')
  1010. stderr(' {}'.format('\n '.join(config_options)))
  1011. raise SystemExit(1)
  1012. else:
  1013. matching_config = settings.FLAT_CONFIG
  1014. print(printable_config(matching_config))
  1015. raise SystemExit(not matching_config)
  1016. elif set:
  1017. new_config = {}
  1018. failed_options = []
  1019. for line in config_options:
  1020. if line.startswith('#') or not line.strip():
  1021. continue
  1022. if '=' not in line:
  1023. stderr('[X] Config KEY=VALUE must have an = sign in it', color='red')
  1024. stderr(f' {line}')
  1025. raise SystemExit(2)
  1026. raw_key, val = line.split('=', 1)
  1027. raw_key = raw_key.upper().strip()
  1028. key = get_real_name(raw_key)
  1029. if key != raw_key:
  1030. stderr(f'[i] Note: The config option {raw_key} has been renamed to {key}, please use the new name going forwards.', color='lightyellow')
  1031. if key in settings.FLAT_CONFIG:
  1032. new_config[key] = val.strip()
  1033. else:
  1034. failed_options.append(line)
  1035. if new_config:
  1036. before = settings.FLAT_CONFIG
  1037. matching_config = write_config_file(new_config, out_dir=DATA_DIR)
  1038. after = load_all_config()
  1039. print(printable_config(matching_config))
  1040. side_effect_changes = {}
  1041. for key, val in after.items():
  1042. if key in settings.FLAT_CONFIG and (before[key] != after[key]) and (key not in matching_config):
  1043. side_effect_changes[key] = after[key]
  1044. if side_effect_changes:
  1045. stderr()
  1046. stderr('[i] Note: This change also affected these other options that depended on it:', color='lightyellow')
  1047. print(' {}'.format(printable_config(side_effect_changes, prefix=' ')))
  1048. if failed_options:
  1049. stderr()
  1050. stderr('[X] These options failed to set (check for typos):', color='red')
  1051. stderr(' {}'.format('\n '.join(failed_options)))
  1052. raise SystemExit(1)
  1053. elif reset:
  1054. stderr('[X] This command is not implemented yet.', color='red')
  1055. stderr(' Please manually remove the relevant lines from your config file:')
  1056. raise SystemExit(2)
  1057. else:
  1058. stderr('[X] You must pass either --get or --set, or no arguments to get the whole config.', color='red')
  1059. stderr(' archivebox config')
  1060. stderr(' archivebox config --get SOME_KEY')
  1061. stderr(' archivebox config --set SOME_KEY=SOME_VALUE')
  1062. raise SystemExit(2)
  1063. @enforce_types
  1064. def schedule(add: bool=False,
  1065. show: bool=False,
  1066. clear: bool=False,
  1067. foreground: bool=False,
  1068. run_all: bool=False,
  1069. quiet: bool=False,
  1070. every: Optional[str]=None,
  1071. tag: str='',
  1072. depth: int=0,
  1073. overwrite: bool=False,
  1074. update: bool=not ARCHIVING_CONFIG.ONLY_NEW,
  1075. import_path: Optional[str]=None,
  1076. out_dir: Path=DATA_DIR):
  1077. """Set ArchiveBox to regularly import URLs at specific times using cron"""
  1078. check_data_folder()
  1079. from archivebox.plugins_pkg.pip.binaries import ARCHIVEBOX_BINARY
  1080. from archivebox.config.permissions import USER
  1081. Path(CONSTANTS.LOGS_DIR).mkdir(exist_ok=True)
  1082. cron = CronTab(user=True)
  1083. cron = dedupe_cron_jobs(cron)
  1084. if clear:
  1085. print(cron.remove_all(comment=CRON_COMMENT))
  1086. cron.write()
  1087. raise SystemExit(0)
  1088. existing_jobs = list(cron.find_comment(CRON_COMMENT))
  1089. if every or add:
  1090. every = every or 'day'
  1091. quoted = lambda s: f'"{s}"' if (s and ' ' in str(s)) else str(s)
  1092. cmd = [
  1093. 'cd',
  1094. quoted(out_dir),
  1095. '&&',
  1096. quoted(ARCHIVEBOX_BINARY.load().abspath),
  1097. *([
  1098. 'add',
  1099. *(['--overwrite'] if overwrite else []),
  1100. *(['--update'] if update else []),
  1101. *([f'--tag={tag}'] if tag else []),
  1102. f'--depth={depth}',
  1103. f'"{import_path}"',
  1104. ] if import_path else ['update']),
  1105. '>>',
  1106. quoted(Path(CONSTANTS.LOGS_DIR) / 'schedule.log'),
  1107. '2>&1',
  1108. ]
  1109. new_job = cron.new(command=' '.join(cmd), comment=CRON_COMMENT)
  1110. if every in ('minute', 'hour', 'day', 'month', 'year'):
  1111. set_every = getattr(new_job.every(), every)
  1112. set_every()
  1113. elif CronSlices.is_valid(every):
  1114. new_job.setall(every)
  1115. else:
  1116. stderr('{red}[X] Got invalid timeperiod for cron task.{reset}'.format(**SHELL_CONFIG.ANSI))
  1117. stderr(' It must be one of minute/hour/day/month')
  1118. stderr(' or a quoted cron-format schedule like:')
  1119. stderr(' archivebox init --every=day --depth=1 https://example.com/some/rss/feed.xml')
  1120. stderr(' archivebox init --every="0/5 * * * *" --depth=1 https://example.com/some/rss/feed.xml')
  1121. raise SystemExit(1)
  1122. cron = dedupe_cron_jobs(cron)
  1123. cron.write()
  1124. total_runs = sum(j.frequency_per_year() for j in cron)
  1125. existing_jobs = list(cron.find_comment(CRON_COMMENT))
  1126. print()
  1127. print('{green}[√] Scheduled new ArchiveBox cron job for user: {} ({} jobs are active).{reset}'.format(USER, len(existing_jobs), **SHELL_CONFIG.ANSI))
  1128. print('\n'.join(f' > {cmd}' if str(cmd) == str(new_job) else f' {cmd}' for cmd in existing_jobs))
  1129. if total_runs > 60 and not quiet:
  1130. stderr()
  1131. stderr('{lightyellow}[!] With the current cron config, ArchiveBox is estimated to run >{} times per year.{reset}'.format(total_runs, **SHELL_CONFIG.ANSI))
  1132. stderr(' Congrats on being an enthusiastic internet archiver! 👌')
  1133. stderr()
  1134. stderr(' Make sure you have enough storage space available to hold all the data.')
  1135. stderr(' Using a compressed/deduped filesystem like ZFS is recommended if you plan on archiving a lot.')
  1136. stderr('')
  1137. elif show:
  1138. if existing_jobs:
  1139. print('\n'.join(str(cmd) for cmd in existing_jobs))
  1140. else:
  1141. stderr('{red}[X] There are no ArchiveBox cron jobs scheduled for your user ({}).{reset}'.format(USER, **SHELL_CONFIG.ANSI))
  1142. stderr(' To schedule a new job, run:')
  1143. stderr(' archivebox schedule --every=[timeperiod] --depth=1 https://example.com/some/rss/feed.xml')
  1144. raise SystemExit(0)
  1145. cron = CronTab(user=True)
  1146. cron = dedupe_cron_jobs(cron)
  1147. existing_jobs = list(cron.find_comment(CRON_COMMENT))
  1148. if foreground or run_all:
  1149. if not existing_jobs:
  1150. stderr('{red}[X] You must schedule some jobs first before running in foreground mode.{reset}'.format(**SHELL_CONFIG.ANSI))
  1151. stderr(' archivebox schedule --every=hour --depth=1 https://example.com/some/rss/feed.xml')
  1152. raise SystemExit(1)
  1153. print('{green}[*] Running {} ArchiveBox jobs in foreground task scheduler...{reset}'.format(len(existing_jobs), **SHELL_CONFIG.ANSI))
  1154. if run_all:
  1155. try:
  1156. for job in existing_jobs:
  1157. sys.stdout.write(f' > {job.command.split("/archivebox ")[0].split(" && ")[0]}\n')
  1158. sys.stdout.write(f' > {job.command.split("/archivebox ")[-1].split(" >> ")[0]}')
  1159. sys.stdout.flush()
  1160. job.run()
  1161. sys.stdout.write(f'\r √ {job.command.split("/archivebox ")[-1]}\n')
  1162. except KeyboardInterrupt:
  1163. print('\n{green}[√] Stopped.{reset}'.format(**SHELL_CONFIG.ANSI))
  1164. raise SystemExit(1)
  1165. if foreground:
  1166. try:
  1167. for job in existing_jobs:
  1168. print(f' > {job.command.split("/archivebox ")[-1].split(" >> ")[0]}')
  1169. for result in cron.run_scheduler():
  1170. print(result)
  1171. except KeyboardInterrupt:
  1172. print('\n{green}[√] Stopped.{reset}'.format(**SHELL_CONFIG.ANSI))
  1173. raise SystemExit(1)
  1174. # if CAN_UPGRADE:
  1175. # hint(f"There's a new version of ArchiveBox available! Your current version is {VERSION}. You can upgrade to {VERSIONS_AVAILABLE['recommended_version']['tag_name']} ({VERSIONS_AVAILABLE['recommended_version']['html_url']}). For more on how to upgrade: https://github.com/ArchiveBox/ArchiveBox/wiki/Upgrading-or-Merging-Archives\n")
  1176. @enforce_types
  1177. def server(runserver_args: Optional[List[str]]=None,
  1178. reload: bool=False,
  1179. debug: bool=False,
  1180. init: bool=False,
  1181. quick_init: bool=False,
  1182. createsuperuser: bool=False,
  1183. daemonize: bool=False,
  1184. out_dir: Path=DATA_DIR) -> None:
  1185. """Run the ArchiveBox HTTP server"""
  1186. from rich import print
  1187. runserver_args = runserver_args or []
  1188. if init:
  1189. run_subcommand('init', stdin=None, pwd=out_dir)
  1190. print()
  1191. elif quick_init:
  1192. run_subcommand('init', subcommand_args=['--quick'], stdin=None, pwd=out_dir)
  1193. print()
  1194. if createsuperuser:
  1195. run_subcommand('manage', subcommand_args=['createsuperuser'], pwd=out_dir)
  1196. print()
  1197. check_data_folder()
  1198. from django.core.management import call_command
  1199. from django.contrib.auth.models import User
  1200. if not User.objects.filter(is_superuser=True).exclude(username='system').exists():
  1201. print()
  1202. # print('[yellow][!] No admin accounts exist, you must create one to be able to log in to the Admin UI![/yellow]')
  1203. print('[violet]Hint:[/violet] To create an [bold]admin username & password[/bold] for the [deep_sky_blue3][underline][link=http://{host}:{port}/admin]Admin UI[/link][/underline][/deep_sky_blue3], run:')
  1204. print(' [green]archivebox manage createsuperuser[/green]')
  1205. print()
  1206. host = '127.0.0.1'
  1207. port = '8000'
  1208. try:
  1209. host_and_port = [arg for arg in runserver_args if arg.replace('.', '').replace(':', '').isdigit()][0]
  1210. if ':' in host_and_port:
  1211. host, port = host_and_port.split(':')
  1212. else:
  1213. if '.' in host_and_port:
  1214. host = host_and_port
  1215. else:
  1216. port = host_and_port
  1217. except IndexError:
  1218. pass
  1219. print('[green][+] Starting ArchiveBox webserver...[/green]')
  1220. print(f' [blink][green]>[/green][/blink] Starting ArchiveBox webserver on [deep_sky_blue4][link=http://{host}:{port}]http://{host}:{port}[/link][/deep_sky_blue4]')
  1221. print(f' [green]>[/green] Log in to ArchiveBox Admin UI on [deep_sky_blue3][link=http://{host}:{port}/admin]http://{host}:{port}/admin[/link][/deep_sky_blue3]')
  1222. print(' > Writing ArchiveBox error log to ./logs/errors.log')
  1223. if SHELL_CONFIG.DEBUG:
  1224. if not reload:
  1225. runserver_args.append('--noreload') # '--insecure'
  1226. call_command("runserver", *runserver_args)
  1227. else:
  1228. from queues.supervisor_util import start_server_workers
  1229. print()
  1230. start_server_workers(host=host, port=port, daemonize=False)
  1231. print("\n[i][green][🟩] ArchiveBox server shut down gracefully.[/green][/i]")
  1232. @enforce_types
  1233. def manage(args: Optional[List[str]]=None, out_dir: Path=DATA_DIR) -> None:
  1234. """Run an ArchiveBox Django management command"""
  1235. check_data_folder()
  1236. from django.core.management import execute_from_command_line
  1237. if (args and "createsuperuser" in args) and (IN_DOCKER and not SHELL_CONFIG.IS_TTY):
  1238. stderr('[!] Warning: you need to pass -it to use interactive commands in docker', color='lightyellow')
  1239. stderr(' docker run -it archivebox manage {}'.format(' '.join(args or ['...'])), color='lightyellow')
  1240. stderr('')
  1241. # import ipdb; ipdb.set_trace()
  1242. execute_from_command_line(['manage.py', *(args or ['help'])])
  1243. @enforce_types
  1244. def shell(out_dir: Path=DATA_DIR) -> None:
  1245. """Enter an interactive ArchiveBox Django shell"""
  1246. check_data_folder()
  1247. from django.core.management import call_command
  1248. call_command("shell_plus")