config.py 57 KB

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