main.py 38 KB

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