adapt to new api and bearer token auth

This commit is contained in:
blumia committed 2026-04-27 17:52:00 +08:00
1 parent 9f77975766
commit 3f834ebd3d
6 files changed
+181 -248

No files matched your search

+29 -67
View File
@@ -1,82 +1,50 @@
import * as vscode from 'vscode';
import { StorageService } from './storageService';
const LOGIN_URL = 'https://ai.getdeepin.org/login/form';
const QUOTA_URL = 'https://ai.getdeepin.org/api/me/quota';
const DEFAULT_BASE_URL = 'https://ai.getdeepin.org/';
function getBaseUrl(): string {
const config = vscode.workspace.getConfiguration('getdeepin-quota');
const url = config.get<string>('baseUrl', DEFAULT_BASE_URL);
return url.endsWith('/') ? url : url + '/';
}
export class AuthService {
private cookies: string = '';
private token: string = '';
private storageService: StorageService;
constructor(storageService: StorageService) {
this.storageService = storageService;
}
async login(username: string, password: string): Promise<boolean> {
try {
const body = new URLSearchParams({
next_path: '/',
username,
password,
remember_me: 'on'
});
const response = await fetch(LOGIN_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: body.toString(),
redirect: 'manual'
});
const setCookie = response.headers.get('set-cookie');
if (setCookie) {
this.cookies = this.parseCookies(setCookie);
await this.storageService.storeCredentials(username, password);
return true;
}
return false;
} catch (error) {
console.error('Login failed:', error);
return false;
}
async setToken(token: string): Promise<void> {
this.token = token;
await this.storageService.storeToken(token);
}
async autoLogin(): Promise<boolean> {
const credentials = await this.storageService.getCredentials();
if (!credentials) {
return false;
async loadToken(): Promise<boolean> {
if (this.token) {
return true;
}
return this.login(credentials.username, credentials.password);
const stored = await this.storageService.getToken();
if (stored) {
this.token = stored;
return true;
}
return false;
}
async logout(): Promise<void> {
this.cookies = '';
await this.storageService.deleteCredentials();
this.token = '';
await this.storageService.deleteToken();
}
isLoggedIn(): boolean {
return this.cookies.length > 0;
return this.token.length > 0;
}
getCookies(): string {
return this.cookies;
}
private parseCookies(setCookie: string): string {
const cookies: string[] = [];
const parts = setCookie.split(',');
for (const part of parts) {
const cookie = part.split(';')[0].trim();
if (cookie && cookie.includes('=')) {
cookies.push(cookie);
}
}
return cookies.join('; ');
getToken(): string {
return this.token;
}
}
@@ -89,24 +57,18 @@ export class QuotaService {
async fetchQuota(): Promise<Response | null> {
if (!this.authService.isLoggedIn()) {
const loggedIn = await this.authService.autoLogin();
if (!loggedIn) {
return null;
}
return null;
}
try {
const response = await fetch(QUOTA_URL, {
const response = await fetch(`${getBaseUrl()}api/me/quota`, {
headers: {
'Cookie': this.authService.getCookies()
'Authorization': `Bearer ${this.authService.getToken()}`
}
});
if (response.status === 401 || response.status === 403) {
const loggedIn = await this.authService.autoLogin();
if (loggedIn) {
return this.fetchQuota();
}
await this.authService.logout();
return null;
}
+26 -32
View File
@@ -30,8 +30,8 @@ export async function activate(context: vscode.ExtensionContext) {
);
context.subscriptions.push(statusBar);
const autoLoggedIn = await authService.autoLogin();
if (autoLoggedIn) {
const hasToken = await authService.loadToken();
if (hasToken) {
await refreshQuota();
} else {
statusBar.updateNotLoggedIn();
@@ -39,48 +39,42 @@ export async function activate(context: vscode.ExtensionContext) {
}
async function loginCommand(): Promise<void> {
const username = await vscode.window.showInputBox({
prompt: '请输入用户名',
placeHolder: '用户名'
});
if (!username) {
return;
}
const password = await vscode.window.showInputBox({
prompt: '请输入密码',
const token = await vscode.window.showInputBox({
prompt: '请输入 Bearer Token',
placeHolder: '在 https://ai.getdeepin.org/me 生成 Token',
password: true
});
if (!password) {
if (!token) {
return;
}
await vscode.window.withProgress(
{
location: vscode.ProgressLocation.Notification,
title: '正在登录...',
cancellable: false
},
async () => {
const success = await authService.login(username, password);
if (success) {
vscode.window.showInformationMessage('登录成功');
await refreshQuota();
} else {
vscode.window.showErrorMessage('登录失败,请检查用户名和密码');
statusBar.updateNotLoggedIn();
}
}
);
await authService.setToken(token);
const response = await quotaService.fetchQuota();
if (!response) {
vscode.window.showErrorMessage('Token 无效或已过期,请检查后重试');
await authService.logout();
statusBar.updateNotLoggedIn();
return;
}
try {
const data = await response.json() as QuotaResponse;
currentQuota = parseQuotaResponse(data);
statusBar.updateWithQuota(currentQuota);
vscode.window.showInformationMessage('Token 验证成功');
} catch {
vscode.window.showErrorMessage('解析用量数据失败');
statusBar.updateWithError();
}
}
async function logoutCommand(): Promise<void> {
await authService.logout();
currentQuota = null;
statusBar.updateNotLoggedIn();
vscode.window.showInformationMessage('已登出');
vscode.window.showInformationMessage('已移除 Token');
}
async function refreshQuota(): Promise<void> {
+101 -91
View File
@@ -18,20 +18,20 @@ export class StatusBarManager {
}
updateNotLoggedIn(): void {
this.statusBarItem.text = '$(cloud) 未登录';
this.statusBarItem.tooltip = new vscode.MarkdownString('**点击登录 GetDeepin AI**');
this.statusBarItem.text = '$(cloud) 未设置Token';
this.statusBarItem.tooltip = new vscode.MarkdownString('**点击设置 GetDeepin AI Token**');
}
updateWithError(): void {
this.statusBarItem.text = '$(cloud) 获取失败';
this.statusBarItem.tooltip = new vscode.MarkdownString('**获取数据失败**\n\n点击重试或重新登录');
this.statusBarItem.tooltip = new vscode.MarkdownString('**获取数据失败**\n\n点击重试或重新设置 Token');
}
updateWithQuota(data: QuotaDisplay): void {
const domesticPercent = Math.round(data.domestic.daily.percent);
const globalPercent = Math.round(data.global.monthly.percent);
const domesticUsed = (100 - data.domestic.remainingDailyPercent).toFixed(0);
const globalUsed = (100 - data.global.remainingMonthlyPercent).toFixed(0);
this.statusBarItem.text = `$(cloud) 国内 ${domesticPercent}% | 国外 ${globalPercent}%`;
this.statusBarItem.text = `$(cloud) 国内 ${domesticUsed}% | 国外 ${globalUsed}%`;
this.statusBarItem.tooltip = this.generateTooltipMarkdown(data);
}
@@ -39,10 +39,10 @@ export class StatusBarManager {
const md = new vscode.MarkdownString();
md.supportHtml = true;
const formatNumber = (n: number) => n.toLocaleString('zh-CN');
const formatPercent = (n: number) => n.toFixed(1);
const getProgressBar = (percent: number) => {
const filled = Math.round(percent / 5);
const formatTokens = (n: number) => n.toLocaleString('zh-CN');
const getProgressBar = (usedPercent: number) => {
const filled = Math.round(usedPercent / 5);
const empty = 20 - filled;
return '█'.repeat(filled) + '░'.repeat(empty);
};
@@ -52,23 +52,28 @@ export class StatusBarManager {
md.appendMarkdown(`${data.user.email}\n\n`);
md.appendMarkdown('---\n\n');
const domesticDailyWarning = data.domestic.daily.percent > 80 ? '⚠️ ' : '';
md.appendMarkdown(`#### ${domesticDailyWarning}${data.domestic.label} (日额度)\n\n`);
md.appendMarkdown(`\`${getProgressBar(data.domestic.daily.percent)}\` \`${formatPercent(data.domestic.daily.percent)}%\`\n\n`);
md.appendMarkdown(`已用 **${formatNumber(data.domestic.daily.used)}** / ${formatNumber(data.domestic.daily.total)}\n\n`);
if (data.domestic.hasMonthlyLimit) {
md.appendMarkdown(`月额度: ${formatPercent(data.domestic.monthly.percent)}% (${formatNumber(data.domestic.monthly.used)} / ${formatNumber(data.domestic.monthly.total)})\n\n`);
}
const domesticDailyUsed = 100 - data.domestic.remainingDailyPercent;
const domesticDailyWarning = domesticDailyUsed > 80 ? '⚠️ ' : '';
md.appendMarkdown(`#### ${domesticDailyWarning}${data.domestic.label}\n\n`);
md.appendMarkdown(`日额度: \`${getProgressBar(domesticDailyUsed)}\` 已用 \`${formatPercent(domesticDailyUsed)}%\`\n\n`);
const domesticMonthlyUsed = 100 - data.domestic.remainingMonthlyPercent;
md.appendMarkdown(`月额度: \`${getProgressBar(domesticMonthlyUsed)}\` 已用 \`${formatPercent(domesticMonthlyUsed)}%\`\n\n`);
md.appendMarkdown(`累计消耗: ${formatTokens(data.domestic.totalTokens)} tokens\n\n`);
md.appendMarkdown(`支持模型: ${data.domestic.models.map(m => `\`${m}\``).join(' ')}\n\n`);
const globalWarning = data.global.monthly.percent > 80 ? '⚠️ ' : '';
const globalMonthlyUsed = 100 - data.global.remainingMonthlyPercent;
const globalWarning = globalMonthlyUsed > 80 ? '⚠️ ' : '';
md.appendMarkdown(`#### ${globalWarning}${data.global.label}\n\n`);
md.appendMarkdown(`\`${getProgressBar(data.global.monthly.percent)}\` \`${formatPercent(data.global.monthly.percent)}%\`\n\n`);
md.appendMarkdown(`已用 **${formatNumber(data.global.monthly.used)}** / ${formatNumber(data.global.monthly.total)}\n\n`);
if (data.global.hasDailyLimit && data.global.remainingDailyPercent !== null) {
const globalDailyUsed = 100 - data.global.remainingDailyPercent;
md.appendMarkdown(`日额度: \`${getProgressBar(globalDailyUsed)}\` 已用 \`${formatPercent(globalDailyUsed)}%\`\n\n`);
}
md.appendMarkdown(`月额度: \`${getProgressBar(globalMonthlyUsed)}\` 已用 \`${formatPercent(globalMonthlyUsed)}%\`\n\n`);
md.appendMarkdown(`累计消耗: ${formatTokens(data.global.totalTokens)} tokens\n\n`);
md.appendMarkdown(`支持模型: ${data.global.models.map(m => `\`${m}\``).join(' ')}\n\n`);
md.appendMarkdown('---\n\n');
md.appendMarkdown('*点击查看更多操作*');
md.appendMarkdown('*点击查看详情*');
return md;
}
@@ -89,8 +94,8 @@ export class StatusBarManager {
private showLoginPrompt(): void {
vscode.window.showQuickPick(
[{ label: '$(sign-in) 登录', id: 'login' }],
{ placeHolder: '请先登录 GetDeepin AI' }
[{ label: '$(key) 设置 Token', id: 'login' }],
{ placeHolder: '请先设置 GetDeepin AI Token' }
).then(selection => {
if ((selection as any)?.id === 'login') {
vscode.commands.executeCommand('getdeepin-quota.login');
@@ -102,7 +107,7 @@ export class StatusBarManager {
vscode.window.showQuickPick(
[
{ label: '$(refresh) 重试', id: 'refresh' },
{ label: '$(sign-in) 重新登录', id: 'login' }
{ label: '$(key) 重新设置 Token', id: 'login' }
],
{ placeHolder: '获取用量数据失败' }
).then(selection => {
@@ -147,9 +152,57 @@ export class StatusBarManager {
}
private generatePanelHtml(data: QuotaDisplay): string {
const formatNumber = (n: number) => n.toLocaleString('zh-CN');
const formatTokens = (n: number) => n.toLocaleString('zh-CN');
const formatPercent = (n: number) => n.toFixed(1);
const renderQuotaSection = (
label: string,
remainingDailyPercent: number | null,
remainingMonthlyPercent: number,
hasDailyLimit: boolean,
totalTokens: number,
models: string[]
) => {
const dailyUsed = remainingDailyPercent !== null ? 100 - remainingDailyPercent : null;
const monthlyUsed = 100 - remainingMonthlyPercent;
let html = `
<div class="quota-section">
<h2>${label}</h2>`;
if (hasDailyLimit && dailyUsed !== null) {
html += `
<div class="quota-row">
<span class="quota-label">日额度</span>
<span class="quota-percent ${dailyUsed > 80 ? 'warning' : ''}">${formatPercent(dailyUsed)}%</span>
<span class="quota-details">已使用</span>
</div>
<div class="progress-container">
<div class="progress-bar ${dailyUsed > 80 ? 'progress-warning' : 'progress-ok'}" style="width: ${Math.min(dailyUsed, 100)}%;"></div>
</div>`;
}
html += `
<div class="quota-row">
<span class="quota-label">月额度</span>
<span class="quota-percent ${monthlyUsed > 80 ? 'warning' : ''}">${formatPercent(monthlyUsed)}%</span>
<span class="quota-details">已使用</span>
</div>
<div class="progress-container">
<div class="progress-bar ${monthlyUsed > 80 ? 'progress-warning' : 'progress-ok'}" style="width: ${Math.min(monthlyUsed, 100)}%;"></div>
</div>
<div class="quota-row">
<span class="quota-label">累计消耗</span>
<span class="quota-details">${formatTokens(totalTokens)} tokens</span>
</div>
<div class="models-list">
${models.map(m => `<span class="model-tag">${m}</span>`).join('')}
</div>
</div>`;
return html;
};
return `
<!DOCTYPE html>
<html>
@@ -255,59 +308,23 @@ export class StatusBarManager {
</div>
</div>
<div class="quota-section">
<h2>${data.domestic.label}</h2>
${data.domestic.hasDailyLimit ? `
<div class="quota-row">
<span class="quota-label">日额度</span>
<span class="quota-percent ${data.domestic.daily.percent > 80 ? 'warning' : ''}">${formatPercent(data.domestic.daily.percent)}%</span>
<span class="quota-details">已用 ${formatNumber(data.domestic.daily.used)} / ${formatNumber(data.domestic.daily.total)}</span>
</div>
<div class="progress-container">
<div class="progress-bar ${data.domestic.daily.percent > 80 ? 'progress-warning' : 'progress-ok'}" style="width: ${Math.min(data.domestic.daily.percent, 100)}%;"></div>
</div>
` : ''}
${data.domestic.hasMonthlyLimit ? `
<div class="quota-row">
<span class="quota-label">月额度</span>
<span class="quota-percent ${data.domestic.monthly.percent > 80 ? 'warning' : ''}">${formatPercent(data.domestic.monthly.percent)}%</span>
<span class="quota-details">已用 ${formatNumber(data.domestic.monthly.used)} / ${formatNumber(data.domestic.monthly.total)}</span>
</div>
<div class="progress-container">
<div class="progress-bar ${data.domestic.monthly.percent > 80 ? 'progress-warning' : 'progress-ok'}" style="width: ${Math.min(data.domestic.monthly.percent, 100)}%;"></div>
</div>
` : ''}
<div class="models-list">
${data.domestic.models.map(m => `<span class="model-tag">${m}</span>`).join('')}
</div>
</div>
${renderQuotaSection(
data.domestic.label,
data.domestic.remainingDailyPercent,
data.domestic.remainingMonthlyPercent,
data.domestic.hasDailyLimit,
data.domestic.totalTokens,
data.domestic.models
)}
<div class="quota-section">
<h2>${data.global.label}</h2>
${data.global.hasDailyLimit ? `
<div class="quota-row">
<span class="quota-label">日额度</span>
<span class="quota-percent ${data.global.daily.percent > 80 ? 'warning' : ''}">${formatPercent(data.global.daily.percent)}%</span>
<span class="quota-details">已用 ${formatNumber(data.global.daily.used)} / ${formatNumber(data.global.daily.total)}</span>
</div>
<div class="progress-container">
<div class="progress-bar ${data.global.daily.percent > 80 ? 'progress-warning' : 'progress-ok'}" style="width: ${Math.min(data.global.daily.percent, 100)}%;"></div>
</div>
` : ''}
${data.global.hasMonthlyLimit ? `
<div class="quota-row">
<span class="quota-label">月额度</span>
<span class="quota-percent ${data.global.monthly.percent > 80 ? 'warning' : ''}">${formatPercent(data.global.monthly.percent)}%</span>
<span class="quota-details">已用 ${formatNumber(data.global.monthly.used)} / ${formatNumber(data.global.monthly.total)}</span>
</div>
<div class="progress-container">
<div class="progress-bar ${data.global.monthly.percent > 80 ? 'progress-warning' : 'progress-ok'}" style="width: ${Math.min(data.global.monthly.percent, 100)}%;"></div>
</div>
` : ''}
<div class="models-list">
${data.global.models.map(m => `<span class="model-tag">${m}</span>`).join('')}
</div>
</div>
${renderQuotaSection(
data.global.label,
data.global.remainingDailyPercent,
data.global.remainingMonthlyPercent,
data.global.hasDailyLimit,
data.global.totalTokens,
data.global.models
)}
<div class="actions">
<button class="refresh-btn" onclick="refresh()">刷新数据</button>
@@ -333,30 +350,23 @@ export function parseQuotaResponse(response: QuotaResponse): QuotaDisplay {
const domestic = response.groups.find(g => g.key === 'domestic')!;
const global = response.groups.find(g => g.key === 'global')!;
const parseQuota = (usedStr: string, totalStr: string) => {
const used = parseFloat(usedStr) || 0;
const total = parseFloat(totalStr) || 1;
const percent = total > 0 ? (used / total) * 100 : 0;
return { used, total, percent };
};
return {
user: response.user,
domestic: {
label: domestic.label,
models: domestic.models,
hasDailyLimit: domestic.has_daily_limit,
hasMonthlyLimit: domestic.has_monthly_limit,
daily: parseQuota(domestic.usage.daily_amount, domestic.effective_daily_amount),
monthly: parseQuota(domestic.usage.month_amount, domestic.effective_monthly_amount)
hasDailyLimit: domestic.remaining_daily_percent !== null,
remainingDailyPercent: domestic.remaining_daily_percent ?? 100,
remainingMonthlyPercent: domestic.remaining_monthly_percent,
totalTokens: domestic.usage.total_tokens
},
global: {
label: global.label,
models: global.models,
hasDailyLimit: global.has_daily_limit,
hasMonthlyLimit: global.has_monthly_limit,
daily: parseQuota(global.usage.daily_amount, global.effective_daily_amount),
monthly: parseQuota(global.usage.month_amount, global.effective_monthly_amount)
hasDailyLimit: global.remaining_daily_percent !== null,
remainingDailyPercent: global.remaining_daily_percent,
remainingMonthlyPercent: global.remaining_monthly_percent,
totalTokens: global.usage.total_tokens
}
};
}
+6 -15
View File
@@ -1,6 +1,6 @@
import * as vscode from 'vscode';
const SECRET_KEY = 'getdeepin-quota.credentials';
const SECRET_KEY = 'getdeepin-quota.token';
export class StorageService {
private secrets: vscode.SecretStorage;
@@ -9,24 +9,15 @@ export class StorageService {
this.secrets = context.secrets;
}
async storeCredentials(username: string, password: string): Promise<void> {
const credentials = JSON.stringify({ username, password });
await this.secrets.store(SECRET_KEY, credentials);
async storeToken(token: string): Promise<void> {
await this.secrets.store(SECRET_KEY, token);
}
async getCredentials(): Promise<{ username: string; password: string } | undefined> {
const credentials = await this.secrets.get(SECRET_KEY);
if (!credentials) {
return undefined;
}
try {
return JSON.parse(credentials);
} catch {
return undefined;
}
async getToken(): Promise<string | undefined> {
return await this.secrets.get(SECRET_KEY);
}
async deleteCredentials(): Promise<void> {
async deleteToken(): Promise<void> {
await this.secrets.delete(SECRET_KEY);
}
}
+8 -42
View File
@@ -6,10 +6,6 @@ export interface User {
export interface Usage {
total_tokens: number;
daily_amount: string;
month_amount: string;
daily_amount_available: boolean;
month_amount_available: boolean;
unpriced_models: string[];
}
@@ -17,17 +13,8 @@ export interface Group {
key: 'domestic' | 'global';
label: string;
models: string[];
default_daily_amount: string;
effective_daily_amount: string;
effective_monthly_amount: string;
monthly_limit_amount: string;
has_daily_limit: boolean;
has_monthly_limit: boolean;
remaining_daily_amount: string;
remaining_monthly_amount: string;
remaining_daily_ratio: number | null;
remaining_monthly_ratio: number;
remaining_ratio: number | null;
remaining_daily_percent: number | null;
remaining_monthly_percent: number;
usage: Usage;
}
@@ -36,43 +23,22 @@ export interface QuotaResponse {
groups: Group[];
}
export interface Credentials {
username: string;
password: string;
}
export interface QuotaDisplay {
user: User;
domestic: {
label: string;
models: string[];
hasDailyLimit: boolean;
hasMonthlyLimit: boolean;
daily: {
used: number;
total: number;
percent: number;
};
monthly: {
used: number;
total: number;
percent: number;
};
remainingDailyPercent: number;
remainingMonthlyPercent: number;
totalTokens: number;
};
global: {
label: string;
models: string[];
hasDailyLimit: boolean;
hasMonthlyLimit: boolean;
daily: {
used: number;
total: number;
percent: number;
};
monthly: {
used: number;
total: number;
percent: number;
};
remainingDailyPercent: number | null;
remainingMonthlyPercent: number;
totalTokens: number;
};
}