config.py 71 KB

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