main.py 44 KB

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