File size: 39,144 Bytes
7ee9dd5 3d1bdb6 7ee9dd5 3d1bdb6 7ee9dd5 3d1bdb6 7ee9dd5 3d1bdb6 7ee9dd5 3d1bdb6 7ee9dd5 3d1bdb6 7ee9dd5 3d1bdb6 7ee9dd5 f5bdd3c 7ee9dd5 3d1bdb6 7ee9dd5 f5bdd3c 7ee9dd5 3d1bdb6 7ee9dd5 3d1bdb6 7ee9dd5 84a61e6 7ee9dd5 84a61e6 7ee9dd5 3d1bdb6 7ee9dd5 3d1bdb6 7ee9dd5 3d1bdb6 7ee9dd5 3d1bdb6 7ee9dd5 3d1bdb6 7ee9dd5 3d1bdb6 7ee9dd5 3d1bdb6 7ee9dd5 f5bdd3c 7ee9dd5 3d1bdb6 7ee9dd5 3d1bdb6 7ee9dd5 3d1bdb6 7ee9dd5 3d1bdb6 7ee9dd5 f5bdd3c 7ee9dd5 f5bdd3c 7ee9dd5 f5bdd3c 7ee9dd5 3d1bdb6 7ee9dd5 3d1bdb6 7ee9dd5 872c437 7ee9dd5 98bb76b 7ee9dd5 98bb76b 7ee9dd5 98bb76b 7ee9dd5 | 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 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 | const crypto = require('crypto');
const { prisma } = require('./db');
const { decrypt } = require('./crypto');
const { sendModelChangeNotification } = require('./notifier');
const { performCheckIn, shouldCheckIn, shouldCheckModels } = require('./checkin');
const { siteFetch } = require('./site-http');
// 辅助函数:获取嵌套对象的值
function getNestedValue(obj, path) {
return path.split('.').reduce((current, key) => {
return current && current[key] !== undefined ? current[key] : undefined;
}, obj);
}
function normalizeModels(response) {
if (!response) return [];
const arr = Array.isArray(response.data) ? response.data : Array.isArray(response) ? response : [];
const list = arr.map((m) => {
// 处理字符串类型的模型ID(newapi/Veloare返回字符串数组)
if (typeof m === 'string') {
return {
id: m,
object: 'model',
owned_by: 'unknown',
created: Date.now() / 1000
};
}
// 处理对象类型的模型
return {
id: m.id || m.model || m,
object: m.object || 'model',
owned_by: m.owned_by || m.ownedBy || 'unknown',
permission: m.permission,
created: m.created || Date.now() / 1000,
root: m.root,
parent: m.parent,
...('type' in m ? { type: m.type } : {}),
};
});
list.sort((a, b) => String(a.id || '').localeCompare(String(b.id || '')));
return list;
}
function hashModels(models) {
const json = JSON.stringify(models);
return crypto.createHash('sha256').update(json).digest('hex');
}
function computeDiff(prevList, nextList) {
const prevMap = new Map(prevList.map((m) => [m.id, m]));
const nextMap = new Map(nextList.map((m) => [m.id, m]));
const added = [];
const removed = [];
// 只检测模型ID的新增和删除,不关注属性变化
for (const [id, m] of nextMap) {
if (!prevMap.has(id)) added.push(m);
}
for (const [id, m] of prevMap) {
if (!nextMap.has(id)) removed.push(m);
}
return { added, removed, changed: [] };
}
// Newapi/Veloera API:获取模型列表
async function fetchModelsNewapi(baseUrl, apiKey, userId, apiType, fastify, site) {
const url = new URL('api/user/models', baseUrl.endsWith('/') ? baseUrl : baseUrl + '/');
const ac = new AbortController();
const timeout = setTimeout(() => ac.abort(), 15000);
const startTime = Date.now();
const userHeader = apiType === 'newapi' ? 'new-api-user' : 'veloera-user';
try {
console.log(`[NEWAPI-REQ] GET ${url}`);
const res = await siteFetch(site, url, {
method: 'GET',
headers: {
'Authorization': `Bearer ${apiKey}`,
[userHeader]: userId,
'Content-Type': 'application/json',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Accept': 'application/json'
},
signal: ac.signal
});
const responseTime = Date.now() - startTime;
const rawText = await res.text();
console.log(`[NEWAPI-RES] Status: ${res.status}`);
console.log(`[NEWAPI-RES] Body: ${rawText.substring(0, 500)}...`);
if (!res.ok) {
throw new Error(`HTTP ${res.status}: ${rawText}`);
}
const json = JSON.parse(rawText);
if (!json.success || !Array.isArray(json.data)) {
throw new Error('Invalid response format');
}
// 转换为OpenAI格式
// Newapi/Veloera返回的是字符串数组,不是对象数组
const models = json.data.map(m => {
if (typeof m === 'string') {
return {
id: m,
object: 'model',
owned_by: apiType === 'newapi' ? 'new-api' : 'veloera',
created: Date.now() / 1000
};
}
return {
id: m.id || m.model || m,
object: 'model',
owned_by: m.owned_by || (apiType === 'newapi' ? 'new-api' : 'veloera'),
created: Date.now() / 1000
};
});
return {
models,
rawResponse: rawText,
statusCode: res.status,
responseTime,
errorMessage: null
};
} catch (error) {
const responseTime = Date.now() - startTime;
console.log(`[NEWAPI-ERR] ${error.message}`);
throw {
error,
rawResponse: null,
statusCode: null,
responseTime,
errorMessage: error.message
};
} finally {
clearTimeout(timeout);
}
}
// Newapi/Veloera API:获取用户信息(billing)
async function fetchUserInfoNewapi(baseUrl, apiKey, userId, apiType, fastify, site) {
const url = new URL('api/user/self', baseUrl.endsWith('/') ? baseUrl : baseUrl + '/');
const ac = new AbortController();
const timeout = setTimeout(() => ac.abort(), 10000);
const userHeader = apiType === 'newapi' ? 'new-api-user' : 'veloera-user';
try {
console.log(`[NEWAPI-REQ] GET ${url}`);
const res = await siteFetch(site, url, {
method: 'GET',
headers: {
'Authorization': `Bearer ${apiKey}`,
[userHeader]: userId,
'Content-Type': 'application/json',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Accept': 'application/json'
},
signal: ac.signal
});
const rawText = await res.text();
console.log(`[NEWAPI-RES] Status: ${res.status}`);
console.log(`[NEWAPI-RES] Body: ${rawText}`);
if (!res.ok) {
throw new Error(`HTTP ${res.status}: ${rawText}`);
}
const data = JSON.parse(rawText);
if (!data.success || !data.data) {
throw new Error('Invalid user info response');
}
const userData = data.data;
// 根据API类型设置不同的转换比例
let conversionRatio;
if (apiType === 'newapi') {
conversionRatio = 500000; // Newapi: 500000 = $1
} else if (apiType === 'veloera') {
conversionRatio = 500000; // Veloera: 500000 = $1 (修正后)
} else {
conversionRatio = 500000; // 默认值
}
console.log(`[QUOTA-CONVERSION] API类型: ${apiType}, 转换比例: ${conversionRatio}:1`);
console.log(`[QUOTA-CONVERSION] 原始quota: ${userData.quota || 0}, 原始used_quota: ${userData.used_quota || 0}`);
const quotaInDollars = (userData.quota || 0) / conversionRatio;
const usedQuotaInDollars = (userData.used_quota || 0) / conversionRatio;
console.log(`[QUOTA-CONVERSION] 转换后quota: $${quotaInDollars.toFixed(6)}, 转换后used_quota: $${usedQuotaInDollars.toFixed(6)}`);
const totalQuotaInDollars = quotaInDollars + usedQuotaInDollars; // 总额度 = 当前余额 + 已使用
console.log(`[QUOTA-CONVERSION] 当前余额: $${quotaInDollars.toFixed(6)}, 已使用: $${usedQuotaInDollars.toFixed(6)}, 总额度: $${totalQuotaInDollars.toFixed(6)}`);
return {
quota: totalQuotaInDollars, // 返回总额度
usedQuota: usedQuotaInDollars, // 返回已使用额度
status: userData.status
};
} catch (error) {
console.log(`[NEWAPI-ERR] User info: ${error.message}`);
throw error;
} finally {
clearTimeout(timeout);
}
}
// DoneHub API:获取模型列表
async function fetchModelsDonehub(baseUrl, apiKey, fastify, site) {
const url = new URL('api/available_model', baseUrl.endsWith('/') ? baseUrl : baseUrl + '/');
const ac = new AbortController();
const timeout = setTimeout(() => ac.abort(), 15000);
const startTime = Date.now();
try {
console.log(`[DONEHUB-REQ] GET ${url}`);
const res = await siteFetch(site, url, {
method: 'GET',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Accept': 'application/json'
},
signal: ac.signal
});
const responseTime = Date.now() - startTime;
const rawText = await res.text();
console.log(`[DONEHUB-RES] Status: ${res.status}`);
console.log(`[DONEHUB-RES] Body: ${rawText.substring(0, 500)}...`);
if (!res.ok) {
throw new Error(`HTTP ${res.status}: ${rawText}`);
}
const json = JSON.parse(rawText);
if (!json.data) {
throw new Error('Invalid response format');
}
// 提取模型名称
const models = Object.keys(json.data).map(modelId => ({
id: modelId,
object: 'model',
owned_by: json.data[modelId].owned_by || 'unknown',
created: Date.now() / 1000
}));
return {
models,
rawResponse: rawText,
statusCode: res.status,
responseTime,
errorMessage: null
};
} catch (error) {
const responseTime = Date.now() - startTime;
console.log(`[DONEHUB-ERR] ${error.message}`);
throw {
error,
rawResponse: null,
statusCode: null,
responseTime,
errorMessage: error.message
};
} finally {
clearTimeout(timeout);
}
}
// VOAPI API:获取用户信息(billing)
async function fetchUserInfoVoapi(baseUrl, apiKey, fastify, site) {
const url = new URL('api/user/info', baseUrl.endsWith('/') ? baseUrl : baseUrl + '/');
const ac = new AbortController();
const timeout = setTimeout(() => ac.abort(), 10000);
try {
console.log(`[VOAPI-REQ] GET ${url}`);
const res = await siteFetch(site, url, {
method: 'GET',
headers: {
'Authorization': apiKey, // VOAPI直接使用API key
'Content-Type': 'application/json',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Accept': 'application/json'
},
signal: ac.signal
});
const rawText = await res.text();
console.log(`[VOAPI-RES] Status: ${res.status}`);
console.log(`[VOAPI-RES] Body: ${rawText}`);
if (!res.ok) {
throw new Error(`HTTP ${res.status}: ${rawText}`);
}
const data = JSON.parse(rawText);
if (data.code !== 0 || !data.data) {
throw new Error('Invalid user info response');
}
const userData = data.data;
// VOAPI: bindBalance + basicBalance = 总余额, usedBindBalance + usedBasicBalance = 已使用
const totalBalance = parseFloat(userData.bindBalance || 0) + parseFloat(userData.basicBalance || 0);
const totalUsed = parseFloat(userData.usedBindBalance || 0) + parseFloat(userData.usedBasicBalance || 0);
console.log(`[VOAPI-QUOTA] 总余额: $${totalBalance.toFixed(6)}, 已使用: $${totalUsed.toFixed(6)}`);
return {
quota: totalBalance,
usedQuota: totalUsed,
status: userData.ban ? 'banned' : 'active'
};
} catch (error) {
console.log(`[VOAPI-ERR] User info: ${error.message}`);
throw error;
} finally {
clearTimeout(timeout);
}
}
// DoneHub API:获取用户信息(billing)
async function fetchUserInfoDonehub(baseUrl, apiKey, fastify, site) {
const url = new URL('api/user/self', baseUrl.endsWith('/') ? baseUrl : baseUrl + '/');
const ac = new AbortController();
const timeout = setTimeout(() => ac.abort(), 10000);
try {
console.log(`[DONEHUB-REQ] GET ${url}`);
const res = await siteFetch(site, url, {
method: 'GET',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Accept': 'application/json'
},
signal: ac.signal
});
const rawText = await res.text();
console.log(`[DONEHUB-RES] Status: ${res.status}`);
console.log(`[DONEHUB-RES] Body: ${rawText}`);
if (!res.ok) {
throw new Error(`HTTP ${res.status}: ${rawText}`);
}
const data = JSON.parse(rawText);
if (!data.success || !data.data) {
throw new Error('Invalid user info response');
}
const userData = data.data;
// DoneHub: 500000 = $1 (可配置)
const conversionRatio = 500000; // DoneHub的转换比例
const quotaInDollars = (userData.quota || 0) / conversionRatio;
const usedQuotaInDollars = (userData.used_quota || 0) / conversionRatio;
console.log(`[DONEHUB-QUOTA-CONVERSION] 转换后quota: $${quotaInDollars.toFixed(6)}, 转换后used_quota: $${usedQuotaInDollars.toFixed(6)}`);
const totalQuotaInDollars = quotaInDollars + usedQuotaInDollars; // 总额度 = 当前余额 + 已使用
console.log(`[DONEHUB-QUOTA-CONVERSION] 当前余额: $${quotaInDollars.toFixed(6)}, 已使用: $${usedQuotaInDollars.toFixed(6)}, 总额度: $${totalQuotaInDollars.toFixed(6)}`);
return {
quota: totalQuotaInDollars, // 返回总额度
usedQuota: usedQuotaInDollars, // 返回已使用额度
status: userData.status
};
} catch (error) {
console.log(`[DONEHUB-ERR] User info: ${error.message}`);
throw error;
} finally {
clearTimeout(timeout);
}
}
// 获取billing订阅额度信息
async function fetchBillingSubscription(baseUrl, apiKey, fastify, site) {
const url = new URL('v1/dashboard/billing/subscription', baseUrl.endsWith('/') ? baseUrl : baseUrl + '/');
const ac = new AbortController();
const timeout = setTimeout(() => ac.abort(), 10000);
try {
console.log(`[BILLING-REQ] GET ${url}`);
const res = await siteFetch(site, url, {
method: 'GET',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'Accept': 'application/json, text/plain, */*',
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
'Cache-Control': 'no-cache',
'Pragma': 'no-cache'
},
signal: ac.signal
});
const rawText = await res.text();
console.log(`[BILLING-RES] Status: ${res.status}`);
console.log(`[BILLING-RES] Body: ${rawText}`);
if (!res.ok) {
throw new Error(`HTTP ${res.status}: ${rawText}`);
}
const data = JSON.parse(rawText);
return data.system_hard_limit_usd || null;
} catch (error) {
console.log(`[BILLING-ERR] Subscription: ${error.message}`);
fastify?.log?.warn({ msg: 'Failed to fetch billing subscription', error: error.message });
throw error; // 抛出错误而不是返回null
} finally {
clearTimeout(timeout);
}
}
// 获取自定义billing信息
async function fetchCustomBilling(site, fastify) {
if (!site.billingUrl) {
throw new Error('No custom billing URL configured');
}
const ac = new AbortController();
const timeout = setTimeout(() => ac.abort(), 10000);
try {
console.log(`[CUSTOM-BILLING-REQ] GET ${site.billingUrl}`);
// 准备认证头
const headers = {
'Content-Type': 'application/json',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Accept': 'application/json'
};
if (site.billingAuthValue) {
const authValue = decrypt(site.billingAuthValue);
if (site.billingAuthType === 'token') {
headers['Authorization'] = authValue.startsWith('Bearer ') ? authValue : `Bearer ${authValue}`;
} else if (site.billingAuthType === 'cookie') {
headers['Cookie'] = authValue;
}
}
const res = await siteFetch(site, site.billingUrl, {
method: 'GET',
headers,
signal: ac.signal
});
const rawText = await res.text();
console.log(`[CUSTOM-BILLING-RES] Status: ${res.status}`);
console.log(`[CUSTOM-BILLING-RES] Body: ${rawText}`);
if (!res.ok) {
throw new Error(`HTTP ${res.status}: ${rawText}`);
}
const data = JSON.parse(rawText);
// 尝试从响应中提取billing信息
let billingLimit = null;
let billingUsage = null;
// 使用自定义字段映射(如果配置了)
if (site.billingLimitField && site.billingUsageField) {
// 支持嵌套字段,如 "data.balance"
const limitValue = getNestedValue(data, site.billingLimitField);
const usageValue = getNestedValue(data, site.billingUsageField);
if (limitValue !== undefined) billingLimit = parseFloat(limitValue);
if (usageValue !== undefined) billingUsage = parseFloat(usageValue);
console.log(`[CUSTOM-BILLING] 使用自定义字段映射: ${site.billingLimitField}=${limitValue}, ${site.billingUsageField}=${usageValue}`);
} else {
// 使用默认的字段名匹配
// 常见的字段名
if (data.limit !== undefined) billingLimit = parseFloat(data.limit);
if (data.usage !== undefined) billingUsage = parseFloat(data.usage);
if (data.quota !== undefined) billingLimit = parseFloat(data.quota);
if (data.used !== undefined) billingUsage = parseFloat(data.used);
if (data.balance !== undefined) billingLimit = parseFloat(data.balance);
if (data.consumed !== undefined) billingUsage = parseFloat(data.consumed);
// OpenAI格式
if (data.system_hard_limit_usd !== undefined) billingLimit = parseFloat(data.system_hard_limit_usd);
if (data.total_usage !== undefined) billingUsage = parseFloat(data.total_usage) * 0.01;
}
return {
billingLimit,
billingUsage,
rawResponse: rawText
};
} catch (error) {
console.log(`[CUSTOM-BILLING-ERR] ${error.message}`);
fastify?.log?.warn({ msg: 'Failed to fetch custom billing', error: error.message });
throw error;
} finally {
clearTimeout(timeout);
}
}
// 获取billing使用量信息
async function fetchBillingUsage(baseUrl, apiKey, fastify, site) {
const url = new URL('v1/dashboard/billing/usage', baseUrl.endsWith('/') ? baseUrl : baseUrl + '/');
const ac = new AbortController();
const timeout = setTimeout(() => ac.abort(), 10000);
try {
console.log(`[BILLING-REQ] GET ${url}`);
const res = await siteFetch(site, url, {
method: 'GET',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'Accept': 'application/json, text/plain, */*',
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
'Cache-Control': 'no-cache',
'Pragma': 'no-cache'
},
signal: ac.signal
});
const rawText = await res.text();
console.log(`[BILLING-RES] Status: ${res.status}`);
console.log(`[BILLING-RES] Body: ${rawText}`);
if (!res.ok) {
throw new Error(`HTTP ${res.status}: ${rawText}`);
}
const data = JSON.parse(rawText);
// total_usage 单位为 0.01 美元,需要乘以 0.01
return data.total_usage ? (data.total_usage * 0.01) : null;
} catch (error) {
console.log(`[BILLING-ERR] Usage: ${error.message}`);
fastify?.log?.warn({ msg: 'Failed to fetch billing usage', error: error.message });
throw error; // 抛出错误而不是返回null
} finally {
clearTimeout(timeout);
}
}
async function fetchModels(baseUrl, apiKey, fastify, site) {
// 使用相对路径(不带前导/)以保留 baseUrl 中的路径部分(如 /api)
const url = new URL('v1/models', baseUrl.endsWith('/') ? baseUrl : baseUrl + '/');
const ac = new AbortController();
const timeout = setTimeout(() => ac.abort(), 15000);
const startTime = Date.now();
try {
// VERSION: v2.0-simplified (只用2个头,模仿Python)
fastify?.log?.info({ msg: 'Fetching with v2.0-simplified headers', url: url.toString() });
const res = await siteFetch(site, url, {
method: 'GET',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
},
signal: ac.signal
});
const responseTime = Date.now() - startTime;
const rawText = await res.text();
let json;
try {
json = JSON.parse(rawText);
} catch (e) {
throw new Error(`Invalid JSON response: ${rawText.substring(0, 200)}`);
}
if (!res.ok) {
throw new Error(`HTTP ${res.status}: ${rawText.substring(0, 200)}`);
}
const models = normalizeModels(json);
return {
models,
rawResponse: rawText,
statusCode: res.status,
responseTime,
errorMessage: null
};
} catch (error) {
const responseTime = Date.now() - startTime;
// 详细的错误日志
fastify?.log?.error({
msg: 'Fetch error details',
url: url.toString(),
errorName: error.name,
errorMessage: error.message,
errorStack: error.stack?.split('\n')[0],
responseTime
});
throw {
error,
rawResponse: null,
statusCode: null,
responseTime,
errorMessage: error.message
};
} finally {
clearTimeout(timeout);
}
}
async function fetchModelsVoapi(baseUrl, apiKey, fastify, site) {
const url = new URL('api/models', baseUrl.endsWith('/') ? baseUrl : baseUrl + '/');
const ac = new AbortController();
const timeout = setTimeout(() => ac.abort(), 15000);
const startTime = Date.now();
try {
fastify?.log?.info({ msg: 'Fetching VOAPI models with raw Authorization', url: url.toString() });
const res = await siteFetch(site, url, {
method: 'GET',
headers: {
'Authorization': apiKey,
'Content-Type': 'application/json',
'Accept': 'application/json, text/plain, */*'
},
signal: ac.signal
});
const responseTime = Date.now() - startTime;
const rawText = await res.text();
let json;
try {
json = JSON.parse(rawText);
} catch (e) {
throw new Error(`Invalid JSON response: ${rawText.substring(0, 200)}`);
}
if (!res.ok) {
throw new Error(`HTTP ${res.status}: ${rawText.substring(0, 200)}`);
}
if (json.code !== 0 || !json.data) {
throw new Error(json.msg || json.message || 'Invalid VOAPI models response');
}
const rawModels = Array.isArray(json.data.models)
? json.data.models
: Array.isArray(json.data)
? json.data
: [];
const models = rawModels.map((model) => {
const created = Number(model.created);
const createdAt = Number.isFinite(created)
? (created > 1e12 ? Math.floor(created / 1000) : created)
: Math.floor(Date.now() / 1000);
return {
id: model.idKey || model.model || model.id,
object: 'model',
owned_by: model.firmIdKey || model.firm || model.provider || 'voapi',
created: createdAt,
chargingType: model.chargingType,
inputPrice: model.inputPrice,
outputPrice: model.outputPrice,
singlePrice: model.singlePrice,
ac: Array.isArray(model.ac) ? model.ac : []
};
}).filter(model => model.id);
return {
models,
rawResponse: rawText,
statusCode: res.status,
responseTime,
errorMessage: null
};
} catch (error) {
const responseTime = Date.now() - startTime;
fastify?.log?.error({
msg: 'VOAPI fetch error details',
url: url.toString(),
errorName: error.name,
errorMessage: error.message,
errorStack: error.stack?.split('\n')[0],
responseTime
});
throw {
error,
rawResponse: null,
statusCode: null,
responseTime,
errorMessage: error.message
};
} finally {
clearTimeout(timeout);
}
}
async function checkSiteById(siteId, fastify, options = {}) {
const site = await prisma.site.findUnique({ where: { id: siteId } });
if (!site) throw new Error('Site not found');
return checkSite(site, fastify, options);
}
/**
* 判断是否为手动触发(立即检测、一键检测)
*/
function isManualTrigger(options = {}) {
return options.isManual === true;
}
async function checkSite(site, fastify, options = {}) {
const { skipNotification = false } = options;
const isManual = isManualTrigger(options);
const apiKey = decrypt(site.apiKeyEnc);
let fetchResult;
let models;
let rawResponse = null;
let errorMessage = null;
let statusCode = null;
let responseTime = null;
// 并行获取billing信息(不阻塞主检测流程)
let billingLimit = null;
let billingUsage = null;
let billingError = null;
// 签到相关变量
let checkInSuccess = null;
let checkInMessage = null;
let checkInQuota = null;
let checkInError = null;
console.log(`\n[CHECK] ========== 开始检测站点: ${site.name} (${site.apiType || 'other'}) ==========`);
console.log(`[CHECK] 触发方式: ${isManual ? '手动' : '定时'}, 模式: ${site.checkInMode || 'both'}`);
// 判断是否需要执行签到和模型检测
const needCheckIn = shouldCheckIn(site, isManual);
const needCheckModels = shouldCheckModels(site, isManual);
console.log(`[CHECK] 需要签到: ${needCheckIn}, 需要检测模型: ${needCheckModels}`);
// 执行签到(如果需要)
if (needCheckIn) {
console.log(`[CHECK] 开始执行签到...`);
try {
const checkInResult = await performCheckIn(site);
checkInSuccess = checkInResult.success;
checkInMessage = checkInResult.message;
checkInQuota = checkInResult.quota;
checkInError = checkInResult.error;
console.log(`[CHECK] 签到完成: ${checkInSuccess ? '成功' : '失败'} - ${checkInMessage}`);
} catch (error) {
console.error(`[CHECK] 签到异常:`, error);
checkInSuccess = false;
checkInError = error.message || '签到异常';
}
}
// 如果不需要检测模型,直接保存签到结果并返回
if (!needCheckModels) {
console.log(`[CHECK] 仅签到模式,跳过模型检测`);
const now = new Date();
await prisma.modelSnapshot.create({
data: {
siteId: site.id,
modelsJson: '[]',
hash: '',
fetchedAt: now,
rawResponse: null,
errorMessage: null,
statusCode: null,
responseTime: null,
billingLimit: null,
billingUsage: null,
billingError: null,
checkInSuccess,
checkInMessage,
checkInQuota,
checkInError
}
});
await prisma.site.update({
where: { id: site.id },
data: { lastCheckedAt: now }
});
return {
ok: true,
hasChanges: false,
diff: null,
siteName: site.name,
checkInOnly: true,
checkInResult: { checkInSuccess, checkInMessage, checkInQuota, checkInError }
};
}
// 检查是否为无限余额站点
if (site.unlimitedQuota) {
console.log(`[CHECK] 站点 ${site.name} 标记为无限余额,跳过billing检测`);
billingLimit = null; // 无限余额不设置限制
billingUsage = null; // 无限余额不检测使用量
billingError = null;
}
// 根据API类型选择对应的获取函数
let billingPromises;
let fetchModelsFunc;
if (site.apiType === 'newapi' || site.apiType === 'veloera') {
// Newapi/Veloera:使用userId进行鉴权
if (!site.userId) {
console.log(`[WARN] ${site.apiType} requires userId but it's not set`);
}
if (!site.unlimitedQuota) {
billingPromises = Promise.allSettled([
fetchUserInfoNewapi(site.baseUrl, apiKey, site.userId || '1', site.apiType, fastify, site)
]);
}
fetchModelsFunc = () => fetchModelsNewapi(site.baseUrl, apiKey, site.userId || '1', site.apiType, fastify, site);
} else if (site.apiType === 'donehub') {
// DoneHub:不需要userId
if (!site.unlimitedQuota) {
billingPromises = Promise.allSettled([
fetchUserInfoDonehub(site.baseUrl, apiKey, fastify, site)
]);
}
fetchModelsFunc = () => fetchModelsDonehub(site.baseUrl, apiKey, fastify, site);
} else if (site.apiType === 'voapi') {
// VOAPI:全部请求统一使用 apiKey 原样鉴权
if (!site.unlimitedQuota) {
billingPromises = Promise.allSettled([
fetchUserInfoVoapi(site.baseUrl, apiKey, fastify, site)
]);
}
fetchModelsFunc = () => fetchModelsVoapi(site.baseUrl, apiKey, fastify, site);
} else {
// Other: 使用原有的OpenAI兼容方式或自定义billing
if (!site.unlimitedQuota) {
if (site.billingUrl) {
// 使用自定义billing URL
billingPromises = Promise.allSettled([
fetchCustomBilling(site, fastify)
]);
} else {
// 使用默认的OpenAI兼容billing
billingPromises = Promise.allSettled([
fetchBillingSubscription(site.baseUrl, apiKey, fastify, site),
fetchBillingUsage(site.baseUrl, apiKey, fastify, site)
]);
}
}
fetchModelsFunc = () => fetchModels(site.baseUrl, apiKey, fastify, site);
}
try {
const [fetchResult] = await Promise.all([
fetchModelsFunc()
]);
// 等待billing结果(仅对非无限余额站点)
if (!site.unlimitedQuota && billingPromises) {
const billingResults = await billingPromises;
// 根据API类型处理billing结果
if (site.apiType === 'newapi' || site.apiType === 'veloera' || site.apiType === 'donehub' || site.apiType === 'voapi') {
// Newapi/Veloera/DoneHub返回 {quota, usedQuota, status}
if (billingResults[0].status === 'fulfilled') {
const userInfo = billingResults[0].value;
billingLimit = userInfo.quota;
billingUsage = userInfo.usedQuota;
} else {
billingError = billingResults[0].reason?.message || String(billingResults[0].reason);
}
} else {
// Other类型:可能是自定义billing或默认OpenAI兼容billing
if (site.billingUrl) {
// 自定义billing返回单个对象
if (billingResults[0].status === 'fulfilled') {
const customBilling = billingResults[0].value;
billingLimit = customBilling.billingLimit;
billingUsage = customBilling.billingUsage;
} else {
billingError = billingResults[0].reason?.message || String(billingResults[0].reason);
}
} else {
// 默认OpenAI兼容billing返回两个单独的值
billingLimit = billingResults[0].status === 'fulfilled' ? billingResults[0].value : null;
billingUsage = billingResults[1].status === 'fulfilled' ? billingResults[1].value : null;
const errors = [];
if (billingResults[0].status === 'rejected') errors.push(`Subscription: ${billingResults[0].reason?.message || billingResults[0].reason}`);
if (billingResults[1].status === 'rejected') errors.push(`Usage: ${billingResults[1].reason?.message || billingResults[1].reason}`);
if (errors.length > 0) billingError = errors.join('; ');
}
}
}
// 输出billing汇总结果
console.log(`[BILLING] ========== 站点: ${site.name} - 结果汇总 ==========`);
if (site.unlimitedQuota) {
console.log(`[BILLING] 无限余额站点,跳过billing检测`);
} else {
console.log(`[BILLING] 总额度: ${billingLimit !== null ? '$' + billingLimit.toFixed(2) : '获取失败'}`);
console.log(`[BILLING] 已使用: ${billingUsage !== null ? '$' + billingUsage.toFixed(2) : '获取失败'}`);
if (billingLimit !== null && billingUsage !== null) {
const remaining = billingLimit - billingUsage;
const percentage = ((billingLimit - billingUsage) / billingLimit * 100).toFixed(1);
console.log(`[BILLING] 剩余额度: $${remaining.toFixed(2)} (${percentage}%)`);
}
if (billingError) {
console.log(`[BILLING] 错误: ${billingError}`);
}
}
console.log(`[BILLING] ========================================\n`);
models = fetchResult.models;
rawResponse = fetchResult.rawResponse;
statusCode = fetchResult.statusCode;
responseTime = fetchResult.responseTime;
} catch (e) {
// 请求失败时创建错误快照用于调试,但不用于对比(有 errorMessage)
const now = new Date();
await prisma.modelSnapshot.create({
data: {
siteId: site.id,
modelsJson: '[]',
hash: '',
fetchedAt: now,
rawResponse: e.rawResponse,
errorMessage: e.errorMessage || e.error?.message || String(e),
statusCode: e.statusCode,
responseTime: e.responseTime,
billingLimit: null,
billingUsage: null,
billingError: null,
checkInSuccess,
checkInMessage,
checkInQuota,
checkInError
}
});
await prisma.site.update({
where: { id: site.id },
data: { lastCheckedAt: now }
});
fastify?.log?.warn({
siteId: site.id,
siteName: site.name,
err: e.errorMessage || e.error?.message,
statusCode: e.statusCode,
responseTime: e.responseTime
}, 'Fetch failed - error snapshot created for debugging');
throw e.error || e;
}
const hash = hashModels(models);
// 只查找成功的快照进行对比(errorMessage 为 null)
const lastSnap = await prisma.modelSnapshot.findFirst({
where: {
siteId: site.id,
errorMessage: null // 只取成功的快照
},
orderBy: { fetchedAt: 'desc' }
});
const now = new Date();
let diff = { added: [], removed: [], changed: [] };
let hasChanges = false;
let checkInChanged = false;
// 检测签到状态是否发生变化
console.log(`[CHECK-IN] ========== 签到状态检测 ==========`);
console.log(`[CHECK-IN] needCheckIn=${needCheckIn}`);
if (needCheckIn) {
console.log(`[CHECK-IN] 开始检测签到状态变化...`);
console.log(`[CHECK-IN] 当前签到结果: success=${checkInSuccess}, message=${checkInMessage}, error=${checkInError}`);
if (!lastSnap) {
// 首次检测:如果有签到结果,标记为变更
console.log(`[CHECK-IN] 首次检测,无历史快照`);
if (checkInSuccess !== null) {
checkInChanged = true;
console.log(`[CHECK-IN] ✅ 首次签到标记为变更: ${checkInSuccess ? '成功' : '失败'}`);
}
} else {
// 非首次检测:对比上次快照
const lastCheckInSuccess = lastSnap.checkInSuccess;
const lastCheckInError = lastSnap.checkInError;
console.log(`[CHECK-IN] 上次签到结果: success=${lastCheckInSuccess}, error=${lastCheckInError}`);
// 签到状态发生变化的情况:
// 1. 从无记录到有记录
// 2. 从成功变为失败,或从失败变为成功
// 3. 错误信息发生变化
if (lastCheckInSuccess === null && checkInSuccess !== null) {
checkInChanged = true;
console.log(`[CHECK-IN] ✅ 签到状态变化: 无记录 -> ${checkInSuccess ? '成功' : '失败'}`);
} else if (lastCheckInSuccess !== null && checkInSuccess !== null && lastCheckInSuccess !== checkInSuccess) {
checkInChanged = true;
console.log(`[CHECK-IN] ✅ 签到状态变化: ${lastCheckInSuccess ? '成功' : '失败'} -> ${checkInSuccess ? '成功' : '失败'}`);
} else if (checkInSuccess === false && lastCheckInError !== checkInError) {
checkInChanged = true;
console.log(`[CHECK-IN] ✅ 签到错误信息变化: "${lastCheckInError}" -> "${checkInError}"`);
} else {
console.log(`[CHECK-IN] ⭕ 签到状态无变化`);
}
}
console.log(`[CHECK-IN] 检测结果: checkInChanged=${checkInChanged}`);
} else {
console.log(`[CHECK-IN] 跳过签到变更检测 (needCheckIn=${needCheckIn})`);
}
// 每次检测都创建快照(不管是否有变更),这样"请求详情"能显示最新结果
const snap = await prisma.modelSnapshot.create({
data: {
siteId: site.id,
modelsJson: JSON.stringify(models),
hash,
fetchedAt: now,
rawResponse,
errorMessage: null,
statusCode,
responseTime,
billingLimit,
billingUsage,
billingError,
checkInSuccess,
checkInMessage,
checkInQuota,
checkInError
}
});
// 检查是否有变更
if (lastSnap && lastSnap.hash !== hash) {
let prev = [];
try { prev = JSON.parse(lastSnap.modelsJson) } catch (_) { prev = [] }
diff = computeDiff(Array.isArray(prev) ? prev : [], models);
hasChanges = diff.added.length > 0 || diff.removed.length > 0; // 只检测新增和删除
// 只有当有变更时才创建 diff 记录
if (hasChanges) {
await prisma.modelDiff.create({
data: {
siteId: site.id,
diffAt: now,
addedJson: JSON.stringify(diff.added),
removedJson: JSON.stringify(diff.removed),
changedJson: JSON.stringify(diff.changed),
snapshotFromId: lastSnap.id,
snapshotToId: snap.id,
},
});
}
} else if (!lastSnap) {
// 首次检测:不创建 diff 记录,也不发送通知
hasChanges = false;
fastify?.log?.info({ siteId: site.id, siteName: site.name, modelCount: models.length }, 'First check - snapshot created, no diff record');
}
// 发送邮件通知(只有当有实际变更时才发送)
if (hasChanges && !skipNotification) {
try {
console.log(`[EMAIL] 尝试发送邮件通知 - 站点: ${site.name}`);
console.log(`[EMAIL] 变化内容:`, {
added: diff.added?.length || 0,
removed: diff.removed?.length || 0
});
await sendModelChangeNotification(site.name, diff, fastify);
} catch (emailError) {
console.error(`[EMAIL] 邮件通知失败: ${site.name}`, emailError);
fastify?.log?.error(`邮件通知失败: ${site.name}`, emailError);
}
} else if (hasChanges && skipNotification) {
console.log(`[EMAIL] 跳过单站点邮件通知(将聚合发送)- 站点: ${site.name}`);
}
await prisma.site.update({ where: { id: site.id }, data: { lastCheckedAt: now } });
// 返回变更信息供聚合使用(包含签到结果)
// 只要执行了签到,就返回签到结果(用于邮件通知)
const hasCheckInResult = needCheckIn && checkInSuccess !== null;
console.log(`\n[CHECK] ========== 检测结果汇总 ==========`);
console.log(`[CHECK] 站点: ${site.name}`);
console.log(`[CHECK] 模型变更: ${hasChanges}`);
console.log(`[CHECK] 执行签到: ${needCheckIn}`);
console.log(`[CHECK] 有签到结果: ${hasCheckInResult}`);
if (hasCheckInResult) {
console.log(`[CHECK] 签到状态: ${checkInSuccess ? '成功' : '失败'}`);
console.log(`[CHECK] 签到消息: ${checkInMessage}`);
}
console.log(`[CHECK] 将发送通知: ${hasChanges || hasCheckInResult ? '是' : '否'}`);
console.log(`[CHECK] ======================================\n`);
return {
ok: true,
hasChanges,
diff: hasChanges ? diff : null,
siteName: site.name,
checkInChanged, // 保留用于日志
checkInResult: hasCheckInResult ? { checkInSuccess, checkInMessage, checkInQuota, checkInError } : null
};
}
module.exports = { normalizeModels, hashModels, computeDiff, fetchModels, checkSiteById, checkSite };
|