config.py 59 KB

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