main.py 41 KB

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