config.py 68 KB

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