main.py 44 KB

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