xiaoyukkkk commited on
Commit
e796cfc
·
verified ·
1 Parent(s): 49d7f7c

Upload 2 files

Browse files
Files changed (2) hide show
  1. static/js/admin.js +328 -0
  2. static/js/api.js +41 -0
static/js/admin.js CHANGED
@@ -0,0 +1,328 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ let currentConfig = null;
2
+
3
+ // 标签页切换函数
4
+ function switchTab(tabName) {
5
+ // 隐藏所有标签页内容
6
+ document.querySelectorAll('.tab-content').forEach(content => {
7
+ content.classList.remove('active');
8
+ });
9
+ // 移除所有标签按钮的active状态
10
+ document.querySelectorAll('.tab-button').forEach(button => {
11
+ button.classList.remove('active');
12
+ });
13
+
14
+ // 显示选中的标签页
15
+ document.getElementById('tab-' + tabName).classList.add('active');
16
+ // 激活对应的按钮
17
+ event.target.classList.add('active');
18
+ }
19
+
20
+ // 统一的页面刷新函数(避免缓存)
21
+ function refreshPage() {
22
+ window.location.reload();
23
+ }
24
+
25
+ // 统一的错误处理函数
26
+ async function handleApiResponse(response) {
27
+ if (!response.ok) {
28
+ const errorText = await response.text();
29
+ let errorMsg;
30
+ try {
31
+ const errorJson = JSON.parse(errorText);
32
+ errorMsg = errorJson.detail || errorJson.message || errorText;
33
+ } catch {
34
+ errorMsg = errorText;
35
+ }
36
+ throw new Error(`HTTP $${response.status}: $${errorMsg}`);
37
+ }
38
+ return await response.json();
39
+ }
40
+
41
+ async function showEditConfig() {
42
+ const config = await fetch(`/${window.ADMIN_PATH}/accounts-config`).then(r => r.json());
43
+ currentConfig = config.accounts;
44
+ const json = JSON.stringify(config.accounts, null, 2);
45
+ document.getElementById('jsonEditor').value = json;
46
+ document.getElementById('jsonError').classList.remove('show');
47
+ document.getElementById('jsonModal').classList.add('show');
48
+
49
+ // 实时验证 JSON
50
+ document.getElementById('jsonEditor').addEventListener('input', validateJSON);
51
+ }
52
+
53
+ function validateJSON() {
54
+ const editor = document.getElementById('jsonEditor');
55
+ const errorDiv = document.getElementById('jsonError');
56
+ try {
57
+ JSON.parse(editor.value);
58
+ errorDiv.classList.remove('show');
59
+ errorDiv.textContent = '';
60
+ return true;
61
+ } catch (e) {
62
+ errorDiv.classList.add('show');
63
+ errorDiv.textContent = '❌ JSON 格式错误: ' + e.message;
64
+ return false;
65
+ }
66
+ }
67
+
68
+ function closeModal() {
69
+ document.getElementById('jsonModal').classList.remove('show');
70
+ document.getElementById('jsonEditor').removeEventListener('input', validateJSON);
71
+ }
72
+
73
+ async function saveConfig() {
74
+ if (!validateJSON()) {
75
+ alert('JSON 格式错误,请修正后再保存');
76
+ return;
77
+ }
78
+
79
+ const newJson = document.getElementById('jsonEditor').value;
80
+ const originalJson = JSON.stringify(currentConfig, null, 2);
81
+
82
+ if (newJson === originalJson) {
83
+ closeModal();
84
+ return;
85
+ }
86
+
87
+ try {
88
+ const data = JSON.parse(newJson);
89
+ const response = await fetch(`/${window.ADMIN_PATH}/accounts-config`, {
90
+ method: 'PUT',
91
+ headers: {'Content-Type': 'application/json'},
92
+ body: JSON.stringify(data)
93
+ });
94
+
95
+ await handleApiResponse(response);
96
+ closeModal();
97
+ refreshPage();
98
+ } catch (error) {
99
+ console.error('保存失败:', error);
100
+ alert('更新失败: ' + error.message);
101
+ }
102
+ }
103
+
104
+ async function deleteAccount(accountId) {
105
+ if (!confirm(`确定删除账户 $${accountId}?`)) return;
106
+
107
+ try {
108
+ const response = await fetch(`/${window.ADMIN_PATH}/accounts/${accountId}`, {
109
+ method: 'DELETE'
110
+ });
111
+
112
+ await handleApiResponse(response);
113
+ refreshPage();
114
+ } catch (error) {
115
+ console.error('删除失败:', error);
116
+ alert('删除失败: ' + error.message);
117
+ }
118
+ }
119
+
120
+ async function disableAccount(accountId) {
121
+ try {
122
+ const response = await fetch(`/${window.ADMIN_PATH}/accounts/${accountId}/disable`, {
123
+ method: 'PUT'
124
+ });
125
+
126
+ await handleApiResponse(response);
127
+ refreshPage();
128
+ } catch (error) {
129
+ console.error('禁用失败:', error);
130
+ alert('禁用失败: ' + error.message);
131
+ }
132
+ }
133
+
134
+ async function enableAccount(accountId) {
135
+ try {
136
+ const response = await fetch(`/${window.ADMIN_PATH}/accounts/${accountId}/enable`, {
137
+ method: 'PUT'
138
+ });
139
+
140
+ await handleApiResponse(response);
141
+ refreshPage();
142
+ } catch (error) {
143
+ console.error('启用失败:', error);
144
+ alert('启用失败: ' + error.message);
145
+ }
146
+ }
147
+
148
+ // 批量上传相关函数
149
+ async function handleFileUpload(event) {
150
+ const files = event.target.files;
151
+ if (!files.length) return;
152
+
153
+ let newAccounts = [];
154
+ for (const file of files) {
155
+ try {
156
+ const text = await file.text();
157
+ const data = JSON.parse(text);
158
+ if (Array.isArray(data)) {
159
+ newAccounts.push(...data);
160
+ } else {
161
+ newAccounts.push(data);
162
+ }
163
+ } catch (e) {
164
+ alert(`文件 $${file.name} 解析失败: $${e.message}`);
165
+ event.target.value = '';
166
+ return;
167
+ }
168
+ }
169
+
170
+ if (!newAccounts.length) {
171
+ alert('未找到有效账户数据');
172
+ event.target.value = '';
173
+ return;
174
+ }
175
+
176
+ try {
177
+ // 获取现有配置
178
+ const configResp = await fetch(`/${window.ADMIN_PATH}/accounts-config`);
179
+ const configData = await handleApiResponse(configResp);
180
+ const existing = configData.accounts || [];
181
+
182
+ // 构建ID到索引的映射
183
+ const idToIndex = new Map();
184
+ existing.forEach((acc, idx) => {
185
+ if (acc.id) idToIndex.set(acc.id, idx);
186
+ });
187
+
188
+ // 合并:相同ID覆盖,新ID追加
189
+ let added = 0;
190
+ let updated = 0;
191
+ for (const acc of newAccounts) {
192
+ if (!acc.secure_c_ses || !acc.csesidx || !acc.config_id) continue;
193
+ const accId = acc.id || `account_${existing.length + added + 1}`;
194
+ acc.id = accId;
195
+
196
+ if (idToIndex.has(accId)) {
197
+ // 覆盖已存在的账户
198
+ existing[idToIndex.get(accId)] = acc;
199
+ updated++;
200
+ } else {
201
+ // 追加新账户
202
+ existing.push(acc);
203
+ idToIndex.set(accId, existing.length - 1);
204
+ added++;
205
+ }
206
+ }
207
+
208
+ if (added === 0 && updated === 0) {
209
+ alert('没有有效账户可导入');
210
+ event.target.value = '';
211
+ return;
212
+ }
213
+
214
+ // 保存合并后的配置
215
+ const response = await fetch(`/${window.ADMIN_PATH}/accounts-config`, {
216
+ method: 'PUT',
217
+ headers: {'Content-Type': 'application/json'},
218
+ body: JSON.stringify(existing)
219
+ });
220
+
221
+ await handleApiResponse(response);
222
+ event.target.value = '';
223
+ refreshPage();
224
+ } catch (error) {
225
+ console.error('导入失败:', error);
226
+ alert('导入失败: ' + error.message);
227
+ event.target.value = '';
228
+ }
229
+ }
230
+
231
+ // 点击模态框外部关闭
232
+ document.getElementById('jsonModal').addEventListener('click', function(e) {
233
+ if (e.target === this) {
234
+ closeModal();
235
+ }
236
+ });
237
+
238
+ // ========== 系统设置相关函数 ==========
239
+ async function loadSettings() {
240
+ try {
241
+ const response = await fetch(`/${window.ADMIN_PATH}/settings`);
242
+ const settings = await handleApiResponse(response);
243
+
244
+ // 基础配置
245
+ document.getElementById('setting-api-key').value = settings.basic?.api_key || '';
246
+ document.getElementById('setting-base-url').value = settings.basic?.base_url || '';
247
+ document.getElementById('setting-proxy').value = settings.basic?.proxy || '';
248
+
249
+ // 图片生成配置
250
+ document.getElementById('setting-image-enabled').checked = settings.image_generation?.enabled ?? true;
251
+ const supportedModels = settings.image_generation?.supported_models || [];
252
+ document.querySelectorAll('#setting-image-models input[type="checkbox"]').forEach(cb => {
253
+ cb.checked = supportedModels.includes(cb.value);
254
+ });
255
+
256
+ // 重试策略配置
257
+ document.getElementById('setting-max-new-session').value = settings.retry?.max_new_session_tries || 5;
258
+ document.getElementById('setting-max-retries').value = settings.retry?.max_request_retries || 3;
259
+ document.getElementById('setting-max-switch').value = settings.retry?.max_account_switch_tries || 5;
260
+ document.getElementById('setting-failure-threshold').value = settings.retry?.account_failure_threshold || 3;
261
+ document.getElementById('setting-cooldown').value = settings.retry?.rate_limit_cooldown_seconds || 600;
262
+ document.getElementById('setting-cache-ttl').value = settings.retry?.session_cache_ttl_seconds || 3600;
263
+
264
+ // 公开展示配置
265
+ document.getElementById('setting-logo-url').value = settings.public_display?.logo_url || '';
266
+ document.getElementById('setting-chat-url').value = settings.public_display?.chat_url || '';
267
+ document.getElementById('setting-session-hours').value = settings.session?.expire_hours || 24;
268
+ } catch (error) {
269
+ console.error('加载设置失败:', error);
270
+ alert('加载设置失败: ' + error.message);
271
+ }
272
+ }
273
+
274
+ async function saveSettings() {
275
+ try {
276
+ // 收集图片生成支持的模型
277
+ const supportedModels = [];
278
+ document.querySelectorAll('#setting-image-models input[type="checkbox"]:checked').forEach(cb => {
279
+ supportedModels.push(cb.value);
280
+ });
281
+
282
+ const settings = {
283
+ basic: {
284
+ api_key: document.getElementById('setting-api-key').value,
285
+ base_url: document.getElementById('setting-base-url').value,
286
+ proxy: document.getElementById('setting-proxy').value
287
+ },
288
+ image_generation: {
289
+ enabled: document.getElementById('setting-image-enabled').checked,
290
+ supported_models: supportedModels
291
+ },
292
+ retry: {
293
+ max_new_session_tries: parseInt(document.getElementById('setting-max-new-session').value) || 5,
294
+ max_request_retries: parseInt(document.getElementById('setting-max-retries').value) || 3,
295
+ max_account_switch_tries: parseInt(document.getElementById('setting-max-switch').value) || 5,
296
+ account_failure_threshold: parseInt(document.getElementById('setting-failure-threshold').value) || 3,
297
+ rate_limit_cooldown_seconds: parseInt(document.getElementById('setting-cooldown').value) || 600,
298
+ session_cache_ttl_seconds: parseInt(document.getElementById('setting-cache-ttl').value) || 3600
299
+ },
300
+ public_display: {
301
+ logo_url: document.getElementById('setting-logo-url').value,
302
+ chat_url: document.getElementById('setting-chat-url').value
303
+ },
304
+ session: {
305
+ expire_hours: parseInt(document.getElementById('setting-session-hours').value) || 24
306
+ }
307
+ };
308
+
309
+ const response = await fetch(`/${window.ADMIN_PATH}/settings`, {
310
+ method: 'PUT',
311
+ headers: {'Content-Type': 'application/json'},
312
+ body: JSON.stringify(settings)
313
+ });
314
+
315
+ await handleApiResponse(response);
316
+
317
+ // 直接刷新页面,不显示弹窗
318
+ window.location.reload();
319
+ } catch (error) {
320
+ console.error('保存设置失败:', error);
321
+ alert('保存设置失败: ' + error.message);
322
+ }
323
+ }
324
+
325
+ // 页面加载时自动加载设置
326
+ document.addEventListener('DOMContentLoaded', function() {
327
+ loadSettings();
328
+ });
static/js/api.js ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // API 请求工具函数
2
+
3
+ // 全局配置(由页面初始化)
4
+ window.ADMIN_PATH = window.ADMIN_PATH || 'admin';
5
+
6
+ // 构建 API 路径
7
+ function getApiPath(path) {
8
+ // 如果路径已经包含 admin_path,直接返回
9
+ if (path.startsWith(`/${window.ADMIN_PATH}`)) {
10
+ return path;
11
+ }
12
+ // 否则添加前缀
13
+ return `/${window.ADMIN_PATH}${path}`;
14
+ }
15
+
16
+ // 统一的 API 请求函数
17
+ async function apiRequest(url, options = {}) {
18
+ try {
19
+ const response = await fetch(url, options);
20
+ if (!response.ok) {
21
+ const errorText = await response.text();
22
+ let errorMsg;
23
+ try {
24
+ const errorJson = JSON.parse(errorText);
25
+ errorMsg = errorJson.detail || errorJson.message || errorText;
26
+ } catch {
27
+ errorMsg = errorText;
28
+ }
29
+ throw new Error(`HTTP ${response.status}: ${errorMsg}`);
30
+ }
31
+ return await response.json();
32
+ } catch (error) {
33
+ console.error('API请求失败:', error);
34
+ throw error;
35
+ }
36
+ }
37
+
38
+ // 导出函数(如果使用模块化)
39
+ if (typeof module !== 'undefined' && module.exports) {
40
+ module.exports = { getApiPath, apiRequest };
41
+ }