config.py 60 KB

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