archive.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. #!/usr/bin/env python3
  2. """
  3. ArchiveBox command line application.
  4. ./archive and ./bin/archivebox both point to this file,
  5. but you can also run it directly using `python3 archive.py`
  6. Usage & Documentation:
  7. https://github.com/pirate/ArchiveBox/Wiki
  8. """
  9. __package__ = 'archivebox'
  10. import os
  11. import sys
  12. import shutil
  13. from typing import List, Optional
  14. from core.schema import Link
  15. from core.links import links_after_timestamp
  16. from core.index import write_links_index, load_links_index
  17. from core.archive_methods import archive_link
  18. from core.config import (
  19. ONLY_NEW,
  20. OUTPUT_DIR,
  21. VERSION,
  22. ANSI,
  23. CURL_VERSION,
  24. GIT_VERSION,
  25. WGET_VERSION,
  26. YOUTUBEDL_VERSION,
  27. CHROME_VERSION,
  28. USE_CURL,
  29. USE_WGET,
  30. USE_CHROME,
  31. CURL_BINARY,
  32. GIT_BINARY,
  33. WGET_BINARY,
  34. YOUTUBEDL_BINARY,
  35. CHROME_BINARY,
  36. FETCH_GIT,
  37. FETCH_MEDIA,
  38. )
  39. from core.util import (
  40. enforce_types,
  41. handle_stdin_import,
  42. handle_file_import,
  43. )
  44. from core.logs import (
  45. log_archiving_started,
  46. log_archiving_paused,
  47. log_archiving_finished,
  48. )
  49. __AUTHOR__ = 'Nick Sweeting <[email protected]>'
  50. __VERSION__ = VERSION
  51. __DESCRIPTION__ = 'ArchiveBox: The self-hosted internet archive.'
  52. __DOCUMENTATION__ = 'https://github.com/pirate/ArchiveBox/wiki'
  53. def print_help():
  54. print('ArchiveBox: The self-hosted internet archive.\n')
  55. print("Documentation:")
  56. print(" https://github.com/pirate/ArchiveBox/wiki\n")
  57. print("UI Usage:")
  58. print(" Open output/index.html to view your archive.\n")
  59. print("CLI Usage:")
  60. print(" mkdir data; cd data/")
  61. print(" archivebox init\n")
  62. print(" echo 'https://example.com/some/page' | archivebox add")
  63. print(" archivebox add https://example.com/some/other/page")
  64. print(" archivebox add --depth=1 ~/Downloads/bookmarks_export.html")
  65. print(" archivebox add --depth=1 https://example.com/feed.rss")
  66. print(" archivebox update --resume=15109948213.123")
  67. def print_version():
  68. print('ArchiveBox v{}'.format(__VERSION__))
  69. print()
  70. print(
  71. '[{}] CURL:'.format('√' if USE_CURL else 'X').ljust(14),
  72. '{} --version\n'.format(shutil.which(CURL_BINARY)),
  73. ' '*13, CURL_VERSION, '\n',
  74. )
  75. print(
  76. '[{}] GIT:'.format('√' if FETCH_GIT else 'X').ljust(14),
  77. '{} --version\n'.format(shutil.which(GIT_BINARY)),
  78. ' '*13, GIT_VERSION, '\n',
  79. )
  80. print(
  81. '[{}] WGET:'.format('√' if USE_WGET else 'X').ljust(14),
  82. '{} --version\n'.format(shutil.which(WGET_BINARY)),
  83. ' '*13, WGET_VERSION, '\n',
  84. )
  85. print(
  86. '[{}] YOUTUBEDL:'.format('√' if FETCH_MEDIA else 'X').ljust(14),
  87. '{} --version\n'.format(shutil.which(YOUTUBEDL_BINARY)),
  88. ' '*13, YOUTUBEDL_VERSION, '\n',
  89. )
  90. print(
  91. '[{}] CHROME:'.format('√' if USE_CHROME else 'X').ljust(14),
  92. '{} --version\n'.format(shutil.which(CHROME_BINARY)),
  93. ' '*13, CHROME_VERSION, '\n',
  94. )
  95. def main(args=None) -> None:
  96. if args is None:
  97. args = sys.argv
  98. if set(args).intersection(('-h', '--help', 'help')) or len(args) > 2:
  99. print_help()
  100. raise SystemExit(0)
  101. if set(args).intersection(('--version', 'version')):
  102. print_version()
  103. raise SystemExit(0)
  104. ### Handle CLI arguments
  105. # ./archive bookmarks.html
  106. # ./archive 1523422111.234
  107. import_path, resume = None, None
  108. if len(args) == 2:
  109. # if the argument is a string, it's a import_path file to import
  110. # if it's a number, it's a timestamp to resume archiving from
  111. if args[1].replace('.', '').isdigit():
  112. import_path, resume = None, args[1]
  113. else:
  114. import_path, resume = args[1], None
  115. ### Set up output folder
  116. if not os.path.exists(OUTPUT_DIR):
  117. print('{green}[+] Created a new archive directory: {}{reset}'.format(OUTPUT_DIR, **ANSI))
  118. os.makedirs(OUTPUT_DIR)
  119. else:
  120. not_empty = len(set(os.listdir(OUTPUT_DIR)) - {'.DS_Store'})
  121. index_exists = os.path.exists(os.path.join(OUTPUT_DIR, 'index.json'))
  122. if not_empty and not index_exists:
  123. print(
  124. ("{red}[X] Could not find index.json in the OUTPUT_DIR: {reset}{}\n\n"
  125. " If you're trying to update an existing archive, you must set OUTPUT_DIR to or run archivebox from inside the archive folder you're trying to update.\n"
  126. " If you're trying to create a new archive, you must run archivebox inside a completely empty directory."
  127. "\n\n"
  128. " {lightred}Hint:{reset} To import a data folder created by an older version of ArchiveBox, \n"
  129. " just cd into the folder and run the archivebox command to pick up where you left off.\n\n"
  130. " (Always make sure your data folder is backed up first before updating ArchiveBox)"
  131. ).format(OUTPUT_DIR, **ANSI)
  132. )
  133. raise SystemExit(1)
  134. ### Handle ingesting urls piped in through stdin
  135. # (.e.g if user does cat example_urls.txt | ./archive)
  136. if not sys.stdin.isatty():
  137. stdin_raw_text = sys.stdin.read()
  138. if stdin_raw_text and import_path:
  139. print(
  140. '[X] You should pass either a path as an argument, '
  141. 'or pass a list of links via stdin, but not both.\n'
  142. )
  143. print_help()
  144. raise SystemExit(1)
  145. import_path = handle_stdin_import(stdin_raw_text)
  146. ### Handle ingesting url from a remote file/feed
  147. # (e.g. if an RSS feed URL is used as the import path)
  148. if import_path:
  149. import_path = handle_file_import(import_path)
  150. ### Run the main archive update process
  151. update_archive_data(import_path=import_path, resume=resume)
  152. @enforce_types
  153. def update_archive_data(import_path: Optional[str]=None, resume: Optional[float]=None) -> List[Link]:
  154. """The main ArchiveBox entrancepoint. Everything starts here."""
  155. # Step 1: Load list of links from the existing index
  156. # merge in and dedupe new links from import_path
  157. all_links, new_links = load_links_index(out_dir=OUTPUT_DIR, import_path=import_path)
  158. # Step 2: Write updated index with deduped old and new links back to disk
  159. write_links_index(links=list(all_links), out_dir=OUTPUT_DIR)
  160. # Step 3: Run the archive methods for each link
  161. links = new_links if ONLY_NEW else all_links
  162. log_archiving_started(len(links), resume)
  163. idx: int = 0
  164. link: Optional[Link] = None
  165. try:
  166. for idx, link in enumerate(links_after_timestamp(links, resume)):
  167. archive_link(link, link_dir=link.link_dir)
  168. except KeyboardInterrupt:
  169. log_archiving_paused(len(links), idx, link.timestamp if link else '0')
  170. raise SystemExit(0)
  171. except:
  172. print()
  173. raise
  174. log_archiving_finished(len(links))
  175. # Step 4: Re-write links index with updated titles, icons, and resources
  176. all_links, _ = load_links_index(out_dir=OUTPUT_DIR)
  177. write_links_index(links=list(all_links), out_dir=OUTPUT_DIR, finished=True)
  178. return all_links
  179. if __name__ == '__main__':
  180. main(sys.argv)