config.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. import os
  2. import re
  3. import sys
  4. import django
  5. import shutil
  6. from typing import Optional
  7. from subprocess import run, PIPE, DEVNULL
  8. # ******************************************************************************
  9. # Documentation: https://github.com/pirate/ArchiveBox/wiki/Configuration
  10. # Use the 'env' command to pass config options to ArchiveBox. e.g.:
  11. # env USE_COLOR=True CHROME_BINARY=google-chrome ./archive export.html
  12. # ******************************************************************************
  13. IS_TTY = sys.stdout.isatty()
  14. USE_COLOR = os.getenv('USE_COLOR', str(IS_TTY) ).lower() == 'true'
  15. SHOW_PROGRESS = os.getenv('SHOW_PROGRESS', str(IS_TTY) ).lower() == 'true'
  16. OUTPUT_DIR = os.getenv('OUTPUT_DIR', '')
  17. ONLY_NEW = os.getenv('ONLY_NEW', 'False' ).lower() == 'true'
  18. TIMEOUT = int(os.getenv('TIMEOUT', '60'))
  19. MEDIA_TIMEOUT = int(os.getenv('MEDIA_TIMEOUT', '3600'))
  20. OUTPUT_PERMISSIONS = os.getenv('OUTPUT_PERMISSIONS', '755' )
  21. FOOTER_INFO = os.getenv('FOOTER_INFO', 'Content is hosted for personal archiving purposes only. Contact server owner for any takedown requests.',)
  22. URL_BLACKLIST = os.getenv('URL_BLACKLIST', None)
  23. FETCH_WGET = os.getenv('FETCH_WGET', 'True' ).lower() == 'true'
  24. FETCH_WGET_REQUISITES = os.getenv('FETCH_WGET_REQUISITES', 'True' ).lower() == 'true'
  25. FETCH_PDF = os.getenv('FETCH_PDF', 'True' ).lower() == 'true'
  26. FETCH_SCREENSHOT = os.getenv('FETCH_SCREENSHOT', 'True' ).lower() == 'true'
  27. FETCH_DOM = os.getenv('FETCH_DOM', 'True' ).lower() == 'true'
  28. FETCH_WARC = os.getenv('FETCH_WARC', 'True' ).lower() == 'true'
  29. FETCH_GIT = os.getenv('FETCH_GIT', 'True' ).lower() == 'true'
  30. FETCH_MEDIA = os.getenv('FETCH_MEDIA', 'True' ).lower() == 'true'
  31. FETCH_FAVICON = os.getenv('FETCH_FAVICON', 'True' ).lower() == 'true'
  32. FETCH_TITLE = os.getenv('FETCH_TITLE', 'True' ).lower() == 'true'
  33. SUBMIT_ARCHIVE_DOT_ORG = os.getenv('SUBMIT_ARCHIVE_DOT_ORG', 'True' ).lower() == 'true'
  34. CHECK_SSL_VALIDITY = os.getenv('CHECK_SSL_VALIDITY', 'True' ).lower() == 'true'
  35. RESOLUTION = os.getenv('RESOLUTION', '1440,2000' )
  36. GIT_DOMAINS = os.getenv('GIT_DOMAINS', 'github.com,bitbucket.org,gitlab.com').split(',')
  37. WGET_USER_AGENT = os.getenv('WGET_USER_AGENT', 'ArchiveBox/{VERSION} (+https://github.com/pirate/ArchiveBox/) wget/{WGET_VERSION}')
  38. COOKIES_FILE = os.getenv('COOKIES_FILE', None)
  39. CHROME_USER_DATA_DIR = os.getenv('CHROME_USER_DATA_DIR', None)
  40. CHROME_HEADLESS = os.getenv('CHROME_HEADLESS', 'True' ).lower() == 'true'
  41. CHROME_USER_AGENT = os.getenv('CHROME_USER_AGENT', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36')
  42. CHROME_SANDBOX = os.getenv('CHROME_SANDBOX', 'True' ).lower() == 'true'
  43. USE_CURL = os.getenv('USE_CURL', 'True' ).lower() == 'true'
  44. USE_WGET = os.getenv('USE_WGET', 'True' ).lower() == 'true'
  45. USE_CHROME = os.getenv('USE_CHROME', 'True' ).lower() == 'true'
  46. CURL_BINARY = os.getenv('CURL_BINARY', 'curl')
  47. GIT_BINARY = os.getenv('GIT_BINARY', 'git')
  48. WGET_BINARY = os.getenv('WGET_BINARY', 'wget')
  49. YOUTUBEDL_BINARY = os.getenv('YOUTUBEDL_BINARY', 'youtube-dl')
  50. CHROME_BINARY = os.getenv('CHROME_BINARY', None)
  51. # ******************************************************************************
  52. ### Terminal Configuration
  53. TERM_WIDTH = lambda: shutil.get_terminal_size((100, 10)).columns
  54. ANSI = {
  55. 'reset': '\033[00;00m',
  56. 'lightblue': '\033[01;30m',
  57. 'lightyellow': '\033[01;33m',
  58. 'lightred': '\033[01;35m',
  59. 'red': '\033[01;31m',
  60. 'green': '\033[01;32m',
  61. 'blue': '\033[01;34m',
  62. 'white': '\033[01;37m',
  63. 'black': '\033[01;30m',
  64. }
  65. if not USE_COLOR:
  66. # dont show colors if USE_COLOR is False
  67. ANSI = {k: '' for k in ANSI.keys()}
  68. REPO_DIR = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..'))
  69. if OUTPUT_DIR:
  70. OUTPUT_DIR = os.path.abspath(OUTPUT_DIR)
  71. else:
  72. OUTPUT_DIR = os.path.abspath(os.curdir)
  73. ARCHIVE_DIR_NAME = 'archive'
  74. SOURCES_DIR_NAME = 'sources'
  75. DATABASE_DIR_NAME = 'database'
  76. ARCHIVE_DIR = os.path.join(OUTPUT_DIR, ARCHIVE_DIR_NAME)
  77. SOURCES_DIR = os.path.join(OUTPUT_DIR, SOURCES_DIR_NAME)
  78. DATABASE_DIR = os.path.join(OUTPUT_DIR, DATABASE_DIR_NAME)
  79. PYTHON_DIR = os.path.join(REPO_DIR, 'archivebox')
  80. LEGACY_DIR = os.path.join(PYTHON_DIR, 'legacy')
  81. TEMPLATES_DIR = os.path.join(LEGACY_DIR, 'templates')
  82. if COOKIES_FILE:
  83. COOKIES_FILE = os.path.abspath(COOKIES_FILE)
  84. URL_BLACKLIST_PTN = re.compile(URL_BLACKLIST, re.IGNORECASE) if URL_BLACKLIST else None
  85. ########################### Environment & Dependencies #########################
  86. VERSION = open(os.path.join(REPO_DIR, 'VERSION'), 'r').read().strip()
  87. GIT_SHA = VERSION.split('+')[-1] or 'unknown'
  88. ### Check Python environment
  89. python_vers = float('{}.{}'.format(sys.version_info.major, sys.version_info.minor))
  90. if python_vers < 3.5:
  91. print('{}[X] Python version is not new enough: {} (>3.5 is required){}'.format(ANSI['red'], python_vers, ANSI['reset']))
  92. print(' See https://github.com/pirate/ArchiveBox/wiki/Troubleshooting#python for help upgrading your Python installation.')
  93. raise SystemExit(1)
  94. if sys.stdout.encoding.upper() not in ('UTF-8', 'UTF8'):
  95. print('[X] Your system is running python3 scripts with a bad locale setting: {} (it should be UTF-8).'.format(sys.stdout.encoding))
  96. print(' To fix it, add the line "export PYTHONIOENCODING=UTF-8" to your ~/.bashrc file (without quotes)')
  97. print('')
  98. print(' Confirm that it\'s fixed by opening a new shell and running:')
  99. print(' python3 -c "import sys; print(sys.stdout.encoding)" # should output UTF-8')
  100. print('')
  101. print(' Alternatively, run this script with:')
  102. print(' env PYTHONIOENCODING=UTF-8 ./archive.py export.html')
  103. # ******************************************************************************
  104. # ***************************** Helper Functions *******************************
  105. # ******************************************************************************
  106. def bin_version(binary: str) -> str:
  107. """check the presence and return valid version line of a specified binary"""
  108. if not shutil.which(binary):
  109. print('{red}[X] Missing dependency: wget{reset}'.format(**ANSI))
  110. print(' Install it, then confirm it works with: {} --version'.format(binary))
  111. print(' See https://github.com/pirate/ArchiveBox/wiki/Install for help.')
  112. raise SystemExit(1)
  113. try:
  114. version_str = run([binary, "--version"], stdout=PIPE, cwd=REPO_DIR).stdout.strip().decode()
  115. return version_str.split('\n')[0].strip()
  116. except Exception:
  117. print('{red}[X] Unable to find a working version of {cmd}, is it installed and in your $PATH?'.format(cmd=binary, **ANSI))
  118. raise SystemExit(1)
  119. def find_chrome_binary() -> str:
  120. """find any installed chrome binaries in the default locations"""
  121. # Precedence: Chromium, Chrome, Beta, Canary, Unstable, Dev
  122. # make sure data dir finding precedence order always matches binary finding order
  123. default_executable_paths = (
  124. 'chromium-browser',
  125. 'chromium',
  126. '/Applications/Chromium.app/Contents/MacOS/Chromium',
  127. 'google-chrome',
  128. '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
  129. 'google-chrome-stable',
  130. 'google-chrome-beta',
  131. 'google-chrome-canary',
  132. '/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary',
  133. 'google-chrome-unstable',
  134. 'google-chrome-dev',
  135. )
  136. for name in default_executable_paths:
  137. full_path_exists = shutil.which(name)
  138. if full_path_exists:
  139. return name
  140. print('{red}[X] Unable to find a working version of Chrome/Chromium, is it installed and in your $PATH?'.format(**ANSI))
  141. raise SystemExit(1)
  142. def find_chrome_data_dir() -> Optional[str]:
  143. """find any installed chrome user data directories in the default locations"""
  144. # Precedence: Chromium, Chrome, Beta, Canary, Unstable, Dev
  145. # make sure data dir finding precedence order always matches binary finding order
  146. default_profile_paths = (
  147. '~/.config/chromium',
  148. '~/Library/Application Support/Chromium',
  149. '~/AppData/Local/Chromium/User Data',
  150. '~/.config/google-chrome',
  151. '~/Library/Application Support/Google/Chrome',
  152. '~/AppData/Local/Google/Chrome/User Data',
  153. '~/.config/google-chrome-stable',
  154. '~/.config/google-chrome-beta',
  155. '~/Library/Application Support/Google/Chrome Canary',
  156. '~/AppData/Local/Google/Chrome SxS/User Data',
  157. '~/.config/google-chrome-unstable',
  158. '~/.config/google-chrome-dev',
  159. )
  160. for path in default_profile_paths:
  161. full_path = os.path.expanduser(path)
  162. if os.path.exists(full_path):
  163. return full_path
  164. return None
  165. # ******************************************************************************
  166. # ************************ Environment & Dependencies **************************
  167. # ******************************************************************************
  168. try:
  169. ### Get Django version
  170. DJANGO_BINARY = django.__file__.replace('__init__.py', 'bin/django-admin.py')
  171. DJANGO_VERSION = '{}.{}.{} {} ({})'.format(*django.VERSION)
  172. ### Make sure curl is installed
  173. if USE_CURL:
  174. USE_CURL = FETCH_FAVICON or SUBMIT_ARCHIVE_DOT_ORG
  175. else:
  176. FETCH_FAVICON = SUBMIT_ARCHIVE_DOT_ORG = False
  177. CURL_VERSION = None
  178. if USE_CURL:
  179. CURL_VERSION = bin_version(CURL_BINARY)
  180. ### Make sure wget is installed and calculate version
  181. if USE_WGET:
  182. USE_WGET = FETCH_WGET or FETCH_WARC
  183. else:
  184. FETCH_WGET = FETCH_WARC = False
  185. WGET_VERSION = None
  186. WGET_AUTO_COMPRESSION = False
  187. if USE_WGET:
  188. WGET_VERSION = bin_version(WGET_BINARY)
  189. WGET_AUTO_COMPRESSION = not run([WGET_BINARY, "--compression=auto", "--help"], stdout=DEVNULL, stderr=DEVNULL).returncode
  190. WGET_USER_AGENT = WGET_USER_AGENT.format(
  191. VERSION=VERSION,
  192. WGET_VERSION=WGET_VERSION or '',
  193. )
  194. ### Make sure git is installed
  195. GIT_VERSION = None
  196. if FETCH_GIT:
  197. GIT_VERSION = bin_version(GIT_BINARY)
  198. ### Make sure youtube-dl is installed
  199. YOUTUBEDL_VERSION = None
  200. if FETCH_MEDIA:
  201. YOUTUBEDL_VERSION = bin_version(YOUTUBEDL_BINARY)
  202. ### Make sure chrome is installed and calculate version
  203. if USE_CHROME:
  204. USE_CHROME = FETCH_PDF or FETCH_SCREENSHOT or FETCH_DOM
  205. else:
  206. FETCH_PDF = FETCH_SCREENSHOT = FETCH_DOM = False
  207. if not CHROME_BINARY:
  208. CHROME_BINARY = find_chrome_binary() or 'chromium-browser'
  209. CHROME_VERSION = None
  210. if USE_CHROME:
  211. if CHROME_BINARY:
  212. CHROME_VERSION = bin_version(CHROME_BINARY)
  213. # print('[i] Using Chrome binary: {}'.format(shutil.which(CHROME_BINARY) or CHROME_BINARY))
  214. if CHROME_USER_DATA_DIR is None:
  215. CHROME_USER_DATA_DIR = find_chrome_data_dir()
  216. # print('[i] Using Chrome data dir: {}'.format(os.path.abspath(CHROME_USER_DATA_DIR)))
  217. CHROME_OPTIONS = {
  218. 'TIMEOUT': TIMEOUT,
  219. 'RESOLUTION': RESOLUTION,
  220. 'CHECK_SSL_VALIDITY': CHECK_SSL_VALIDITY,
  221. 'CHROME_BINARY': CHROME_BINARY,
  222. 'CHROME_HEADLESS': CHROME_HEADLESS,
  223. 'CHROME_SANDBOX': CHROME_SANDBOX,
  224. 'CHROME_USER_AGENT': CHROME_USER_AGENT,
  225. 'CHROME_USER_DATA_DIR': CHROME_USER_DATA_DIR,
  226. }
  227. # PYPPETEER_ARGS = {
  228. # 'headless': CHROME_HEADLESS,
  229. # 'ignoreHTTPSErrors': not CHECK_SSL_VALIDITY,
  230. # # 'executablePath': CHROME_BINARY,
  231. # }
  232. except KeyboardInterrupt:
  233. raise SystemExit(1)
  234. except:
  235. print('[X] There was an error while reading configuration. Your archive data is unaffected.')
  236. raise