config.py 74 KB

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