forked from QuantumNous/new-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuse-system-config.ts
More file actions
204 lines (180 loc) · 5.57 KB
/
Copy pathuse-system-config.ts
File metadata and controls
204 lines (180 loc) · 5.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useEffect, useCallback } from 'react'
import { DEFAULT_SYSTEM_NAME, DEFAULT_LOGO } from '@/lib/constants'
import { applyFaviconToDom } from '@/lib/dom-utils'
import {
useSystemConfigStore,
type CurrencyConfig,
type CurrencyDisplayType,
type SystemConfig,
DEFAULT_CURRENCY_CONFIG,
} from '@/stores/system-config-store'
interface UseSystemConfigOptions {
/** Automatically fetch config from backend (use only in root component) */
autoLoad?: boolean
}
interface StatusApiResponse {
success: boolean
data: {
system_name?: string
logo?: string
footer_html?: string
demo_site_enabled?: boolean
display_token_stat_enabled?: boolean
display_in_currency?: boolean
quota_display_type?: CurrencyDisplayType
quota_per_unit?: number
usd_exchange_rate?: number
custom_currency_symbol?: string
custom_currency_exchange_rate?: number
}
}
function toNumber(value: unknown, fallback: number): number {
if (typeof value === 'number' && !Number.isNaN(value)) return value
if (typeof value === 'string') {
const parsed = Number(value)
if (!Number.isNaN(parsed)) return parsed
}
return fallback
}
/**
* Map `/api/status` response data to our persisted system config structure
*/
export function mapStatusDataToConfig(
data: StatusApiResponse['data'] | undefined
): Partial<SystemConfig> {
if (!data) return {}
const quotaDisplayType =
(data.quota_display_type as CurrencyDisplayType | undefined) ??
DEFAULT_CURRENCY_CONFIG.quotaDisplayType
const currency: CurrencyConfig = {
displayInCurrency:
data.display_in_currency ?? DEFAULT_CURRENCY_CONFIG.displayInCurrency,
quotaDisplayType,
quotaPerUnit: toNumber(
data.quota_per_unit,
DEFAULT_CURRENCY_CONFIG.quotaPerUnit
),
usdExchangeRate: toNumber(
data.usd_exchange_rate,
DEFAULT_CURRENCY_CONFIG.usdExchangeRate
),
customCurrencySymbol:
data.custom_currency_symbol?.trim() ||
DEFAULT_CURRENCY_CONFIG.customCurrencySymbol,
customCurrencyExchangeRate: toNumber(
data.custom_currency_exchange_rate,
DEFAULT_CURRENCY_CONFIG.customCurrencyExchangeRate
),
}
return {
systemName: data.system_name || DEFAULT_SYSTEM_NAME,
logo: data.logo || DEFAULT_LOGO,
footerHtml: data.footer_html,
demoSiteEnabled: data.demo_site_enabled,
displayTokenStatEnabled: data.display_token_stat_enabled,
currency,
}
}
// Fetch system config from API
async function fetchSystemConfig(): Promise<Partial<SystemConfig>> {
const response = await fetch('/api/status')
if (!response.ok) throw new Error('Failed to fetch status')
const data: StatusApiResponse = await response.json()
if (!data.success) throw new Error('API returned error')
return mapStatusDataToConfig(data.data)
}
// Preload image and return cleanup function
function preloadImage(
src: string,
onLoad: () => void,
onError: () => void
): () => void {
const img = new Image()
img.onload = onLoad
img.onerror = onError
img.src = src
return () => {
img.onload = null
img.onerror = null
}
}
/**
* System configuration hook with auto-loading and logo preloading
*
* @example
* // Root component - auto-load from backend
* useSystemConfig({ autoLoad: true })
*
* @example
* // Other components - use cached config
* const { systemName, logo, loading } = useSystemConfig()
*/
export function useSystemConfig(options: UseSystemConfigOptions = {}) {
const { autoLoad = false } = options
const {
config,
loading,
loadedLogoUrl,
setConfig,
setLoadedLogoUrl,
setLoading,
} = useSystemConfigStore()
// Load config from backend
const loadConfig = useCallback(async () => {
try {
setLoading(true)
const newConfig = await fetchSystemConfig()
setConfig(newConfig)
} catch (error) {
// eslint-disable-next-line no-console
console.error('Failed to load system config:', error)
} finally {
setLoading(false)
}
}, [setConfig, setLoading])
useEffect(() => {
if (autoLoad) loadConfig()
}, [autoLoad, loadConfig])
// Preload logo image when URL changes
useEffect(() => {
const { logo } = config
// Skip if logo is already loaded
if (!logo || logo === loadedLogoUrl) return
// Preload new logo
return preloadImage(
logo,
() => {
setLoadedLogoUrl(logo)
applyFaviconToDom(logo)
},
() => {
if (logo !== DEFAULT_LOGO) {
// eslint-disable-next-line no-console
console.error('Failed to load logo:', logo)
}
// Mark as loaded even on error to prevent infinite retry
setLoadedLogoUrl(logo)
}
)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [config.logo, loadedLogoUrl, setLoadedLogoUrl])
return {
...config,
loading,
logoLoaded: config.logo === loadedLogoUrl && !!loadedLogoUrl,
}
}