config.py 57 KB

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