main.py 64 KB

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