config.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. import os
  2. import re
  3. import sys
  4. import shutil
  5. from subprocess import run, PIPE, DEVNULL
  6. # ******************************************************************************
  7. # Documentation: https://github.com/pirate/ArchiveBox/wiki/Configuration
  8. # Use the 'env' command to pass config options to ArchiveBox. e.g.:
  9. # env USE_COLOR=True CHROME_BINARY=google-chrome ./archive export.html
  10. # ******************************************************************************
  11. IS_TTY = sys.stdout.isatty()
  12. USE_COLOR = os.getenv('USE_COLOR', str(IS_TTY) ).lower() == 'true'
  13. SHOW_PROGRESS = os.getenv('SHOW_PROGRESS', str(IS_TTY) ).lower() == 'true'
  14. ONLY_NEW = os.getenv('ONLY_NEW', 'False' ).lower() == 'true'
  15. MEDIA_TIMEOUT = int(os.getenv('MEDIA_TIMEOUT', '3600'))
  16. TIMEOUT = int(os.getenv('TIMEOUT', '60'))
  17. OUTPUT_PERMISSIONS = os.getenv('OUTPUT_PERMISSIONS', '755' )
  18. FOOTER_INFO = os.getenv('FOOTER_INFO', 'Content is hosted for personal archiving purposes only. Contact server owner for any takedown requests.',)
  19. FETCH_WGET = os.getenv('FETCH_WGET', 'True' ).lower() == 'true'
  20. FETCH_WGET_REQUISITES = os.getenv('FETCH_WGET_REQUISITES', 'True' ).lower() == 'true'
  21. FETCH_PDF = os.getenv('FETCH_PDF', 'True' ).lower() == 'true'
  22. FETCH_SCREENSHOT = os.getenv('FETCH_SCREENSHOT', 'True' ).lower() == 'true'
  23. FETCH_DOM = os.getenv('FETCH_DOM', 'True' ).lower() == 'true'
  24. FETCH_WARC = os.getenv('FETCH_WARC', 'True' ).lower() == 'true'
  25. FETCH_GIT = os.getenv('FETCH_GIT', 'True' ).lower() == 'true'
  26. FETCH_MEDIA = os.getenv('FETCH_MEDIA', 'True' ).lower() == 'true'
  27. FETCH_FAVICON = os.getenv('FETCH_FAVICON', 'True' ).lower() == 'true'
  28. FETCH_TITLE = os.getenv('FETCH_TITLE', 'True' ).lower() == 'true'
  29. SUBMIT_ARCHIVE_DOT_ORG = os.getenv('SUBMIT_ARCHIVE_DOT_ORG', 'True' ).lower() == 'true'
  30. CHECK_SSL_VALIDITY = os.getenv('CHECK_SSL_VALIDITY', 'True' ).lower() == 'true'
  31. RESOLUTION = os.getenv('RESOLUTION', '1440,2000' )
  32. GIT_DOMAINS = os.getenv('GIT_DOMAINS', 'github.com,bitbucket.org,gitlab.com').split(',')
  33. WGET_USER_AGENT = os.getenv('WGET_USER_AGENT', 'ArchiveBox/{GIT_SHA} (+https://github.com/pirate/ArchiveBox/) wget/{WGET_VERSION}')
  34. COOKIES_FILE = os.getenv('COOKIES_FILE', None)
  35. CHROME_USER_DATA_DIR = os.getenv('CHROME_USER_DATA_DIR', None)
  36. CHROME_HEADLESS = os.getenv('CHROME_HEADLESS', 'True' ).lower() == 'true'
  37. 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')
  38. CURL_BINARY = os.getenv('CURL_BINARY', 'curl')
  39. GIT_BINARY = os.getenv('GIT_BINARY', 'git')
  40. WGET_BINARY = os.getenv('WGET_BINARY', 'wget')
  41. YOUTUBEDL_BINARY = os.getenv('YOUTUBEDL_BINARY', 'youtube-dl')
  42. CHROME_BINARY = os.getenv('CHROME_BINARY', None)
  43. try:
  44. OUTPUT_DIR = os.path.abspath(os.getenv('OUTPUT_DIR'))
  45. except Exception:
  46. OUTPUT_DIR = None
  47. # ******************************************************************************
  48. # **************************** Derived Settings ********************************
  49. # ******************************************************************************
  50. REPO_DIR = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))
  51. if not OUTPUT_DIR:
  52. OUTPUT_DIR = os.path.join(REPO_DIR, 'output')
  53. ARCHIVE_DIR_NAME = 'archive'
  54. SOURCES_DIR_NAME = 'sources'
  55. ARCHIVE_DIR = os.path.join(OUTPUT_DIR, ARCHIVE_DIR_NAME)
  56. SOURCES_DIR = os.path.join(OUTPUT_DIR, SOURCES_DIR_NAME)
  57. PYTHON_PATH = os.path.join(REPO_DIR, 'archivebox')
  58. TEMPLATES_DIR = os.path.join(PYTHON_PATH, 'templates')
  59. CHROME_SANDBOX = os.getenv('CHROME_SANDBOX', 'True').lower() == 'true'
  60. USE_CHROME = FETCH_PDF or FETCH_SCREENSHOT or FETCH_DOM
  61. USE_WGET = FETCH_WGET or FETCH_WGET_REQUISITES or FETCH_WARC
  62. ########################### Environment & Dependencies #########################
  63. try:
  64. ### Terminal Configuration
  65. TERM_WIDTH = lambda: shutil.get_terminal_size((100, 10)).columns
  66. ANSI = {
  67. 'reset': '\033[00;00m',
  68. 'lightblue': '\033[01;30m',
  69. 'lightyellow': '\033[01;33m',
  70. 'lightred': '\033[01;35m',
  71. 'red': '\033[01;31m',
  72. 'green': '\033[01;32m',
  73. 'blue': '\033[01;34m',
  74. 'white': '\033[01;37m',
  75. 'black': '\033[01;30m',
  76. }
  77. if not USE_COLOR:
  78. # dont show colors if USE_COLOR is False
  79. ANSI = {k: '' for k in ANSI.keys()}
  80. if not CHROME_BINARY:
  81. # Precedence: Chromium, Chrome, Beta, Canary, Unstable, Dev
  82. default_executable_paths = (
  83. 'chromium-browser',
  84. 'chromium',
  85. '/Applications/Chromium.app/Contents/MacOS/Chromium',
  86. 'google-chrome',
  87. '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
  88. 'google-chrome-stable',
  89. 'google-chrome-beta',
  90. 'google-chrome-canary',
  91. '/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary',
  92. 'google-chrome-unstable',
  93. 'google-chrome-dev',
  94. )
  95. for name in default_executable_paths:
  96. full_path_exists = shutil.which(name)
  97. if full_path_exists:
  98. CHROME_BINARY = name
  99. break
  100. else:
  101. CHROME_BINARY = 'chromium-browser'
  102. # print('[i] Using Chrome binary: {}'.format(shutil.which(CHROME_BINARY) or CHROME_BINARY))
  103. if CHROME_USER_DATA_DIR is None:
  104. # Precedence: Chromium, Chrome, Beta, Canary, Unstable, Dev
  105. default_profile_paths = (
  106. '~/.config/chromium',
  107. '~/Library/Application Support/Chromium',
  108. '~/AppData/Local/Chromium/User Data',
  109. '~/.config/google-chrome',
  110. '~/Library/Application Support/Google/Chrome',
  111. '~/AppData/Local/Google/Chrome/User Data',
  112. '~/.config/google-chrome-stable',
  113. '~/.config/google-chrome-beta',
  114. '~/Library/Application Support/Google/Chrome Canary',
  115. '~/AppData/Local/Google/Chrome SxS/User Data',
  116. '~/.config/google-chrome-unstable',
  117. '~/.config/google-chrome-dev',
  118. )
  119. for path in default_profile_paths:
  120. full_path = os.path.expanduser(path)
  121. if os.path.exists(full_path):
  122. CHROME_USER_DATA_DIR = full_path
  123. break
  124. # print('[i] Using Chrome data dir: {}'.format(os.path.abspath(CHROME_USER_DATA_DIR)))
  125. CHROME_OPTIONS = {
  126. 'TIMEOUT': TIMEOUT,
  127. 'RESOLUTION': RESOLUTION,
  128. 'CHECK_SSL_VALIDITY': CHECK_SSL_VALIDITY,
  129. 'CHROME_BINARY': CHROME_BINARY,
  130. 'CHROME_HEADLESS': CHROME_HEADLESS,
  131. 'CHROME_SANDBOX': CHROME_SANDBOX,
  132. 'CHROME_USER_AGENT': CHROME_USER_AGENT,
  133. 'CHROME_USER_DATA_DIR': CHROME_USER_DATA_DIR,
  134. }
  135. ### Check Python environment
  136. python_vers = float('{}.{}'.format(sys.version_info.major, sys.version_info.minor))
  137. if python_vers < 3.5:
  138. print('{}[X] Python version is not new enough: {} (>3.5 is required){}'.format(ANSI['red'], python_vers, ANSI['reset']))
  139. print(' See https://github.com/pirate/ArchiveBox/wiki/Troubleshooting#python for help upgrading your Python installation.')
  140. raise SystemExit(1)
  141. if sys.stdout.encoding.upper() not in ('UTF-8', 'UTF8'):
  142. print('[X] Your system is running python3 scripts with a bad locale setting: {} (it should be UTF-8).'.format(sys.stdout.encoding))
  143. print(' To fix it, add the line "export PYTHONIOENCODING=UTF-8" to your ~/.bashrc file (without quotes)')
  144. print('')
  145. print(' Confirm that it\'s fixed by opening a new shell and running:')
  146. print(' python3 -c "import sys; print(sys.stdout.encoding)" # should output UTF-8')
  147. print('')
  148. print(' Alternatively, run this script with:')
  149. print(' env PYTHONIOENCODING=UTF-8 ./archive.py export.html')
  150. ### Get code version by parsing git log
  151. GIT_SHA = 'unknown'
  152. try:
  153. GIT_SHA = run([GIT_BINARY, 'rev-list', '-1', 'HEAD', './'], stdout=PIPE, cwd=REPO_DIR).stdout.strip().decode()
  154. except Exception:
  155. print('[!] Warning: unable to determine git version, is git installed and in your $PATH?')
  156. ### Get absolute path for cookies file
  157. try:
  158. COOKIES_FILE = os.path.abspath(COOKIES_FILE) if COOKIES_FILE else None
  159. except Exception:
  160. print('[!] Warning: unable to get full path to COOKIES_FILE, are you sure you specified it correctly?')
  161. raise
  162. ### Make sure curl is installed
  163. if FETCH_FAVICON or SUBMIT_ARCHIVE_DOT_ORG:
  164. if run(['which', CURL_BINARY], stdout=DEVNULL, stderr=DEVNULL).returncode or run([CURL_BINARY, '--version'], stdout=DEVNULL, stderr=DEVNULL).returncode:
  165. print('{red}[X] Missing dependency: curl{reset}'.format(**ANSI))
  166. print(' Install it, then confirm it works with: {} --version'.format(CURL_BINARY))
  167. print(' See https://github.com/pirate/ArchiveBox/wiki/Install for help.')
  168. raise SystemExit(1)
  169. ### Make sure wget is installed and calculate version
  170. if FETCH_WGET or FETCH_WARC:
  171. if run(['which', WGET_BINARY], stdout=DEVNULL, stderr=DEVNULL).returncode or run([WGET_BINARY, '--version'], stdout=DEVNULL, stderr=DEVNULL).returncode:
  172. print('{red}[X] Missing dependency: wget{reset}'.format(**ANSI))
  173. print(' Install it, then confirm it works with: {} --version'.format(WGET_BINARY))
  174. print(' See https://github.com/pirate/ArchiveBox/wiki/Install for help.')
  175. raise SystemExit(1)
  176. WGET_VERSION = 'unknown'
  177. try:
  178. wget_vers_str = run([WGET_BINARY, "--version"], stdout=PIPE, cwd=REPO_DIR).stdout.strip().decode()
  179. WGET_VERSION = wget_vers_str.split('\n')[0].split(' ')[2]
  180. except Exception:
  181. if USE_WGET:
  182. print('[!] Warning: unable to determine wget version, is wget installed and in your $PATH?')
  183. WGET_USER_AGENT = WGET_USER_AGENT.format(GIT_SHA=GIT_SHA[:9], WGET_VERSION=WGET_VERSION)
  184. ### Make sure chrome is installed and calculate version
  185. if FETCH_PDF or FETCH_SCREENSHOT or FETCH_DOM:
  186. if run(['which', CHROME_BINARY], stdout=DEVNULL, stderr=DEVNULL).returncode:
  187. print('{}[X] Missing dependency: {}{}'.format(ANSI['red'], CHROME_BINARY, ANSI['reset']))
  188. print(' Install it, then confirm it works with: {} --version'.format(CHROME_BINARY))
  189. print(' See https://github.com/pirate/ArchiveBox/wiki/Install for help.')
  190. raise SystemExit(1)
  191. # parse chrome --version e.g. Google Chrome 61.0.3114.0 canary / Chromium 59.0.3029.110 built on Ubuntu, running on Ubuntu 16.04
  192. try:
  193. result = run([CHROME_BINARY, '--version'], stdout=PIPE)
  194. version_str = result.stdout.decode('utf-8')
  195. version_lines = re.sub("(Google Chrome|Chromium) (\\d+?)\\.(\\d+?)\\.(\\d+?).*?$", "\\2", version_str).split('\n')
  196. version = [l for l in version_lines if l.isdigit()][-1]
  197. if int(version) < 59:
  198. print(version_lines)
  199. print('{red}[X] Chrome version must be 59 or greater for headless PDF, screenshot, and DOM saving{reset}'.format(**ANSI))
  200. print(' See https://github.com/pirate/ArchiveBox/wiki/Install for help.')
  201. raise SystemExit(1)
  202. except (IndexError, TypeError, OSError):
  203. print('{red}[X] Failed to parse Chrome version, is it installed properly?{reset}'.format(**ANSI))
  204. print(' Install it, then confirm it works with: {} --version'.format(CHROME_BINARY))
  205. print(' See https://github.com/pirate/ArchiveBox/wiki/Install for help.')
  206. raise SystemExit(1)
  207. CHROME_VERSION = 'unknown'
  208. try:
  209. chrome_vers_str = run([CHROME_BINARY, "--version"], stdout=PIPE, cwd=REPO_DIR).stdout.strip().decode()
  210. CHROME_VERSION = [v for v in chrome_vers_str.strip().split(' ') if v.replace('.', '').isdigit()][0]
  211. except Exception:
  212. if USE_CHROME:
  213. print('[!] Warning: unable to determine chrome version, is chrome installed and in your $PATH?')
  214. ### Make sure git is installed
  215. if FETCH_GIT:
  216. if run(['which', GIT_BINARY], stdout=DEVNULL, stderr=DEVNULL).returncode or run([GIT_BINARY, '--version'], stdout=DEVNULL, stderr=DEVNULL).returncode:
  217. print('{red}[X] Missing dependency: git{reset}'.format(**ANSI))
  218. print(' Install it, then confirm it works with: {} --version'.format(GIT_BINARY))
  219. print(' See https://github.com/pirate/ArchiveBox/wiki/Install for help.')
  220. raise SystemExit(1)
  221. ### Make sure youtube-dl is installed
  222. if FETCH_MEDIA:
  223. if run(['which', YOUTUBEDL_BINARY], stdout=DEVNULL, stderr=DEVNULL).returncode or run([YOUTUBEDL_BINARY, '--version'], stdout=DEVNULL, stderr=DEVNULL).returncode:
  224. print('{red}[X] Missing dependency: youtube-dl{reset}'.format(**ANSI))
  225. print(' Install it, then confirm it was installed with: {} --version'.format(YOUTUBEDL_BINARY))
  226. print(' See https://github.com/pirate/ArchiveBox/wiki/Install for help.')
  227. raise SystemExit(1)
  228. except KeyboardInterrupt:
  229. raise SystemExit(1)
  230. except:
  231. print('[X] There was an error during the startup procedure, your archive data is unaffected.')
  232. raise