config.py 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138
  1. """
  2. ArchiveBox config definitons (including defaults and dynamic config options).
  3. Config Usage Example:
  4. archivebox config --set MEDIA_TIMEOUT=600
  5. env MEDIA_TIMEOUT=600 USE_COLOR=False ... archivebox [subcommand] ...
  6. Config Precedence Order:
  7. 1. cli args (--update-all / --index-only / etc.)
  8. 2. shell environment vars (env USE_COLOR=False archivebox add '...')
  9. 3. config file (echo "SAVE_FAVICON=False" >> ArchiveBox.conf)
  10. 4. defaults (defined below in Python)
  11. Documentation:
  12. https://github.com/ArchiveBox/ArchiveBox/wiki/Configuration
  13. """
  14. __package__ = 'archivebox'
  15. import os
  16. import io
  17. import re
  18. import sys
  19. import json
  20. import getpass
  21. import platform
  22. import shutil
  23. import sqlite3
  24. import django
  25. from hashlib import md5
  26. from pathlib import Path
  27. from datetime import datetime
  28. from typing import Optional, Type, Tuple, Dict, Union, List
  29. from subprocess import run, PIPE, DEVNULL
  30. from configparser import ConfigParser
  31. from collections import defaultdict
  32. from .config_stubs import (
  33. SimpleConfigValueDict,
  34. ConfigValue,
  35. ConfigDict,
  36. ConfigDefaultValue,
  37. ConfigDefaultDict,
  38. )
  39. ############################### Config Schema ##################################
  40. CONFIG_SCHEMA: Dict[str, ConfigDefaultDict] = {
  41. 'SHELL_CONFIG': {
  42. 'IS_TTY': {'type': bool, 'default': lambda _: sys.stdout.isatty()},
  43. 'USE_COLOR': {'type': bool, 'default': lambda c: c['IS_TTY']},
  44. 'SHOW_PROGRESS': {'type': bool, 'default': lambda c: (c['IS_TTY'] and platform.system() != 'Darwin')}, # progress bars are buggy on mac, disable for now
  45. 'IN_DOCKER': {'type': bool, 'default': False},
  46. # TODO: 'SHOW_HINTS': {'type: bool, 'default': True},
  47. },
  48. 'GENERAL_CONFIG': {
  49. 'OUTPUT_DIR': {'type': str, 'default': None},
  50. 'CONFIG_FILE': {'type': str, 'default': None},
  51. 'ONLY_NEW': {'type': bool, 'default': True},
  52. 'TIMEOUT': {'type': int, 'default': 60},
  53. 'MEDIA_TIMEOUT': {'type': int, 'default': 3600},
  54. 'OUTPUT_PERMISSIONS': {'type': str, 'default': '755'},
  55. 'RESTRICT_FILE_NAMES': {'type': str, 'default': 'windows'},
  56. 'URL_BLACKLIST': {'type': str, 'default': r'\.(css|js|otf|ttf|woff|woff2|gstatic\.com|googleapis\.com/css)(\?.*)?$'}, # to avoid downloading code assets as their own pages
  57. },
  58. 'SERVER_CONFIG': {
  59. 'SECRET_KEY': {'type': str, 'default': None},
  60. 'BIND_ADDR': {'type': str, 'default': lambda c: ['127.0.0.1:8000', '0.0.0.0:8000'][c['IN_DOCKER']]},
  61. 'ALLOWED_HOSTS': {'type': str, 'default': '*'},
  62. 'DEBUG': {'type': bool, 'default': False},
  63. 'PUBLIC_INDEX': {'type': bool, 'default': True},
  64. 'PUBLIC_SNAPSHOTS': {'type': bool, 'default': True},
  65. 'PUBLIC_ADD_VIEW': {'type': bool, 'default': False},
  66. 'FOOTER_INFO': {'type': str, 'default': 'Content is hosted for personal archiving purposes only. Contact server owner for any takedown requests.'},
  67. 'SNAPSHOTS_PER_PAGE': {'type': int, 'default': 40},
  68. 'CUSTOM_TEMPLATES_DIR': {'type': str, 'default': None}
  69. },
  70. 'ARCHIVE_METHOD_TOGGLES': {
  71. 'SAVE_TITLE': {'type': bool, 'default': True, 'aliases': ('FETCH_TITLE',)},
  72. 'SAVE_FAVICON': {'type': bool, 'default': True, 'aliases': ('FETCH_FAVICON',)},
  73. 'SAVE_WGET': {'type': bool, 'default': True, 'aliases': ('FETCH_WGET',)},
  74. 'SAVE_WGET_REQUISITES': {'type': bool, 'default': True, 'aliases': ('FETCH_WGET_REQUISITES',)},
  75. 'SAVE_SINGLEFILE': {'type': bool, 'default': True, 'aliases': ('FETCH_SINGLEFILE',)},
  76. 'SAVE_READABILITY': {'type': bool, 'default': True, 'aliases': ('FETCH_READABILITY',)},
  77. 'SAVE_MERCURY': {'type': bool, 'default': True, 'aliases': ('FETCH_MERCURY',)},
  78. 'SAVE_PDF': {'type': bool, 'default': True, 'aliases': ('FETCH_PDF',)},
  79. 'SAVE_SCREENSHOT': {'type': bool, 'default': True, 'aliases': ('FETCH_SCREENSHOT',)},
  80. 'SAVE_DOM': {'type': bool, 'default': True, 'aliases': ('FETCH_DOM',)},
  81. 'SAVE_HEADERS': {'type': bool, 'default': True, 'aliases': ('FETCH_HEADERS',)},
  82. 'SAVE_WARC': {'type': bool, 'default': True, 'aliases': ('FETCH_WARC',)},
  83. 'SAVE_GIT': {'type': bool, 'default': True, 'aliases': ('FETCH_GIT',)},
  84. 'SAVE_MEDIA': {'type': bool, 'default': True, 'aliases': ('FETCH_MEDIA',)},
  85. 'SAVE_ARCHIVE_DOT_ORG': {'type': bool, 'default': True, 'aliases': ('SUBMIT_ARCHIVE_DOT_ORG',)},
  86. },
  87. 'ARCHIVE_METHOD_OPTIONS': {
  88. 'RESOLUTION': {'type': str, 'default': '1440,2000', 'aliases': ('SCREENSHOT_RESOLUTION',)},
  89. 'GIT_DOMAINS': {'type': str, 'default': 'github.com,bitbucket.org,gitlab.com,gist.github.com'},
  90. 'CHECK_SSL_VALIDITY': {'type': bool, 'default': True},
  91. 'MEDIA_MAX_SIZE': {'type': str, 'default': '750m'},
  92. 'CURL_USER_AGENT': {'type': str, 'default': 'ArchiveBox/{VERSION} (+https://github.com/ArchiveBox/ArchiveBox/) curl/{CURL_VERSION}'},
  93. 'WGET_USER_AGENT': {'type': str, 'default': 'ArchiveBox/{VERSION} (+https://github.com/ArchiveBox/ArchiveBox/) wget/{WGET_VERSION}'},
  94. 'CHROME_USER_AGENT': {'type': str, 'default': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36'},
  95. 'COOKIES_FILE': {'type': str, 'default': None},
  96. 'CHROME_USER_DATA_DIR': {'type': str, 'default': None},
  97. 'CHROME_HEADLESS': {'type': bool, 'default': True},
  98. 'CHROME_SANDBOX': {'type': bool, 'default': lambda c: not c['IN_DOCKER']},
  99. 'YOUTUBEDL_ARGS': {'type': list, 'default': lambda c: ['--write-description',
  100. '--write-info-json',
  101. '--write-annotations',
  102. '--write-thumbnail',
  103. '--no-call-home',
  104. '--all-subs',
  105. '--yes-playlist',
  106. '--continue',
  107. '--ignore-errors',
  108. '--geo-bypass',
  109. '--add-metadata',
  110. '--max-filesize={}'.format(c['MEDIA_MAX_SIZE']),
  111. ]},
  112. 'WGET_ARGS': {'type': list, 'default': ['--no-verbose',
  113. '--adjust-extension',
  114. '--convert-links',
  115. '--force-directories',
  116. '--backup-converted',
  117. '--span-hosts',
  118. '--no-parent',
  119. '-e', 'robots=off',
  120. ]},
  121. 'CURL_ARGS': {'type': list, 'default': ['--silent',
  122. '--location',
  123. '--compressed'
  124. ]},
  125. 'GIT_ARGS': {'type': list, 'default': ['--recursive']},
  126. },
  127. 'SEARCH_BACKEND_CONFIG' : {
  128. 'USE_INDEXING_BACKEND': {'type': bool, 'default': True},
  129. 'USE_SEARCHING_BACKEND': {'type': bool, 'default': True},
  130. 'SEARCH_BACKEND_ENGINE': {'type': str, 'default': 'ripgrep'},
  131. 'SEARCH_BACKEND_HOST_NAME': {'type': str, 'default': 'localhost'},
  132. 'SEARCH_BACKEND_PORT': {'type': int, 'default': 1491},
  133. 'SEARCH_BACKEND_PASSWORD': {'type': str, 'default': 'SecretPassword'},
  134. # SONIC
  135. 'SONIC_COLLECTION': {'type': str, 'default': 'archivebox'},
  136. 'SONIC_BUCKET': {'type': str, 'default': 'snapshots'},
  137. },
  138. 'DEPENDENCY_CONFIG': {
  139. 'USE_CURL': {'type': bool, 'default': True},
  140. 'USE_WGET': {'type': bool, 'default': True},
  141. 'USE_SINGLEFILE': {'type': bool, 'default': True},
  142. 'USE_READABILITY': {'type': bool, 'default': True},
  143. 'USE_MERCURY': {'type': bool, 'default': True},
  144. 'USE_GIT': {'type': bool, 'default': True},
  145. 'USE_CHROME': {'type': bool, 'default': True},
  146. 'USE_NODE': {'type': bool, 'default': True},
  147. 'USE_YOUTUBEDL': {'type': bool, 'default': True},
  148. 'USE_RIPGREP': {'type': bool, 'default': True},
  149. 'CURL_BINARY': {'type': str, 'default': 'curl'},
  150. 'GIT_BINARY': {'type': str, 'default': 'git'},
  151. 'WGET_BINARY': {'type': str, 'default': 'wget'},
  152. 'SINGLEFILE_BINARY': {'type': str, 'default': lambda c: bin_path('single-file')},
  153. 'READABILITY_BINARY': {'type': str, 'default': lambda c: bin_path('readability-extractor')},
  154. 'MERCURY_BINARY': {'type': str, 'default': lambda c: bin_path('mercury-parser')},
  155. 'YOUTUBEDL_BINARY': {'type': str, 'default': 'youtube-dl'},
  156. 'NODE_BINARY': {'type': str, 'default': 'node'},
  157. 'RIPGREP_BINARY': {'type': str, 'default': 'rg'},
  158. 'CHROME_BINARY': {'type': str, 'default': None},
  159. 'POCKET_CONSUMER_KEY': {'type': str, 'default': None},
  160. 'POCKET_ACCESS_TOKENS': {'type': dict, 'default': {}},
  161. },
  162. }
  163. ########################## Backwards-Compatibility #############################
  164. # for backwards compatibility with old config files, check old/deprecated names for each key
  165. CONFIG_ALIASES = {
  166. alias: key
  167. for section in CONFIG_SCHEMA.values()
  168. for key, default in section.items()
  169. for alias in default.get('aliases', ())
  170. }
  171. USER_CONFIG = {key for section in CONFIG_SCHEMA.values() for key in section.keys()}
  172. def get_real_name(key: str) -> str:
  173. """get the current canonical name for a given deprecated config key"""
  174. return CONFIG_ALIASES.get(key.upper().strip(), key.upper().strip())
  175. ################################ Constants #####################################
  176. PACKAGE_DIR_NAME = 'archivebox'
  177. TEMPLATES_DIR_NAME = 'templates'
  178. ARCHIVE_DIR_NAME = 'archive'
  179. SOURCES_DIR_NAME = 'sources'
  180. LOGS_DIR_NAME = 'logs'
  181. SQL_INDEX_FILENAME = 'index.sqlite3'
  182. JSON_INDEX_FILENAME = 'index.json'
  183. HTML_INDEX_FILENAME = 'index.html'
  184. ROBOTS_TXT_FILENAME = 'robots.txt'
  185. FAVICON_FILENAME = 'favicon.ico'
  186. CONFIG_FILENAME = 'ArchiveBox.conf'
  187. DEFAULT_CLI_COLORS = {
  188. 'reset': '\033[00;00m',
  189. 'lightblue': '\033[01;30m',
  190. 'lightyellow': '\033[01;33m',
  191. 'lightred': '\033[01;35m',
  192. 'red': '\033[01;31m',
  193. 'green': '\033[01;32m',
  194. 'blue': '\033[01;34m',
  195. 'white': '\033[01;37m',
  196. 'black': '\033[01;30m',
  197. }
  198. ANSI = {k: '' for k in DEFAULT_CLI_COLORS.keys()}
  199. COLOR_DICT = defaultdict(lambda: [(0, 0, 0), (0, 0, 0)], {
  200. '00': [(0, 0, 0), (0, 0, 0)],
  201. '30': [(0, 0, 0), (0, 0, 0)],
  202. '31': [(255, 0, 0), (128, 0, 0)],
  203. '32': [(0, 200, 0), (0, 128, 0)],
  204. '33': [(255, 255, 0), (128, 128, 0)],
  205. '34': [(0, 0, 255), (0, 0, 128)],
  206. '35': [(255, 0, 255), (128, 0, 128)],
  207. '36': [(0, 255, 255), (0, 128, 128)],
  208. '37': [(255, 255, 255), (255, 255, 255)],
  209. })
  210. STATICFILE_EXTENSIONS = {
  211. # 99.999% of the time, URLs ending in these extensions are static files
  212. # that can be downloaded as-is, not html pages that need to be rendered
  213. 'gif', 'jpeg', 'jpg', 'png', 'tif', 'tiff', 'wbmp', 'ico', 'jng', 'bmp',
  214. 'svg', 'svgz', 'webp', 'ps', 'eps', 'ai',
  215. 'mp3', 'mp4', 'm4a', 'mpeg', 'mpg', 'mkv', 'mov', 'webm', 'm4v',
  216. 'flv', 'wmv', 'avi', 'ogg', 'ts', 'm3u8',
  217. 'pdf', 'txt', 'rtf', 'rtfd', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx',
  218. 'atom', 'rss', 'css', 'js', 'json',
  219. 'dmg', 'iso', 'img',
  220. 'rar', 'war', 'hqx', 'zip', 'gz', 'bz2', '7z',
  221. # Less common extensions to consider adding later
  222. # jar, swf, bin, com, exe, dll, deb
  223. # ear, hqx, eot, wmlc, kml, kmz, cco, jardiff, jnlp, run, msi, msp, msm,
  224. # pl pm, prc pdb, rar, rpm, sea, sit, tcl tk, der, pem, crt, xpi, xspf,
  225. # ra, mng, asx, asf, 3gpp, 3gp, mid, midi, kar, jad, wml, htc, mml
  226. # These are always treated as pages, not as static files, never add them:
  227. # html, htm, shtml, xhtml, xml, aspx, php, cgi
  228. }
  229. ############################## Derived Config ##################################
  230. DYNAMIC_CONFIG_SCHEMA: ConfigDefaultDict = {
  231. 'TERM_WIDTH': {'default': lambda c: lambda: shutil.get_terminal_size((100, 10)).columns},
  232. 'USER': {'default': lambda c: getpass.getuser() or os.getlogin()},
  233. 'ANSI': {'default': lambda c: DEFAULT_CLI_COLORS if c['USE_COLOR'] else {k: '' for k in DEFAULT_CLI_COLORS.keys()}},
  234. 'PACKAGE_DIR': {'default': lambda c: Path(__file__).resolve().parent},
  235. 'TEMPLATES_DIR': {'default': lambda c: c['PACKAGE_DIR'] / TEMPLATES_DIR_NAME},
  236. 'CUSTOM_TEMPLATES_DIR': {'default': lambda c: c['CUSTOM_TEMPLATES_DIR'] and Path(c['CUSTOM_TEMPLATES_DIR'])},
  237. 'OUTPUT_DIR': {'default': lambda c: Path(c['OUTPUT_DIR']).resolve() if c['OUTPUT_DIR'] else Path(os.curdir).resolve()},
  238. 'ARCHIVE_DIR': {'default': lambda c: c['OUTPUT_DIR'] / ARCHIVE_DIR_NAME},
  239. 'SOURCES_DIR': {'default': lambda c: c['OUTPUT_DIR'] / SOURCES_DIR_NAME},
  240. 'LOGS_DIR': {'default': lambda c: c['OUTPUT_DIR'] / LOGS_DIR_NAME},
  241. 'CONFIG_FILE': {'default': lambda c: Path(c['CONFIG_FILE']).resolve() if c['CONFIG_FILE'] else c['OUTPUT_DIR'] / CONFIG_FILENAME},
  242. 'COOKIES_FILE': {'default': lambda c: c['COOKIES_FILE'] and Path(c['COOKIES_FILE']).resolve()},
  243. 'CHROME_USER_DATA_DIR': {'default': lambda c: find_chrome_data_dir() if c['CHROME_USER_DATA_DIR'] is None else (Path(c['CHROME_USER_DATA_DIR']).resolve() if c['CHROME_USER_DATA_DIR'] else None)}, # None means unset, so we autodetect it with find_chrome_Data_dir(), but emptystring '' means user manually set it to '', and we should store it as None
  244. 'URL_BLACKLIST_PTN': {'default': lambda c: c['URL_BLACKLIST'] and re.compile(c['URL_BLACKLIST'] or '', re.IGNORECASE | re.UNICODE | re.MULTILINE)},
  245. 'ARCHIVEBOX_BINARY': {'default': lambda c: sys.argv[0] or bin_path('archivebox')},
  246. 'VERSION': {'default': lambda c: json.loads((Path(c['PACKAGE_DIR']) / 'package.json').read_text().strip())['version']},
  247. 'PYTHON_BINARY': {'default': lambda c: sys.executable},
  248. 'PYTHON_ENCODING': {'default': lambda c: sys.stdout.encoding.upper()},
  249. 'PYTHON_VERSION': {'default': lambda c: '{}.{}.{}'.format(*sys.version_info[:3])},
  250. 'DJANGO_BINARY': {'default': lambda c: django.__file__.replace('__init__.py', 'bin/django-admin.py')},
  251. 'DJANGO_VERSION': {'default': lambda c: '{}.{}.{} {} ({})'.format(*django.VERSION)},
  252. 'USE_CURL': {'default': lambda c: c['USE_CURL'] and (c['SAVE_FAVICON'] or c['SAVE_TITLE'] or c['SAVE_ARCHIVE_DOT_ORG'])},
  253. 'CURL_VERSION': {'default': lambda c: bin_version(c['CURL_BINARY']) if c['USE_CURL'] else None},
  254. 'CURL_USER_AGENT': {'default': lambda c: c['CURL_USER_AGENT'].format(**c)},
  255. 'CURL_ARGS': {'default': lambda c: c['CURL_ARGS'] or []},
  256. 'SAVE_FAVICON': {'default': lambda c: c['USE_CURL'] and c['SAVE_FAVICON']},
  257. 'SAVE_ARCHIVE_DOT_ORG': {'default': lambda c: c['USE_CURL'] and c['SAVE_ARCHIVE_DOT_ORG']},
  258. 'USE_WGET': {'default': lambda c: c['USE_WGET'] and (c['SAVE_WGET'] or c['SAVE_WARC'])},
  259. 'WGET_VERSION': {'default': lambda c: bin_version(c['WGET_BINARY']) if c['USE_WGET'] else None},
  260. 'WGET_AUTO_COMPRESSION': {'default': lambda c: wget_supports_compression(c) if c['USE_WGET'] else False},
  261. 'WGET_USER_AGENT': {'default': lambda c: c['WGET_USER_AGENT'].format(**c)},
  262. 'SAVE_WGET': {'default': lambda c: c['USE_WGET'] and c['SAVE_WGET']},
  263. 'SAVE_WARC': {'default': lambda c: c['USE_WGET'] and c['SAVE_WARC']},
  264. 'WGET_ARGS': {'default': lambda c: c['WGET_ARGS'] or []},
  265. 'RIPGREP_VERSION': {'default': lambda c: bin_version(c['RIPGREP_BINARY']) if c['USE_RIPGREP'] else None},
  266. 'USE_SINGLEFILE': {'default': lambda c: c['USE_SINGLEFILE'] and c['SAVE_SINGLEFILE']},
  267. 'SINGLEFILE_VERSION': {'default': lambda c: bin_version(c['SINGLEFILE_BINARY']) if c['USE_SINGLEFILE'] else None},
  268. 'USE_READABILITY': {'default': lambda c: c['USE_READABILITY'] and c['SAVE_READABILITY']},
  269. 'READABILITY_VERSION': {'default': lambda c: bin_version(c['READABILITY_BINARY']) if c['USE_READABILITY'] else None},
  270. 'USE_MERCURY': {'default': lambda c: c['USE_MERCURY'] and c['SAVE_MERCURY']},
  271. 'MERCURY_VERSION': {'default': lambda c: '1.0.0' if shutil.which(str(bin_path(c['MERCURY_BINARY']))) else None}, # mercury is unversioned
  272. 'USE_GIT': {'default': lambda c: c['USE_GIT'] and c['SAVE_GIT']},
  273. 'GIT_VERSION': {'default': lambda c: bin_version(c['GIT_BINARY']) if c['USE_GIT'] else None},
  274. 'SAVE_GIT': {'default': lambda c: c['USE_GIT'] and c['SAVE_GIT']},
  275. 'USE_YOUTUBEDL': {'default': lambda c: c['USE_YOUTUBEDL'] and c['SAVE_MEDIA']},
  276. 'YOUTUBEDL_VERSION': {'default': lambda c: bin_version(c['YOUTUBEDL_BINARY']) if c['USE_YOUTUBEDL'] else None},
  277. 'SAVE_MEDIA': {'default': lambda c: c['USE_YOUTUBEDL'] and c['SAVE_MEDIA']},
  278. 'YOUTUBEDL_ARGS': {'default': lambda c: c['YOUTUBEDL_ARGS'] or []},
  279. 'CHROME_BINARY': {'default': lambda c: c['CHROME_BINARY'] or find_chrome_binary()},
  280. 'USE_CHROME': {'default': lambda c: c['USE_CHROME'] and c['CHROME_BINARY'] and (c['SAVE_PDF'] or c['SAVE_SCREENSHOT'] or c['SAVE_DOM'] or c['SAVE_SINGLEFILE'])},
  281. 'CHROME_VERSION': {'default': lambda c: bin_version(c['CHROME_BINARY']) if c['USE_CHROME'] else None},
  282. 'SAVE_PDF': {'default': lambda c: c['USE_CHROME'] and c['SAVE_PDF']},
  283. 'SAVE_SCREENSHOT': {'default': lambda c: c['USE_CHROME'] and c['SAVE_SCREENSHOT']},
  284. 'SAVE_DOM': {'default': lambda c: c['USE_CHROME'] and c['SAVE_DOM']},
  285. 'SAVE_SINGLEFILE': {'default': lambda c: c['USE_CHROME'] and c['SAVE_SINGLEFILE'] and c['USE_NODE']},
  286. 'SAVE_READABILITY': {'default': lambda c: c['USE_READABILITY'] and c['USE_NODE']},
  287. 'SAVE_MERCURY': {'default': lambda c: c['USE_MERCURY'] and c['USE_NODE']},
  288. 'USE_NODE': {'default': lambda c: c['USE_NODE'] and (c['SAVE_READABILITY'] or c['SAVE_SINGLEFILE'] or c['SAVE_MERCURY'])},
  289. 'NODE_VERSION': {'default': lambda c: bin_version(c['NODE_BINARY']) if c['USE_NODE'] else None},
  290. 'DEPENDENCIES': {'default': lambda c: get_dependency_info(c)},
  291. 'CODE_LOCATIONS': {'default': lambda c: get_code_locations(c)},
  292. 'EXTERNAL_LOCATIONS': {'default': lambda c: get_external_locations(c)},
  293. 'DATA_LOCATIONS': {'default': lambda c: get_data_locations(c)},
  294. 'CHROME_OPTIONS': {'default': lambda c: get_chrome_info(c)},
  295. }
  296. ################################### Helpers ####################################
  297. def load_config_val(key: str,
  298. default: ConfigDefaultValue=None,
  299. type: Optional[Type]=None,
  300. aliases: Optional[Tuple[str, ...]]=None,
  301. config: Optional[ConfigDict]=None,
  302. env_vars: Optional[os._Environ]=None,
  303. config_file_vars: Optional[Dict[str, str]]=None) -> ConfigValue:
  304. """parse bool, int, and str key=value pairs from env"""
  305. config_keys_to_check = (key, *(aliases or ()))
  306. for key in config_keys_to_check:
  307. if env_vars:
  308. val = env_vars.get(key)
  309. if val:
  310. break
  311. if config_file_vars:
  312. val = config_file_vars.get(key)
  313. if val:
  314. break
  315. if type is None or val is None:
  316. if callable(default):
  317. assert isinstance(config, dict)
  318. return default(config)
  319. return default
  320. elif type is bool:
  321. if val.lower() in ('true', 'yes', '1'):
  322. return True
  323. elif val.lower() in ('false', 'no', '0'):
  324. return False
  325. else:
  326. raise ValueError(f'Invalid configuration option {key}={val} (expected a boolean: True/False)')
  327. elif type is str:
  328. if val.lower() in ('true', 'false', 'yes', 'no', '1', '0'):
  329. raise ValueError(f'Invalid configuration option {key}={val} (expected a string)')
  330. return val.strip()
  331. elif type is int:
  332. if not val.isdigit():
  333. raise ValueError(f'Invalid configuration option {key}={val} (expected an integer)')
  334. return int(val)
  335. elif type is list or type is dict:
  336. return json.loads(val)
  337. raise Exception('Config values can only be str, bool, int or json')
  338. def load_config_file(out_dir: str=None) -> Optional[Dict[str, str]]:
  339. """load the ini-formatted config file from OUTPUT_DIR/Archivebox.conf"""
  340. out_dir = out_dir or Path(os.getenv('OUTPUT_DIR', '.')).resolve()
  341. config_path = Path(out_dir) / CONFIG_FILENAME
  342. if config_path.exists():
  343. config_file = ConfigParser()
  344. config_file.optionxform = str
  345. config_file.read(config_path)
  346. # flatten into one namespace
  347. config_file_vars = {
  348. key.upper(): val
  349. for section, options in config_file.items()
  350. for key, val in options.items()
  351. }
  352. # print('[i] Loaded config file', os.path.abspath(config_path))
  353. # print(config_file_vars)
  354. return config_file_vars
  355. return None
  356. def write_config_file(config: Dict[str, str], out_dir: str=None) -> ConfigDict:
  357. """load the ini-formatted config file from OUTPUT_DIR/Archivebox.conf"""
  358. from .system import atomic_write
  359. CONFIG_HEADER = (
  360. """# This is the config file for your ArchiveBox collection.
  361. #
  362. # You can add options here manually in INI format, or automatically by running:
  363. # archivebox config --set KEY=VALUE
  364. #
  365. # If you modify this file manually, make sure to update your archive after by running:
  366. # archivebox init
  367. #
  368. # A list of all possible config with documentation and examples can be found here:
  369. # https://github.com/ArchiveBox/ArchiveBox/wiki/Configuration
  370. """)
  371. out_dir = out_dir or Path(os.getenv('OUTPUT_DIR', '.')).resolve()
  372. config_path = Path(out_dir) / CONFIG_FILENAME
  373. if not config_path.exists():
  374. atomic_write(config_path, CONFIG_HEADER)
  375. config_file = ConfigParser()
  376. config_file.optionxform = str
  377. config_file.read(config_path)
  378. with open(config_path, 'r', encoding='utf-8') as old:
  379. atomic_write(f'{config_path}.bak', old.read())
  380. find_section = lambda key: [name for name, opts in CONFIG_SCHEMA.items() if key in opts][0]
  381. # Set up sections in empty config file
  382. for key, val in config.items():
  383. section = find_section(key)
  384. if section in config_file:
  385. existing_config = dict(config_file[section])
  386. else:
  387. existing_config = {}
  388. config_file[section] = {**existing_config, key: val}
  389. # always make sure there's a SECRET_KEY defined for Django
  390. existing_secret_key = None
  391. if 'SERVER_CONFIG' in config_file and 'SECRET_KEY' in config_file['SERVER_CONFIG']:
  392. existing_secret_key = config_file['SERVER_CONFIG']['SECRET_KEY']
  393. if (not existing_secret_key) or ('not a valid secret' in existing_secret_key):
  394. from django.utils.crypto import get_random_string
  395. chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_'
  396. random_secret_key = get_random_string(50, chars)
  397. if 'SERVER_CONFIG' in config_file:
  398. config_file['SERVER_CONFIG']['SECRET_KEY'] = random_secret_key
  399. else:
  400. config_file['SERVER_CONFIG'] = {'SECRET_KEY': random_secret_key}
  401. with open(config_path, 'w+', encoding='utf-8') as new:
  402. config_file.write(new)
  403. try:
  404. # validate the config by attempting to re-parse it
  405. CONFIG = load_all_config()
  406. return {
  407. key.upper(): CONFIG.get(key.upper())
  408. for key in config.keys()
  409. }
  410. except BaseException:
  411. # something went horribly wrong, rever to the previous version
  412. with open(f'{config_path}.bak', 'r', encoding='utf-8') as old:
  413. atomic_write(config_path, old.read())
  414. if Path(f'{config_path}.bak').exists():
  415. os.remove(f'{config_path}.bak')
  416. return {}
  417. def load_config(defaults: ConfigDefaultDict,
  418. config: Optional[ConfigDict]=None,
  419. out_dir: Optional[str]=None,
  420. env_vars: Optional[os._Environ]=None,
  421. config_file_vars: Optional[Dict[str, str]]=None) -> ConfigDict:
  422. env_vars = env_vars or os.environ
  423. config_file_vars = config_file_vars or load_config_file(out_dir=out_dir)
  424. extended_config: ConfigDict = config.copy() if config else {}
  425. for key, default in defaults.items():
  426. try:
  427. extended_config[key] = load_config_val(
  428. key,
  429. default=default['default'],
  430. type=default.get('type'),
  431. aliases=default.get('aliases'),
  432. config=extended_config,
  433. env_vars=env_vars,
  434. config_file_vars=config_file_vars,
  435. )
  436. except KeyboardInterrupt:
  437. raise SystemExit(0)
  438. except Exception as e:
  439. stderr()
  440. stderr(f'[X] Error while loading configuration value: {key}', color='red', config=extended_config)
  441. stderr(' {}: {}'.format(e.__class__.__name__, e))
  442. stderr()
  443. stderr(' Check your config for mistakes and try again (your archive data is unaffected).')
  444. stderr()
  445. stderr(' For config documentation and examples see:')
  446. stderr(' https://github.com/ArchiveBox/ArchiveBox/wiki/Configuration')
  447. stderr()
  448. # raise
  449. raise SystemExit(2)
  450. return extended_config
  451. # def write_config(config: ConfigDict):
  452. # with open(os.path.join(config['OUTPUT_DIR'], CONFIG_FILENAME), 'w+') as f:
  453. # Logging Helpers
  454. def stdout(*args, color: Optional[str]=None, prefix: str='', config: Optional[ConfigDict]=None) -> None:
  455. ansi = DEFAULT_CLI_COLORS if (config or {}).get('USE_COLOR') else ANSI
  456. if color:
  457. strs = [ansi[color], ' '.join(str(a) for a in args), ansi['reset'], '\n']
  458. else:
  459. strs = [' '.join(str(a) for a in args), '\n']
  460. sys.stdout.write(prefix + ''.join(strs))
  461. def stderr(*args, color: Optional[str]=None, prefix: str='', config: Optional[ConfigDict]=None) -> None:
  462. ansi = DEFAULT_CLI_COLORS if (config or {}).get('USE_COLOR') else ANSI
  463. if color:
  464. strs = [ansi[color], ' '.join(str(a) for a in args), ansi['reset'], '\n']
  465. else:
  466. strs = [' '.join(str(a) for a in args), '\n']
  467. sys.stderr.write(prefix + ''.join(strs))
  468. def hint(text: Union[Tuple[str, ...], List[str], str], prefix=' ', config: Optional[ConfigDict]=None) -> None:
  469. ansi = DEFAULT_CLI_COLORS if (config or {}).get('USE_COLOR') else ANSI
  470. if isinstance(text, str):
  471. stderr('{}{lightred}Hint:{reset} {}'.format(prefix, text, **ansi))
  472. else:
  473. stderr('{}{lightred}Hint:{reset} {}'.format(prefix, text[0], **ansi))
  474. for line in text[1:]:
  475. stderr('{} {}'.format(prefix, line))
  476. # Dependency Metadata Helpers
  477. def bin_version(binary: Optional[str]) -> Optional[str]:
  478. """check the presence and return valid version line of a specified binary"""
  479. abspath = bin_path(binary)
  480. if not binary or not abspath:
  481. return None
  482. try:
  483. version_str = run([abspath, "--version"], stdout=PIPE).stdout.strip().decode()
  484. # take first 3 columns of first line of version info
  485. return ' '.join(version_str.split('\n')[0].strip().split()[:3])
  486. except OSError:
  487. pass
  488. # stderr(f'[X] Unable to find working version of dependency: {binary}', color='red')
  489. # stderr(' Make sure it\'s installed, then confirm it\'s working by running:')
  490. # stderr(f' {binary} --version')
  491. # stderr()
  492. # stderr(' If you don\'t want to install it, you can disable it via config. See here for more info:')
  493. # stderr(' https://github.com/ArchiveBox/ArchiveBox/wiki/Install')
  494. return None
  495. def bin_path(binary: Optional[str]) -> Optional[str]:
  496. if binary is None:
  497. return None
  498. node_modules_bin = Path('.') / 'node_modules' / '.bin' / binary
  499. if node_modules_bin.exists():
  500. return str(node_modules_bin.resolve())
  501. return shutil.which(str(Path(binary).expanduser())) or shutil.which(str(binary)) or binary
  502. def bin_hash(binary: Optional[str]) -> Optional[str]:
  503. if binary is None:
  504. return None
  505. abs_path = bin_path(binary)
  506. if abs_path is None or not Path(abs_path).exists():
  507. return None
  508. file_hash = md5()
  509. with io.open(abs_path, mode='rb') as f:
  510. for chunk in iter(lambda: f.read(io.DEFAULT_BUFFER_SIZE), b''):
  511. file_hash.update(chunk)
  512. return f'md5:{file_hash.hexdigest()}'
  513. def find_chrome_binary() -> Optional[str]:
  514. """find any installed chrome binaries in the default locations"""
  515. # Precedence: Chromium, Chrome, Beta, Canary, Unstable, Dev
  516. # make sure data dir finding precedence order always matches binary finding order
  517. default_executable_paths = (
  518. 'chromium-browser',
  519. 'chromium',
  520. '/Applications/Chromium.app/Contents/MacOS/Chromium',
  521. 'chrome',
  522. 'google-chrome',
  523. '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
  524. 'google-chrome-stable',
  525. 'google-chrome-beta',
  526. 'google-chrome-canary',
  527. '/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary',
  528. 'google-chrome-unstable',
  529. 'google-chrome-dev',
  530. )
  531. for name in default_executable_paths:
  532. full_path_exists = shutil.which(name)
  533. if full_path_exists:
  534. return name
  535. return None
  536. def find_chrome_data_dir() -> Optional[str]:
  537. """find any installed chrome user data directories in the default locations"""
  538. # Precedence: Chromium, Chrome, Beta, Canary, Unstable, Dev
  539. # make sure data dir finding precedence order always matches binary finding order
  540. default_profile_paths = (
  541. '~/.config/chromium',
  542. '~/Library/Application Support/Chromium',
  543. '~/AppData/Local/Chromium/User Data',
  544. '~/.config/chrome',
  545. '~/.config/google-chrome',
  546. '~/Library/Application Support/Google/Chrome',
  547. '~/AppData/Local/Google/Chrome/User Data',
  548. '~/.config/google-chrome-stable',
  549. '~/.config/google-chrome-beta',
  550. '~/Library/Application Support/Google/Chrome Canary',
  551. '~/AppData/Local/Google/Chrome SxS/User Data',
  552. '~/.config/google-chrome-unstable',
  553. '~/.config/google-chrome-dev',
  554. )
  555. for path in default_profile_paths:
  556. full_path = Path(path).resolve()
  557. if full_path.exists():
  558. return full_path
  559. return None
  560. def wget_supports_compression(config):
  561. try:
  562. cmd = [
  563. config['WGET_BINARY'],
  564. "--compression=auto",
  565. "--help",
  566. ]
  567. return not run(cmd, stdout=DEVNULL, stderr=DEVNULL).returncode
  568. except (FileNotFoundError, OSError):
  569. return False
  570. def get_code_locations(config: ConfigDict) -> SimpleConfigValueDict:
  571. return {
  572. 'PACKAGE_DIR': {
  573. 'path': (config['PACKAGE_DIR']).resolve(),
  574. 'enabled': True,
  575. 'is_valid': (config['PACKAGE_DIR'] / '__main__.py').exists(),
  576. },
  577. 'TEMPLATES_DIR': {
  578. 'path': (config['TEMPLATES_DIR']).resolve(),
  579. 'enabled': True,
  580. 'is_valid': (config['TEMPLATES_DIR'] / 'static').exists(),
  581. },
  582. 'CUSTOM_TEMPLATES_DIR': {
  583. 'path': config['CUSTOM_TEMPLATES_DIR'] and Path(config['CUSTOM_TEMPLATES_DIR']).resolve(),
  584. 'enabled': bool(config['CUSTOM_TEMPLATES_DIR']),
  585. 'is_valid': config['CUSTOM_TEMPLATES_DIR'] and Path(config['CUSTOM_TEMPLATES_DIR']).exists(),
  586. },
  587. # 'NODE_MODULES_DIR': {
  588. # 'path': ,
  589. # 'enabled': ,
  590. # 'is_valid': (...).exists(),
  591. # },
  592. }
  593. def get_external_locations(config: ConfigDict) -> ConfigValue:
  594. abspath = lambda path: None if path is None else Path(path).resolve()
  595. return {
  596. 'CHROME_USER_DATA_DIR': {
  597. 'path': abspath(config['CHROME_USER_DATA_DIR']),
  598. 'enabled': config['USE_CHROME'] and config['CHROME_USER_DATA_DIR'],
  599. 'is_valid': False if config['CHROME_USER_DATA_DIR'] is None else (Path(config['CHROME_USER_DATA_DIR']) / 'Default').exists(),
  600. },
  601. 'COOKIES_FILE': {
  602. 'path': abspath(config['COOKIES_FILE']),
  603. 'enabled': config['USE_WGET'] and config['COOKIES_FILE'],
  604. 'is_valid': False if config['COOKIES_FILE'] is None else Path(config['COOKIES_FILE']).exists(),
  605. },
  606. }
  607. def get_data_locations(config: ConfigDict) -> ConfigValue:
  608. return {
  609. 'OUTPUT_DIR': {
  610. 'path': config['OUTPUT_DIR'].resolve(),
  611. 'enabled': True,
  612. 'is_valid': (config['OUTPUT_DIR'] / SQL_INDEX_FILENAME).exists(),
  613. },
  614. 'SOURCES_DIR': {
  615. 'path': config['SOURCES_DIR'].resolve(),
  616. 'enabled': True,
  617. 'is_valid': config['SOURCES_DIR'].exists(),
  618. },
  619. 'LOGS_DIR': {
  620. 'path': config['LOGS_DIR'].resolve(),
  621. 'enabled': True,
  622. 'is_valid': config['LOGS_DIR'].exists(),
  623. },
  624. 'ARCHIVE_DIR': {
  625. 'path': config['ARCHIVE_DIR'].resolve(),
  626. 'enabled': True,
  627. 'is_valid': config['ARCHIVE_DIR'].exists(),
  628. },
  629. 'CONFIG_FILE': {
  630. 'path': config['CONFIG_FILE'].resolve(),
  631. 'enabled': True,
  632. 'is_valid': config['CONFIG_FILE'].exists(),
  633. },
  634. 'SQL_INDEX': {
  635. 'path': (config['OUTPUT_DIR'] / SQL_INDEX_FILENAME).resolve(),
  636. 'enabled': True,
  637. 'is_valid': (config['OUTPUT_DIR'] / SQL_INDEX_FILENAME).exists(),
  638. },
  639. }
  640. def get_dependency_info(config: ConfigDict) -> ConfigValue:
  641. return {
  642. 'ARCHIVEBOX_BINARY': {
  643. 'path': bin_path(config['ARCHIVEBOX_BINARY']),
  644. 'version': config['VERSION'],
  645. 'hash': bin_hash(config['ARCHIVEBOX_BINARY']),
  646. 'enabled': True,
  647. 'is_valid': True,
  648. },
  649. 'PYTHON_BINARY': {
  650. 'path': bin_path(config['PYTHON_BINARY']),
  651. 'version': config['PYTHON_VERSION'],
  652. 'hash': bin_hash(config['PYTHON_BINARY']),
  653. 'enabled': True,
  654. 'is_valid': bool(config['PYTHON_VERSION']),
  655. },
  656. 'DJANGO_BINARY': {
  657. 'path': bin_path(config['DJANGO_BINARY']),
  658. 'version': config['DJANGO_VERSION'],
  659. 'hash': bin_hash(config['DJANGO_BINARY']),
  660. 'enabled': True,
  661. 'is_valid': bool(config['DJANGO_VERSION']),
  662. },
  663. 'CURL_BINARY': {
  664. 'path': bin_path(config['CURL_BINARY']),
  665. 'version': config['CURL_VERSION'],
  666. 'hash': bin_hash(config['CURL_BINARY']),
  667. 'enabled': config['USE_CURL'],
  668. 'is_valid': bool(config['CURL_VERSION']),
  669. },
  670. 'WGET_BINARY': {
  671. 'path': bin_path(config['WGET_BINARY']),
  672. 'version': config['WGET_VERSION'],
  673. 'hash': bin_hash(config['WGET_BINARY']),
  674. 'enabled': config['USE_WGET'],
  675. 'is_valid': bool(config['WGET_VERSION']),
  676. },
  677. 'NODE_BINARY': {
  678. 'path': bin_path(config['NODE_BINARY']),
  679. 'version': config['NODE_VERSION'],
  680. 'hash': bin_hash(config['NODE_BINARY']),
  681. 'enabled': config['USE_NODE'],
  682. 'is_valid': bool(config['NODE_VERSION']),
  683. },
  684. 'SINGLEFILE_BINARY': {
  685. 'path': bin_path(config['SINGLEFILE_BINARY']),
  686. 'version': config['SINGLEFILE_VERSION'],
  687. 'hash': bin_hash(config['SINGLEFILE_BINARY']),
  688. 'enabled': config['USE_SINGLEFILE'],
  689. 'is_valid': bool(config['SINGLEFILE_VERSION']),
  690. },
  691. 'READABILITY_BINARY': {
  692. 'path': bin_path(config['READABILITY_BINARY']),
  693. 'version': config['READABILITY_VERSION'],
  694. 'hash': bin_hash(config['READABILITY_BINARY']),
  695. 'enabled': config['USE_READABILITY'],
  696. 'is_valid': bool(config['READABILITY_VERSION']),
  697. },
  698. 'MERCURY_BINARY': {
  699. 'path': bin_path(config['MERCURY_BINARY']),
  700. 'version': config['MERCURY_VERSION'],
  701. 'hash': bin_hash(config['MERCURY_BINARY']),
  702. 'enabled': config['USE_MERCURY'],
  703. 'is_valid': bool(config['MERCURY_VERSION']),
  704. },
  705. 'GIT_BINARY': {
  706. 'path': bin_path(config['GIT_BINARY']),
  707. 'version': config['GIT_VERSION'],
  708. 'hash': bin_hash(config['GIT_BINARY']),
  709. 'enabled': config['USE_GIT'],
  710. 'is_valid': bool(config['GIT_VERSION']),
  711. },
  712. 'YOUTUBEDL_BINARY': {
  713. 'path': bin_path(config['YOUTUBEDL_BINARY']),
  714. 'version': config['YOUTUBEDL_VERSION'],
  715. 'hash': bin_hash(config['YOUTUBEDL_BINARY']),
  716. 'enabled': config['USE_YOUTUBEDL'],
  717. 'is_valid': bool(config['YOUTUBEDL_VERSION']),
  718. },
  719. 'CHROME_BINARY': {
  720. 'path': bin_path(config['CHROME_BINARY']),
  721. 'version': config['CHROME_VERSION'],
  722. 'hash': bin_hash(config['CHROME_BINARY']),
  723. 'enabled': config['USE_CHROME'],
  724. 'is_valid': bool(config['CHROME_VERSION']),
  725. },
  726. 'RIPGREP_BINARY': {
  727. 'path': bin_path(config['RIPGREP_BINARY']),
  728. 'version': config['RIPGREP_VERSION'],
  729. 'hash': bin_hash(config['RIPGREP_BINARY']),
  730. 'enabled': config['USE_RIPGREP'],
  731. 'is_valid': bool(config['RIPGREP_VERSION']),
  732. },
  733. # TODO: add an entry for the sonic search backend?
  734. # 'SONIC_BINARY': {
  735. # 'path': bin_path(config['SONIC_BINARY']),
  736. # 'version': config['SONIC_VERSION'],
  737. # 'hash': bin_hash(config['SONIC_BINARY']),
  738. # 'enabled': config['USE_SONIC'],
  739. # 'is_valid': bool(config['SONIC_VERSION']),
  740. # },
  741. }
  742. def get_chrome_info(config: ConfigDict) -> ConfigValue:
  743. return {
  744. 'TIMEOUT': config['TIMEOUT'],
  745. 'RESOLUTION': config['RESOLUTION'],
  746. 'CHECK_SSL_VALIDITY': config['CHECK_SSL_VALIDITY'],
  747. 'CHROME_BINARY': config['CHROME_BINARY'],
  748. 'CHROME_HEADLESS': config['CHROME_HEADLESS'],
  749. 'CHROME_SANDBOX': config['CHROME_SANDBOX'],
  750. 'CHROME_USER_AGENT': config['CHROME_USER_AGENT'],
  751. 'CHROME_USER_DATA_DIR': config['CHROME_USER_DATA_DIR'],
  752. }
  753. # ******************************************************************************
  754. # ******************************************************************************
  755. # ******************************** Load Config *********************************
  756. # ******* (compile the defaults, configs, and metadata all into CONFIG) ********
  757. # ******************************************************************************
  758. # ******************************************************************************
  759. def load_all_config():
  760. CONFIG: ConfigDict = {}
  761. for section_name, section_config in CONFIG_SCHEMA.items():
  762. CONFIG = load_config(section_config, CONFIG)
  763. return load_config(DYNAMIC_CONFIG_SCHEMA, CONFIG)
  764. # add all final config values in CONFIG to globals in this file
  765. CONFIG = load_all_config()
  766. globals().update(CONFIG)
  767. # this lets us do: from .config import DEBUG, MEDIA_TIMEOUT, ...
  768. # ******************************************************************************
  769. # ******************************************************************************
  770. # ******************************************************************************
  771. # ******************************************************************************
  772. # ******************************************************************************
  773. ########################### System Environment Setup ###########################
  774. # Set timezone to UTC and umask to OUTPUT_PERMISSIONS
  775. os.environ["TZ"] = 'UTC'
  776. os.umask(0o777 - int(OUTPUT_PERMISSIONS, base=8)) # noqa: F821
  777. # add ./node_modules/.bin to $PATH so we can use node scripts in extractors
  778. NODE_BIN_PATH = str((Path(CONFIG["OUTPUT_DIR"]).absolute() / 'node_modules' / '.bin'))
  779. sys.path.append(NODE_BIN_PATH)
  780. # disable stderr "you really shouldnt disable ssl" warnings with library config
  781. if not CONFIG['CHECK_SSL_VALIDITY']:
  782. import urllib3
  783. import requests
  784. requests.packages.urllib3.disable_warnings(requests.packages.urllib3.exceptions.InsecureRequestWarning)
  785. urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
  786. ########################### Config Validity Checkers ###########################
  787. def check_system_config(config: ConfigDict=CONFIG) -> None:
  788. ### Check system environment
  789. if config['USER'] == 'root':
  790. stderr('[!] ArchiveBox should never be run as root!', color='red')
  791. stderr(' For more information, see the security overview documentation:')
  792. stderr(' https://github.com/ArchiveBox/ArchiveBox/wiki/Security-Overview#do-not-run-as-root')
  793. raise SystemExit(2)
  794. ### Check Python environment
  795. if sys.version_info[:3] < (3, 6, 0):
  796. stderr(f'[X] Python version is not new enough: {config["PYTHON_VERSION"]} (>3.6 is required)', color='red')
  797. stderr(' See https://github.com/ArchiveBox/ArchiveBox/wiki/Troubleshooting#python for help upgrading your Python installation.')
  798. raise SystemExit(2)
  799. if config['PYTHON_ENCODING'] not in ('UTF-8', 'UTF8'):
  800. stderr(f'[X] Your system is running python3 scripts with a bad locale setting: {config["PYTHON_ENCODING"]} (it should be UTF-8).', color='red')
  801. stderr(' To fix it, add the line "export PYTHONIOENCODING=UTF-8" to your ~/.bashrc file (without quotes)')
  802. stderr(' Or if you\'re using ubuntu/debian, run "dpkg-reconfigure locales"')
  803. stderr('')
  804. stderr(' Confirm that it\'s fixed by opening a new shell and running:')
  805. stderr(' python3 -c "import sys; print(sys.stdout.encoding)" # should output UTF-8')
  806. raise SystemExit(2)
  807. # stderr('[i] Using Chrome binary: {}'.format(shutil.which(CHROME_BINARY) or CHROME_BINARY))
  808. # stderr('[i] Using Chrome data dir: {}'.format(os.path.abspath(CHROME_USER_DATA_DIR)))
  809. if config['CHROME_USER_DATA_DIR'] is not None:
  810. if not (Path(config['CHROME_USER_DATA_DIR']) / 'Default').exists():
  811. stderr('[X] Could not find profile "Default" in CHROME_USER_DATA_DIR.', color='red')
  812. stderr(f' {config["CHROME_USER_DATA_DIR"]}')
  813. stderr(' Make sure you set it to a Chrome user data directory containing a Default profile folder.')
  814. stderr(' For more info see:')
  815. stderr(' https://github.com/ArchiveBox/ArchiveBox/wiki/Configuration#CHROME_USER_DATA_DIR')
  816. if '/Default' in str(config['CHROME_USER_DATA_DIR']):
  817. stderr()
  818. stderr(' Try removing /Default from the end e.g.:')
  819. stderr(' CHROME_USER_DATA_DIR="{}"'.format(config['CHROME_USER_DATA_DIR'].split('/Default')[0]))
  820. raise SystemExit(2)
  821. def check_dependencies(config: ConfigDict=CONFIG, show_help: bool=True) -> None:
  822. invalid_dependencies = [
  823. (name, info) for name, info in config['DEPENDENCIES'].items()
  824. if info['enabled'] and not info['is_valid']
  825. ]
  826. if invalid_dependencies and show_help:
  827. stderr(f'[!] Warning: Missing {len(invalid_dependencies)} recommended dependencies', color='lightyellow')
  828. for dependency, info in invalid_dependencies:
  829. stderr(
  830. ' ! {}: {} ({})'.format(
  831. dependency,
  832. info['path'] or 'unable to find binary',
  833. info['version'] or 'unable to detect version',
  834. )
  835. )
  836. if dependency in ('YOUTUBEDL_BINARY', 'CHROME_BINARY', 'SINGLEFILE_BINARY', 'READABILITY_BINARY', 'MERCURY_BINARY'):
  837. hint(('To install all packages automatically run: archivebox setup',
  838. f'or to disable it and silence this warning: archivebox config --set SAVE_{dependency.rsplit("_", 1)[0]}=False',
  839. ''), prefix=' ')
  840. stderr('')
  841. if config['TIMEOUT'] < 5:
  842. stderr(f'[!] Warning: TIMEOUT is set too low! (currently set to TIMEOUT={config["TIMEOUT"]} seconds)', color='red')
  843. stderr(' You must allow *at least* 5 seconds for indexing and archive methods to run succesfully.')
  844. stderr(' (Setting it to somewhere between 30 and 3000 seconds is recommended)')
  845. stderr()
  846. stderr(' If you want to make ArchiveBox run faster, disable specific archive methods instead:')
  847. stderr(' https://github.com/ArchiveBox/ArchiveBox/wiki/Configuration#archive-method-toggles')
  848. stderr()
  849. elif config['USE_CHROME'] and config['TIMEOUT'] < 15:
  850. stderr(f'[!] Warning: TIMEOUT is set too low! (currently set to TIMEOUT={config["TIMEOUT"]} seconds)', color='red')
  851. stderr(' Chrome will fail to archive all sites if set to less than ~15 seconds.')
  852. stderr(' (Setting it to somewhere between 30 and 300 seconds is recommended)')
  853. stderr()
  854. stderr(' If you want to make ArchiveBox run faster, disable specific archive methods instead:')
  855. stderr(' https://github.com/ArchiveBox/ArchiveBox/wiki/Configuration#archive-method-toggles')
  856. stderr()
  857. if config['USE_YOUTUBEDL'] and config['MEDIA_TIMEOUT'] < 20:
  858. stderr(f'[!] Warning: MEDIA_TIMEOUT is set too low! (currently set to MEDIA_TIMEOUT={config["MEDIA_TIMEOUT"]} seconds)', color='red')
  859. stderr(' Youtube-dl will fail to archive all media if set to less than ~20 seconds.')
  860. stderr(' (Setting it somewhere over 60 seconds is recommended)')
  861. stderr()
  862. stderr(' If you want to disable media archiving entirely, set SAVE_MEDIA=False instead:')
  863. stderr(' https://github.com/ArchiveBox/ArchiveBox/wiki/Configuration#save_media')
  864. stderr()
  865. def check_data_folder(out_dir: Union[str, Path, None]=None, config: ConfigDict=CONFIG) -> None:
  866. output_dir = out_dir or config['OUTPUT_DIR']
  867. assert isinstance(output_dir, (str, Path))
  868. archive_dir_exists = (Path(output_dir) / ARCHIVE_DIR_NAME).exists()
  869. if not archive_dir_exists:
  870. stderr('[X] No archivebox index found in the current directory.', color='red')
  871. stderr(f' {output_dir}', color='lightyellow')
  872. stderr()
  873. stderr(' {lightred}Hint{reset}: Are you running archivebox in the right folder?'.format(**config['ANSI']))
  874. stderr(' cd path/to/your/archive/folder')
  875. stderr(' archivebox [command]')
  876. stderr()
  877. stderr(' {lightred}Hint{reset}: To create a new archive collection or import existing data in this folder, run:'.format(**config['ANSI']))
  878. stderr(' archivebox init')
  879. raise SystemExit(2)
  880. def check_migrations(out_dir: Union[str, Path, None]=None, config: ConfigDict=CONFIG):
  881. output_dir = out_dir or config['OUTPUT_DIR']
  882. from .index.sql import list_migrations
  883. pending_migrations = [name for status, name in list_migrations() if not status]
  884. if pending_migrations:
  885. stderr('[X] This collection was created with an older version of ArchiveBox and must be upgraded first.', color='lightyellow')
  886. stderr(f' {output_dir}')
  887. stderr()
  888. stderr(f' To upgrade it to the latest version and apply the {len(pending_migrations)} pending migrations, run:')
  889. stderr(' archivebox init')
  890. raise SystemExit(3)
  891. (Path(output_dir) / SOURCES_DIR_NAME).mkdir(exist_ok=True)
  892. (Path(output_dir) / LOGS_DIR_NAME).mkdir(exist_ok=True)
  893. def setup_django(out_dir: Path=None, check_db=False, config: ConfigDict=CONFIG, in_memory_db=False) -> None:
  894. check_system_config()
  895. output_dir = out_dir or Path(config['OUTPUT_DIR'])
  896. assert isinstance(output_dir, Path) and isinstance(config['PACKAGE_DIR'], Path)
  897. try:
  898. from django.core.management import call_command
  899. sys.path.append(str(config['PACKAGE_DIR']))
  900. os.environ.setdefault('OUTPUT_DIR', str(output_dir))
  901. assert (config['PACKAGE_DIR'] / 'core' / 'settings.py').exists(), 'settings.py was not found at archivebox/core/settings.py'
  902. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')
  903. # Check to make sure JSON extension is available in our Sqlite3 instance
  904. try:
  905. cursor = sqlite3.connect(':memory:').cursor()
  906. cursor.execute('SELECT JSON(\'{"a": "b"}\')')
  907. except sqlite3.OperationalError as exc:
  908. stderr(f'[X] Your SQLite3 version is missing the required JSON1 extension: {exc}', color='red')
  909. hint([
  910. 'Upgrade your Python version or install the extension manually:',
  911. 'https://code.djangoproject.com/wiki/JSON1Extension'
  912. ])
  913. if in_memory_db:
  914. # some commands (e.g. oneshot) dont store a long-lived sqlite3 db file on disk.
  915. # in those cases we create a temporary in-memory db and run the migrations
  916. # immediately to get a usable in-memory-database at startup
  917. os.environ.setdefault("ARCHIVEBOX_DATABASE_NAME", ":memory:")
  918. django.setup()
  919. call_command("migrate", interactive=False, verbosity=0)
  920. else:
  921. # Otherwise use default sqlite3 file-based database and initialize django
  922. # without running migrations automatically (user runs them manually by calling init)
  923. django.setup()
  924. from django.conf import settings
  925. # log startup message to the error log
  926. with open(settings.ERROR_LOG, "a+", encoding='utf-8') as f:
  927. command = ' '.join(sys.argv)
  928. ts = datetime.now().strftime('%Y-%m-%d__%H:%M:%S')
  929. f.write(f"\n> {command}; ts={ts} version={config['VERSION']} docker={config['IN_DOCKER']} is_tty={config['IS_TTY']}\n")
  930. if check_db:
  931. # Enable WAL mode in sqlite3
  932. from django.db import connection
  933. with connection.cursor() as cursor:
  934. current_mode = cursor.execute("PRAGMA journal_mode")
  935. if current_mode != 'wal':
  936. cursor.execute("PRAGMA journal_mode=wal;")
  937. # Create cache table in DB if needed
  938. try:
  939. from django.core.cache import cache
  940. cache.get('test', None)
  941. except django.db.utils.OperationalError:
  942. call_command("createcachetable", verbosity=0)
  943. # if archivebox gets imported multiple times, we have to close
  944. # the sqlite3 whenever we init from scratch to avoid multiple threads
  945. # sharing the same connection by accident
  946. from django.db import connections
  947. for conn in connections.all():
  948. conn.close_if_unusable_or_obsolete()
  949. sql_index_path = Path(output_dir) / SQL_INDEX_FILENAME
  950. assert sql_index_path.exists(), (
  951. f'No database file {SQL_INDEX_FILENAME} found in: {config["OUTPUT_DIR"]} (Are you in an ArchiveBox collection directory?)')
  952. except KeyboardInterrupt:
  953. raise SystemExit(2)