File size: 7,200 Bytes
ef8784d 99fc92f ef8784d 99fc92f ef8784d |
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 |
/**
* API密钥管理器 - 密钥创建模块
* 包含API密钥的添加功能
*/
// 添加API密钥
async function addApiKey() {
if (!this.newKey.platform || !this.newKey.key) {
this.errorMessage = '请填写所有必填字段。';
return;
}
// 如果名称为空,生成自动名称
if (!this.newKey.name.trim()) {
const date = new Date();
const dateStr = date.toLocaleDateString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
}).replace(/\//g, '-');
const timeStr = date.toLocaleTimeString('zh-CN', {
hour: '2-digit',
minute: '2-digit'
});
this.newKey.name = `${dateStr} ${timeStr}`;
}
// 保存当前选择的平台类型
localStorage.setItem('lastSelectedPlatform', this.newKey.platform);
this.isSubmitting = true;
this.errorMessage = '';
try {
// 处理输入文本:去除单引号、双引号、小括号、方括号、空格,然后分行
const lines = this.newKey.key
.split('\n')
.map(line => line.replace(/['"\(\)\[\]\s]/g, '')) // 去除单引号、双引号、小括号、方括号和空格
.filter(line => line.length > 0); // 过滤掉空行
// 从每一行中提取逗号分隔的非空元素,作为单独的key
let keysWithDuplicates = [];
for (const line of lines) {
const lineKeys = line.split(',')
.filter(item => item.length > 0); // 过滤掉空元素
// 将每个非空元素添加到数组
keysWithDuplicates.push(...lineKeys);
}
if (keysWithDuplicates.length === 0) {
this.errorMessage = '请输入至少一个有效的API密钥。';
this.isSubmitting = false;
return;
}
// 去除输入中重复的key(同一次提交中的重复)
const inputDuplicatesCount = keysWithDuplicates.length - new Set(keysWithDuplicates).size;
const keys = [...new Set(keysWithDuplicates)]; // 使用Set去重,得到唯一的keys数组
// 过滤掉已存在于同一平台的重复key
const currentPlatform = this.newKey.platform;
const existingKeys = this.apiKeys
.filter(apiKey => apiKey.platform === currentPlatform)
.map(apiKey => apiKey.key);
const uniqueKeys = keys.filter(key => !existingKeys.includes(key));
const duplicateCount = keys.length - uniqueKeys.length;
// 如果所有key都重复,显示错误消息并退出
if (uniqueKeys.length === 0) {
this.errorMessage = '所有输入的API密钥在当前平台中已存在。';
this.isSubmitting = false;
return;
}
// 准备批量添加的数据
const keysData = uniqueKeys.map(keyText => ({
platform: this.newKey.platform,
name: this.newKey.name,
key: keyText
}));
// 记录重复和唯一的key数量,用于显示通知
const skippedCount = duplicateCount;
const addedCount = uniqueKeys.length;
// 使用批量添加API一次性添加所有密钥
const response = await fetch('/api/keys/bulk-add', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ keys: keysData }),
});
const data = await response.json();
if (data.success) {
// 关闭模态框并重置表单
this.showAddModal = false;
this.newKey = {
platform: this.newKey.platform, // 保留平台选择
name: '',
key: ''
};
// 使用Toast风格的通知提示
const Toast = Swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 2500,
timerProgressBar: true,
didOpen: (toast) => {
toast.onmouseenter = Swal.stopTimer;
toast.onmouseleave = Swal.resumeTimer;
}
});
// 重新加载API密钥数据而不刷新页面
this.loadApiKeys();
// 为每个新添加的API密钥调用update API
if (data.keys && data.keys.length > 0) {
// 延迟200ms确保UI更新
setTimeout(() => {
data.keys.forEach(key => {
console.log(`正在请求更新API密钥: ${key.id}`);
fetch(`/api/keys/update/${key.id}`, {
method: 'POST'
}).then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
}).then(data => {
console.log(`API密钥 ${key.id} 更新成功:`, data);
// 更新成功后重新加载密钥列表
this.loadApiKeys();
}).catch(error => {
console.error(`自动更新API密钥 ${key.id} 时出错:`, error);
});
});
}, 200);
}
// 构建通知消息
let title = `已添加 ${addedCount} 个API密钥`;
// 根据不同情况显示通知
if (inputDuplicatesCount > 0 && skippedCount > 0) {
// 既有输入中的重复,也有数据库中的重复
title += `,跳过 ${inputDuplicatesCount} 个输入重复和 ${skippedCount} 个已存在密钥`;
} else if (inputDuplicatesCount > 0) {
// 只有输入中的重复
title += `,跳过 ${inputDuplicatesCount} 个输入重复密钥`;
} else if (skippedCount > 0) {
// 只有数据库中的重复
title += `,跳过 ${skippedCount} 个已存在密钥`;
}
Toast.fire({
icon: 'success',
title: title,
background: '#f0fdf4',
iconColor: '#16a34a'
});
} else {
// 处理批量添加失败
this.errorMessage = data.error || `添加操作失败: ${data.message || '未知错误'}`;
}
} catch (error) {
console.error('添加API密钥失败:', error);
this.errorMessage = '服务器错误,请重试。';
} finally {
this.isSubmitting = false;
}
}
|