config.py 69 KB

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