pre / static /js /api-key-manager /api-key-creator.js
yangtb24's picture
Upload 61 files
99fc92f verified
/**
* 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;
}
}