config.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. __package__ = 'archivebox.legacy'
  2. import os
  3. import re
  4. import sys
  5. import django
  6. import getpass
  7. import shutil
  8. from typing import Optional
  9. from subprocess import run, PIPE, DEVNULL
  10. # ******************************************************************************
  11. # Documentation: https://github.com/pirate/ArchiveBox/wiki/Configuration
  12. # Use the 'env' command to pass config options to ArchiveBox. e.g.:
  13. # env USE_COLOR=True CHROME_BINARY=chromium archivebox add < example.html
  14. # ******************************************************************************
  15. IS_TTY = sys.stdout.isatty()
  16. USE_COLOR = os.getenv('USE_COLOR', str(IS_TTY) ).lower() == 'true'
  17. SHOW_PROGRESS = os.getenv('SHOW_PROGRESS', str(IS_TTY) ).lower() == 'true'
  18. OUTPUT_DIR = os.getenv('OUTPUT_DIR', '')
  19. ONLY_NEW = os.getenv('ONLY_NEW', 'False' ).lower() == 'true'
  20. TIMEOUT = int(os.getenv('TIMEOUT', '60'))
  21. MEDIA_TIMEOUT = int(os.getenv('MEDIA_TIMEOUT', '3600'))
  22. OUTPUT_PERMISSIONS = os.getenv('OUTPUT_PERMISSIONS', '755' )
  23. FOOTER_INFO = os.getenv('FOOTER_INFO', 'Content is hosted for personal archiving purposes only. Contact server owner for any takedown requests.',)
  24. URL_BLACKLIST = os.getenv('URL_BLACKLIST', None)
  25. FETCH_WGET = os.getenv('FETCH_WGET', 'True' ).lower() == 'true'
  26. FETCH_WGET_REQUISITES = os.getenv('FETCH_WGET_REQUISITES', 'True' ).lower() == 'true'
  27. FETCH_PDF = os.getenv('FETCH_PDF', 'True' ).lower() == 'true'
  28. FETCH_SCREENSHOT = os.getenv('FETCH_SCREENSHOT', 'True' ).lower() == 'true'
  29. FETCH_DOM = os.getenv('FETCH_DOM', 'True' ).lower() == 'true'
  30. FETCH_WARC = os.getenv('FETCH_WARC', 'True' ).lower() == 'true'
  31. FETCH_GIT = os.getenv('FETCH_GIT', 'True' ).lower() == 'true'
  32. FETCH_MEDIA = os.getenv('FETCH_MEDIA', 'True' ).lower() == 'true'
  33. FETCH_FAVICON = os.getenv('FETCH_FAVICON', 'True' ).lower() == 'true'
  34. FETCH_TITLE = os.getenv('FETCH_TITLE', 'True' ).lower() == 'true'
  35. SUBMIT_ARCHIVE_DOT_ORG = os.getenv('SUBMIT_ARCHIVE_DOT_ORG', 'True' ).lower() == 'true'
  36. CHECK_SSL_VALIDITY = os.getenv('CHECK_SSL_VALIDITY', 'True' ).lower() == 'true'
  37. RESOLUTION = os.getenv('RESOLUTION', '1440,2000' )
  38. GIT_DOMAINS = os.getenv('GIT_DOMAINS', 'github.com,bitbucket.org,gitlab.com').split(',')
  39. WGET_USER_AGENT = os.getenv('WGET_USER_AGENT', 'ArchiveBox/{VERSION} (+https://github.com/pirate/ArchiveBox/) wget/{WGET_VERSION}')
  40. COOKIES_FILE = os.getenv('COOKIES_FILE', None)
  41. CHROME_USER_DATA_DIR = os.getenv('CHROME_USER_DATA_DIR', None)
  42. CHROME_HEADLESS = os.getenv('CHROME_HEADLESS', 'True' ).lower() == 'true'
  43. 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')
  44. CHROME_SANDBOX = os.getenv('CHROME_SANDBOX', 'True' ).lower() == 'true'
  45. USE_CURL = os.getenv('USE_CURL', 'True' ).lower() == 'true'
  46. USE_WGET = os.getenv('USE_WGET', 'True' ).lower() == 'true'
  47. USE_CHROME = os.getenv('USE_CHROME', 'True' ).lower() == 'true'
  48. CURL_BINARY = os.getenv('CURL_BINARY', 'curl')
  49. GIT_BINARY = os.getenv('GIT_BINARY', 'git')
  50. WGET_BINARY = os.getenv('WGET_BINARY', 'wget')
  51. YOUTUBEDL_BINARY = os.getenv('YOUTUBEDL_BINARY', 'youtube-dl')
  52. CHROME_BINARY = os.getenv('CHROME_BINARY', None)
  53. # ******************************************************************************
  54. ### Terminal Configuration
  55. TERM_WIDTH = lambda: shutil.get_terminal_size((100, 10)).columns
  56. ANSI = {
  57. 'reset': '\033[00;00m',
  58. 'lightblue': '\033[01;30m',
  59. 'lightyellow': '\033[01;33m',
  60. 'lightred': '\033[01;35m',
  61. 'red': '\033[01;31m',
  62. 'green': '\033[01;32m',
  63. 'blue': '\033[01;34m',
  64. 'white': '\033[01;37m',
  65. 'black': '\033[01;30m',
  66. }
  67. if not USE_COLOR:
  68. # dont show colors if USE_COLOR is False
  69. ANSI = {k: '' for k in ANSI.keys()}
  70. def stderr(*args):
  71. sys.stderr.write(' '.join(str(a) for a in args) + '\n')
  72. USER = getpass.getuser() or os.getlogin()
  73. REPO_DIR = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..'))
  74. if OUTPUT_DIR:
  75. OUTPUT_DIR = os.path.abspath(os.path.expanduser(OUTPUT_DIR))
  76. else:
  77. OUTPUT_DIR = os.path.abspath(os.curdir)
  78. ARCHIVE_DIR_NAME = 'archive'
  79. SOURCES_DIR_NAME = 'sources'
  80. DATABASE_DIR_NAME = 'database'
  81. DATABASE_FILE_NAME = 'database.sqlite3'
  82. ARCHIVE_DIR = os.path.join(OUTPUT_DIR, ARCHIVE_DIR_NAME)
  83. SOURCES_DIR = os.path.join(OUTPUT_DIR, SOURCES_DIR_NAME)
  84. DATABASE_DIR = os.path.join(OUTPUT_DIR, DATABASE_DIR_NAME)
  85. DATABASE_FILE = os.path.join(OUTPUT_DIR, DATABASE_DIR_NAME, DATABASE_FILE_NAME)
  86. PYTHON_DIR = os.path.join(REPO_DIR, 'archivebox')
  87. LEGACY_DIR = os.path.join(PYTHON_DIR, 'legacy')
  88. TEMPLATES_DIR = os.path.join(LEGACY_DIR, 'templates')
  89. if COOKIES_FILE:
  90. COOKIES_FILE = os.path.abspath(os.path.expanduser(COOKIES_FILE))
  91. if CHROME_USER_DATA_DIR:
  92. CHROME_USER_DATA_DIR = os.path.abspath(os.path.expanduser(CHROME_USER_DATA_DIR))
  93. URL_BLACKLIST_PTN = re.compile(URL_BLACKLIST, re.IGNORECASE) if URL_BLACKLIST else None
  94. ########################### Environment & Dependencies #########################
  95. VERSION = open(os.path.join(REPO_DIR, 'VERSION'), 'r').read().strip()
  96. GIT_SHA = VERSION.split('+')[-1] or 'unknown'
  97. HAS_INVALID_DEPENDENCIES = False
  98. ### Check system environment
  99. if USER == 'root':
  100. stderr('{red}[!] ArchiveBox should never be run as root!{reset}'.format(**ANSI))
  101. stderr(' For more information, see the security overview documentation:')
  102. stderr(' https://github.com/pirate/ArchiveBox/wiki/Security-Overview#do-not-run-as-root')
  103. raise SystemExit(1)
  104. ### Check Python environment
  105. python_vers = float('{}.{}'.format(sys.version_info.major, sys.version_info.minor))
  106. if python_vers < 3.6:
  107. stderr('{}[X] Python version is not new enough: {} (>3.6 is required){}'.format(ANSI['red'], python_vers, ANSI['reset']))
  108. stderr(' See https://github.com/pirate/ArchiveBox/wiki/Troubleshooting#python for help upgrading your Python installation.')
  109. raise SystemExit(1)
  110. if sys.stdout.encoding.upper() not in ('UTF-8', 'UTF8'):
  111. stderr('[X] Your system is running python3 scripts with a bad locale setting: {} (it should be UTF-8).'.format(sys.stdout.encoding))
  112. stderr(' To fix it, add the line "export PYTHONIOENCODING=UTF-8" to your ~/.bashrc file (without quotes)')
  113. stderr(' Or if you\'re using ubuntu/debian, run "dpkg-reconfigure locales"')
  114. stderr('')
  115. stderr(' Confirm that it\'s fixed by opening a new shell and running:')
  116. stderr(' python3 -c "import sys; print(sys.stdout.encoding)" # should output UTF-8')
  117. stderr('')
  118. stderr(' Alternatively, run this script with:')
  119. stderr(' env PYTHONIOENCODING=UTF-8 ./archive.py export.html')
  120. raise SystemExit(1)
  121. # ******************************************************************************
  122. # ***************************** Helper Functions *******************************
  123. # ******************************************************************************
  124. def bin_version(binary: str) -> Optional[str]:
  125. """check the presence and return valid version line of a specified binary"""
  126. global HAS_INVALID_DEPENDENCIES
  127. binary = os.path.expanduser(binary)
  128. try:
  129. if not shutil.which(binary):
  130. raise Exception
  131. version_str = run([binary, "--version"], stdout=PIPE, cwd=REPO_DIR).stdout.strip().decode()
  132. # take first 3 columns of first line of version info
  133. return ' '.join(version_str.split('\n')[0].strip().split()[:3])
  134. except Exception:
  135. HAS_INVALID_DEPENDENCIES = True
  136. stderr('{red}[X] Unable to find working version of dependency: {}{reset}'.format(binary, **ANSI))
  137. stderr(' Make sure it\'s installed, then confirm it\'s working by running:')
  138. stderr(' {} --version'.format(binary))
  139. stderr()
  140. stderr(' If you don\'t want to install it, you can disable it via config. See here for more info:')
  141. stderr(' https://github.com/pirate/ArchiveBox/wiki/Install')
  142. stderr()
  143. return None
  144. def find_chrome_binary() -> Optional[str]:
  145. """find any installed chrome binaries in the default locations"""
  146. # Precedence: Chromium, Chrome, Beta, Canary, Unstable, Dev
  147. # make sure data dir finding precedence order always matches binary finding order
  148. default_executable_paths = (
  149. 'chromium-browser',
  150. 'chromium',
  151. '/Applications/Chromium.app/Contents/MacOS/Chromium',
  152. 'google-chrome',
  153. '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
  154. 'google-chrome-stable',
  155. 'google-chrome-beta',
  156. 'google-chrome-canary',
  157. '/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary',
  158. 'google-chrome-unstable',
  159. 'google-chrome-dev',
  160. )
  161. for name in default_executable_paths:
  162. full_path_exists = shutil.which(name)
  163. if full_path_exists:
  164. return name
  165. stderr('{red}[X] Unable to find a working version of Chrome/Chromium, is it installed and in your $PATH?'.format(**ANSI))
  166. stderr()
  167. return None
  168. def find_chrome_data_dir() -> Optional[str]:
  169. """find any installed chrome user data directories in the default locations"""
  170. # Precedence: Chromium, Chrome, Beta, Canary, Unstable, Dev
  171. # make sure data dir finding precedence order always matches binary finding order
  172. default_profile_paths = (
  173. '~/.config/chromium',
  174. '~/Library/Application Support/Chromium',
  175. '~/AppData/Local/Chromium/User Data',
  176. '~/.config/google-chrome',
  177. '~/Library/Application Support/Google/Chrome',
  178. '~/AppData/Local/Google/Chrome/User Data',
  179. '~/.config/google-chrome-stable',
  180. '~/.config/google-chrome-beta',
  181. '~/Library/Application Support/Google/Chrome Canary',
  182. '~/AppData/Local/Google/Chrome SxS/User Data',
  183. '~/.config/google-chrome-unstable',
  184. '~/.config/google-chrome-dev',
  185. )
  186. for path in default_profile_paths:
  187. full_path = os.path.expanduser(path)
  188. if os.path.exists(full_path):
  189. return full_path
  190. return None
  191. def setup_django():
  192. import django
  193. sys.path.append(PYTHON_DIR)
  194. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')
  195. django.setup()
  196. # ******************************************************************************
  197. # ************************ Environment & Dependencies **************************
  198. # ******************************************************************************
  199. try:
  200. ### Get Django version
  201. DJANGO_BINARY = django.__file__.replace('__init__.py', 'bin/django-admin.py')
  202. DJANGO_VERSION = '{}.{}.{} {} ({})'.format(*django.VERSION)
  203. ### Make sure curl is installed
  204. if USE_CURL:
  205. USE_CURL = FETCH_FAVICON or SUBMIT_ARCHIVE_DOT_ORG
  206. else:
  207. FETCH_FAVICON = SUBMIT_ARCHIVE_DOT_ORG = False
  208. CURL_VERSION = None
  209. if USE_CURL:
  210. CURL_VERSION = bin_version(CURL_BINARY)
  211. ### Make sure wget is installed and calculate version
  212. if USE_WGET:
  213. USE_WGET = FETCH_WGET or FETCH_WARC
  214. else:
  215. FETCH_WGET = FETCH_WARC = False
  216. WGET_VERSION = None
  217. WGET_AUTO_COMPRESSION = False
  218. if USE_WGET:
  219. WGET_VERSION = bin_version(WGET_BINARY)
  220. WGET_AUTO_COMPRESSION = not run([WGET_BINARY, "--compression=auto", "--help"], stdout=DEVNULL, stderr=DEVNULL).returncode
  221. WGET_USER_AGENT = WGET_USER_AGENT.format(
  222. VERSION=VERSION,
  223. WGET_VERSION=WGET_VERSION or '',
  224. )
  225. ### Make sure git is installed
  226. GIT_VERSION = None
  227. if FETCH_GIT:
  228. GIT_VERSION = bin_version(GIT_BINARY)
  229. ### Make sure youtube-dl is installed
  230. YOUTUBEDL_VERSION = None
  231. if FETCH_MEDIA:
  232. YOUTUBEDL_VERSION = bin_version(YOUTUBEDL_BINARY)
  233. ### Make sure chrome is installed and calculate version
  234. if USE_CHROME:
  235. USE_CHROME = FETCH_PDF or FETCH_SCREENSHOT or FETCH_DOM
  236. else:
  237. FETCH_PDF = FETCH_SCREENSHOT = FETCH_DOM = False
  238. if not CHROME_BINARY:
  239. CHROME_BINARY = find_chrome_binary() or 'chromium-browser'
  240. CHROME_VERSION = None
  241. if USE_CHROME:
  242. if CHROME_BINARY:
  243. CHROME_VERSION = bin_version(CHROME_BINARY)
  244. # stderr('[i] Using Chrome binary: {}'.format(shutil.which(CHROME_BINARY) or CHROME_BINARY))
  245. if CHROME_USER_DATA_DIR is None:
  246. CHROME_USER_DATA_DIR = find_chrome_data_dir()
  247. elif CHROME_USER_DATA_DIR == '':
  248. CHROME_USER_DATA_DIR = None
  249. else:
  250. if not os.path.exists(os.path.join(CHROME_USER_DATA_DIR, 'Default')):
  251. stderr('{red}[X] Could not find profile "Default" in CHROME_USER_DATA_DIR:{reset} {}'.format(CHROME_USER_DATA_DIR, **ANSI))
  252. stderr(' Make sure you set it to a Chrome user data directory containing a Default profile folder.')
  253. stderr(' For more info see:')
  254. stderr(' https://github.com/pirate/ArchiveBox/wiki/Configuration#CHROME_USER_DATA_DIR')
  255. if 'Default' in CHROME_USER_DATA_DIR:
  256. stderr()
  257. stderr(' Try removing /Default from the end e.g.:')
  258. stderr(' CHROME_USER_DATA_DIR="{}"'.format(CHROME_USER_DATA_DIR.split('/Default')[0]))
  259. raise SystemExit(1)
  260. # stderr('[i] Using Chrome data dir: {}'.format(os.path.abspath(CHROME_USER_DATA_DIR)))
  261. ### Summary Lookup Dicts
  262. FOLDERS = {
  263. 'REPO_DIR': {
  264. 'path': os.path.abspath(REPO_DIR),
  265. 'enabled': True,
  266. 'is_valid': os.path.exists(os.path.join(REPO_DIR, '.github')),
  267. },
  268. 'PYTHON_DIR': {
  269. 'path': os.path.abspath(PYTHON_DIR),
  270. 'enabled': True,
  271. 'is_valid': os.path.exists(os.path.join(PYTHON_DIR, '__main__.py')),
  272. },
  273. 'LEGACY_DIR': {
  274. 'path': os.path.abspath(LEGACY_DIR),
  275. 'enabled': True,
  276. 'is_valid': os.path.exists(os.path.join(LEGACY_DIR, 'util.py')),
  277. },
  278. 'TEMPLATES_DIR': {
  279. 'path': os.path.abspath(TEMPLATES_DIR),
  280. 'enabled': True,
  281. 'is_valid': os.path.exists(os.path.join(TEMPLATES_DIR, 'static')),
  282. },
  283. 'OUTPUT_DIR': {
  284. 'path': os.path.abspath(OUTPUT_DIR),
  285. 'enabled': True,
  286. 'is_valid': os.path.exists(os.path.join(OUTPUT_DIR, 'index.json')),
  287. },
  288. 'SOURCES_DIR': {
  289. 'path': os.path.abspath(SOURCES_DIR),
  290. 'enabled': True,
  291. 'is_valid': os.path.exists(SOURCES_DIR),
  292. },
  293. 'ARCHIVE_DIR': {
  294. 'path': os.path.abspath(ARCHIVE_DIR),
  295. 'enabled': True,
  296. 'is_valid': os.path.exists(ARCHIVE_DIR),
  297. },
  298. 'DATABASE_DIR': {
  299. 'path': os.path.abspath(DATABASE_DIR),
  300. 'enabled': True,
  301. 'is_valid': os.path.exists(DATABASE_FILE),
  302. },
  303. 'CHROME_USER_DATA_DIR': {
  304. 'path': CHROME_USER_DATA_DIR and os.path.abspath(CHROME_USER_DATA_DIR),
  305. 'enabled': USE_CHROME and CHROME_USER_DATA_DIR,
  306. 'is_valid': os.path.exists(os.path.join(CHROME_USER_DATA_DIR, 'Default')) if CHROME_USER_DATA_DIR else False,
  307. },
  308. 'COOKIES_FILE': {
  309. 'path': COOKIES_FILE and os.path.abspath(COOKIES_FILE),
  310. 'enabled': USE_WGET and COOKIES_FILE,
  311. 'is_valid': COOKIES_FILE and os.path.exists(COOKIES_FILE),
  312. },
  313. }
  314. DEPENDENCIES = {
  315. 'DJANGO_BINARY': {
  316. 'path': DJANGO_BINARY,
  317. 'version': DJANGO_VERSION,
  318. 'enabled': True,
  319. 'is_valid': bool(DJANGO_VERSION),
  320. },
  321. 'CURL_BINARY': {
  322. 'path': CURL_BINARY and shutil.which(CURL_BINARY),
  323. 'version': CURL_VERSION,
  324. 'enabled': USE_CURL,
  325. 'is_valid': bool(CURL_VERSION),
  326. },
  327. 'WGET_BINARY': {
  328. 'path': WGET_BINARY and shutil.which(WGET_BINARY),
  329. 'version': WGET_VERSION,
  330. 'enabled': USE_WGET,
  331. 'is_valid': bool(WGET_VERSION),
  332. },
  333. 'GIT_BINARY': {
  334. 'path': GIT_BINARY and shutil.which(GIT_BINARY),
  335. 'version': GIT_VERSION,
  336. 'enabled': FETCH_GIT,
  337. 'is_valid': bool(GIT_VERSION),
  338. },
  339. 'YOUTUBEDL_BINARY': {
  340. 'path': YOUTUBEDL_BINARY and shutil.which(YOUTUBEDL_BINARY),
  341. 'version': YOUTUBEDL_VERSION,
  342. 'enabled': FETCH_MEDIA,
  343. 'is_valid': bool(YOUTUBEDL_VERSION),
  344. },
  345. 'CHROME_BINARY': {
  346. 'path': CHROME_BINARY and shutil.which(CHROME_BINARY),
  347. 'version': CHROME_VERSION,
  348. 'enabled': USE_CHROME,
  349. 'is_valid': bool(CHROME_VERSION),
  350. },
  351. }
  352. CHROME_OPTIONS = {
  353. 'TIMEOUT': TIMEOUT,
  354. 'RESOLUTION': RESOLUTION,
  355. 'CHECK_SSL_VALIDITY': CHECK_SSL_VALIDITY,
  356. 'CHROME_BINARY': CHROME_BINARY,
  357. 'CHROME_HEADLESS': CHROME_HEADLESS,
  358. 'CHROME_SANDBOX': CHROME_SANDBOX,
  359. 'CHROME_USER_AGENT': CHROME_USER_AGENT,
  360. 'CHROME_USER_DATA_DIR': CHROME_USER_DATA_DIR,
  361. }
  362. # PYPPETEER_ARGS = {
  363. # 'headless': CHROME_HEADLESS,
  364. # 'ignoreHTTPSErrors': not CHECK_SSL_VALIDITY,
  365. # # 'executablePath': CHROME_BINARY,
  366. # }
  367. except KeyboardInterrupt:
  368. raise SystemExit(1)
  369. except Exception as e:
  370. stderr()
  371. stderr('{red}[X] Error during configuration: {} {}{reset}'.format(e.__class__.__name__, e, **ANSI))
  372. stderr(' Your archive data is unaffected.')
  373. stderr(' Check your config or environemnt variables for mistakes and try again.')
  374. stderr(' For more info see:')
  375. stderr(' https://github.com/pirate/ArchiveBox/wiki/Configuration')
  376. stderr()
  377. raise
  378. def check_dependencies() -> None:
  379. if HAS_INVALID_DEPENDENCIES:
  380. stderr('{red}[X] Missing some required dependencies.{reset}'.format(**ANSI))
  381. raise SystemExit(1)
  382. def check_data_folder() -> None:
  383. if not os.path.exists(os.path.join(OUTPUT_DIR, 'index.json')):
  384. stderr('{red}[X] No archive data was found in:{reset} {}'.format(OUTPUT_DIR, **ANSI))
  385. stderr(' Are you running archivebox in the right folder?')
  386. stderr(' cd path/to/your/archive/folder')
  387. stderr(' archivebox [command]')
  388. stderr()
  389. stderr(' To create a new archive collection in this folder, run:')
  390. stderr(' archivebox init')
  391. raise SystemExit(1)