config.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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(os.path.expanduser(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. DATABASE_FILE = os.path.join(DATABASE_DIR, 'database.sqlite3')
  80. PYTHON_DIR = os.path.join(REPO_DIR, 'archivebox')
  81. LEGACY_DIR = os.path.join(PYTHON_DIR, 'legacy')
  82. TEMPLATES_DIR = os.path.join(LEGACY_DIR, 'templates')
  83. if COOKIES_FILE:
  84. COOKIES_FILE = os.path.abspath(os.path.expanduser(COOKIES_FILE))
  85. if CHROME_USER_DATA_DIR:
  86. CHROME_USER_DATA_DIR = os.path.abspath(os.path.expanduser(CHROME_USER_DATA_DIR))
  87. URL_BLACKLIST_PTN = re.compile(URL_BLACKLIST, re.IGNORECASE) if URL_BLACKLIST else None
  88. ########################### Environment & Dependencies #########################
  89. VERSION = open(os.path.join(REPO_DIR, 'VERSION'), 'r').read().strip()
  90. GIT_SHA = VERSION.split('+')[-1] or 'unknown'
  91. ### Check Python environment
  92. python_vers = float('{}.{}'.format(sys.version_info.major, sys.version_info.minor))
  93. if python_vers < 3.5:
  94. print('{}[X] Python version is not new enough: {} (>3.5 is required){}'.format(ANSI['red'], python_vers, ANSI['reset']))
  95. print(' See https://github.com/pirate/ArchiveBox/wiki/Troubleshooting#python for help upgrading your Python installation.')
  96. raise SystemExit(1)
  97. if sys.stdout.encoding.upper() not in ('UTF-8', 'UTF8'):
  98. print('[X] Your system is running python3 scripts with a bad locale setting: {} (it should be UTF-8).'.format(sys.stdout.encoding))
  99. print(' To fix it, add the line "export PYTHONIOENCODING=UTF-8" to your ~/.bashrc file (without quotes)')
  100. print('')
  101. print(' Confirm that it\'s fixed by opening a new shell and running:')
  102. print(' python3 -c "import sys; print(sys.stdout.encoding)" # should output UTF-8')
  103. print('')
  104. print(' Alternatively, run this script with:')
  105. print(' env PYTHONIOENCODING=UTF-8 ./archive.py export.html')
  106. # ******************************************************************************
  107. # ***************************** Helper Functions *******************************
  108. # ******************************************************************************
  109. def bin_version(binary: str) -> str:
  110. """check the presence and return valid version line of a specified binary"""
  111. if not shutil.which(binary):
  112. print('{red}[X] Missing dependency: wget{reset}'.format(**ANSI))
  113. print(' Install it, then confirm it works with: {} --version'.format(binary))
  114. print(' See https://github.com/pirate/ArchiveBox/wiki/Install for help.')
  115. raise SystemExit(1)
  116. try:
  117. version_str = run([binary, "--version"], stdout=PIPE, cwd=REPO_DIR).stdout.strip().decode()
  118. return version_str.split('\n')[0].strip()
  119. except Exception:
  120. print('{red}[X] Unable to find a working version of {cmd}, is it installed and in your $PATH?'.format(cmd=binary, **ANSI))
  121. raise SystemExit(1)
  122. def find_chrome_binary() -> str:
  123. """find any installed chrome binaries in the default locations"""
  124. # Precedence: Chromium, Chrome, Beta, Canary, Unstable, Dev
  125. # make sure data dir finding precedence order always matches binary finding order
  126. default_executable_paths = (
  127. 'chromium-browser',
  128. 'chromium',
  129. '/Applications/Chromium.app/Contents/MacOS/Chromium',
  130. 'google-chrome',
  131. '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
  132. 'google-chrome-stable',
  133. 'google-chrome-beta',
  134. 'google-chrome-canary',
  135. '/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary',
  136. 'google-chrome-unstable',
  137. 'google-chrome-dev',
  138. )
  139. for name in default_executable_paths:
  140. full_path_exists = shutil.which(name)
  141. if full_path_exists:
  142. return name
  143. print('{red}[X] Unable to find a working version of Chrome/Chromium, is it installed and in your $PATH?'.format(**ANSI))
  144. raise SystemExit(1)
  145. def find_chrome_data_dir() -> Optional[str]:
  146. """find any installed chrome user data directories in the default locations"""
  147. # Precedence: Chromium, Chrome, Beta, Canary, Unstable, Dev
  148. # make sure data dir finding precedence order always matches binary finding order
  149. default_profile_paths = (
  150. '~/.config/chromium',
  151. '~/Library/Application Support/Chromium',
  152. '~/AppData/Local/Chromium/User Data',
  153. '~/.config/google-chrome',
  154. '~/Library/Application Support/Google/Chrome',
  155. '~/AppData/Local/Google/Chrome/User Data',
  156. '~/.config/google-chrome-stable',
  157. '~/.config/google-chrome-beta',
  158. '~/Library/Application Support/Google/Chrome Canary',
  159. '~/AppData/Local/Google/Chrome SxS/User Data',
  160. '~/.config/google-chrome-unstable',
  161. '~/.config/google-chrome-dev',
  162. )
  163. for path in default_profile_paths:
  164. full_path = os.path.expanduser(path)
  165. if os.path.exists(full_path):
  166. return full_path
  167. return None
  168. # ******************************************************************************
  169. # ************************ Environment & Dependencies **************************
  170. # ******************************************************************************
  171. try:
  172. ### Get Django version
  173. DJANGO_BINARY = django.__file__.replace('__init__.py', 'bin/django-admin.py')
  174. DJANGO_VERSION = '{}.{}.{} {} ({})'.format(*django.VERSION)
  175. ### Make sure curl is installed
  176. if USE_CURL:
  177. USE_CURL = FETCH_FAVICON or SUBMIT_ARCHIVE_DOT_ORG
  178. else:
  179. FETCH_FAVICON = SUBMIT_ARCHIVE_DOT_ORG = False
  180. CURL_VERSION = None
  181. if USE_CURL:
  182. CURL_VERSION = bin_version(CURL_BINARY)
  183. ### Make sure wget is installed and calculate version
  184. if USE_WGET:
  185. USE_WGET = FETCH_WGET or FETCH_WARC
  186. else:
  187. FETCH_WGET = FETCH_WARC = False
  188. WGET_VERSION = None
  189. WGET_AUTO_COMPRESSION = False
  190. if USE_WGET:
  191. WGET_VERSION = bin_version(WGET_BINARY)
  192. WGET_AUTO_COMPRESSION = not run([WGET_BINARY, "--compression=auto", "--help"], stdout=DEVNULL, stderr=DEVNULL).returncode
  193. WGET_USER_AGENT = WGET_USER_AGENT.format(
  194. VERSION=VERSION,
  195. WGET_VERSION=WGET_VERSION or '',
  196. )
  197. ### Make sure git is installed
  198. GIT_VERSION = None
  199. if FETCH_GIT:
  200. GIT_VERSION = bin_version(GIT_BINARY)
  201. ### Make sure youtube-dl is installed
  202. YOUTUBEDL_VERSION = None
  203. if FETCH_MEDIA:
  204. YOUTUBEDL_VERSION = bin_version(YOUTUBEDL_BINARY)
  205. ### Make sure chrome is installed and calculate version
  206. if USE_CHROME:
  207. USE_CHROME = FETCH_PDF or FETCH_SCREENSHOT or FETCH_DOM
  208. else:
  209. FETCH_PDF = FETCH_SCREENSHOT = FETCH_DOM = False
  210. if not CHROME_BINARY:
  211. CHROME_BINARY = find_chrome_binary() or 'chromium-browser'
  212. CHROME_VERSION = None
  213. if USE_CHROME:
  214. if CHROME_BINARY:
  215. CHROME_VERSION = bin_version(CHROME_BINARY)
  216. # print('[i] Using Chrome binary: {}'.format(shutil.which(CHROME_BINARY) or CHROME_BINARY))
  217. if CHROME_USER_DATA_DIR is None:
  218. CHROME_USER_DATA_DIR = find_chrome_data_dir()
  219. # print('[i] Using Chrome data dir: {}'.format(os.path.abspath(CHROME_USER_DATA_DIR)))
  220. CHROME_OPTIONS = {
  221. 'TIMEOUT': TIMEOUT,
  222. 'RESOLUTION': RESOLUTION,
  223. 'CHECK_SSL_VALIDITY': CHECK_SSL_VALIDITY,
  224. 'CHROME_BINARY': CHROME_BINARY,
  225. 'CHROME_HEADLESS': CHROME_HEADLESS,
  226. 'CHROME_SANDBOX': CHROME_SANDBOX,
  227. 'CHROME_USER_AGENT': CHROME_USER_AGENT,
  228. 'CHROME_USER_DATA_DIR': CHROME_USER_DATA_DIR,
  229. }
  230. # PYPPETEER_ARGS = {
  231. # 'headless': CHROME_HEADLESS,
  232. # 'ignoreHTTPSErrors': not CHECK_SSL_VALIDITY,
  233. # # 'executablePath': CHROME_BINARY,
  234. # }
  235. except KeyboardInterrupt:
  236. raise SystemExit(1)
  237. except:
  238. print('[X] There was an error while reading configuration. Your archive data is unaffected.')
  239. raise