init commit

This commit is contained in:
blumia committed 2026-04-22 15:28:45 +08:00
commit 4d67f0c8f9
10 files changed
+611

No files matched your search

+123
View File
@@ -0,0 +1,123 @@
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';
export class AuthService {
private cookies: 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 autoLogin(): Promise<boolean> {
const credentials = await this.storageService.getCredentials();
if (!credentials) {
return false;
}
return this.login(credentials.username, credentials.password);
}
async logout(): Promise<void> {
this.cookies = '';
await this.storageService.deleteCredentials();
}
isLoggedIn(): boolean {
return this.cookies.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('; ');
}
}
export class QuotaService {
private authService: AuthService;
constructor(authService: AuthService) {
this.authService = authService;
}
async fetchQuota(): Promise<Response | null> {
if (!this.authService.isLoggedIn()) {
const loggedIn = await this.authService.autoLogin();
if (!loggedIn) {
return null;
}
}
try {
const response = await fetch(QUOTA_URL, {
headers: {
'Cookie': this.authService.getCookies()
}
});
if (response.status === 401 || response.status === 403) {
const loggedIn = await this.authService.autoLogin();
if (loggedIn) {
return this.fetchQuota();
}
return null;
}
if (!response.ok) {
return null;
}
return response;
} catch (error) {
console.error('Fetch quota failed:', error);
return null;
}
}
}
+104
View File
@@ -0,0 +1,104 @@
import * as vscode from 'vscode';
import { StorageService } from './storageService';
import { AuthService, QuotaService } from './authService';
import { StatusBarManager, parseQuotaResponse } from './statusBar';
import { QuotaResponse, QuotaDisplay } from './types';
let storageService: StorageService;
let authService: AuthService;
let quotaService: QuotaService;
let statusBar: StatusBarManager;
let currentQuota: QuotaDisplay | null = null;
export async function activate(context: vscode.ExtensionContext) {
storageService = new StorageService(context);
authService = new AuthService(storageService);
quotaService = new QuotaService(authService);
statusBar = new StatusBarManager(() => {
vscode.commands.executeCommand('getdeepin-quota.showPopup');
});
const autoLoggedIn = await authService.autoLogin();
if (autoLoggedIn) {
await refreshQuota();
} else {
statusBar.updateNotLoggedIn();
}
context.subscriptions.push(
vscode.commands.registerCommand('getdeepin-quota.login', loginCommand),
vscode.commands.registerCommand('getdeepin-quota.logout', logoutCommand),
vscode.commands.registerCommand('getdeepin-quota.refresh', refreshQuota),
vscode.commands.registerCommand('getdeepin-quota.showPopup', showPopup),
statusBar
);
}
async function loginCommand(): Promise<void> {
const username = await vscode.window.showInputBox({
prompt: '请输入用户名',
placeHolder: '用户名'
});
if (!username) {
return;
}
const password = await vscode.window.showInputBox({
prompt: '请输入密码',
password: true
});
if (!password) {
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();
}
}
);
}
async function logoutCommand(): Promise<void> {
await authService.logout();
currentQuota = null;
statusBar.updateNotLoggedIn();
vscode.window.showInformationMessage('已登出');
}
async function refreshQuota(): Promise<void> {
const response = await quotaService.fetchQuota();
if (!response) {
statusBar.updateWithError();
return;
}
try {
const data = await response.json() as QuotaResponse;
currentQuota = parseQuotaResponse(data);
statusBar.updateWithQuota(currentQuota);
} catch (error) {
console.error('Parse quota response failed:', error);
statusBar.updateWithError();
}
}
function showPopup(): void {
statusBar.showPopup(currentQuota, authService.isLoggedIn());
}
export function deactivate() {}
+174
View File
@@ -0,0 +1,174 @@
import * as vscode from 'vscode';
import { QuotaResponse, QuotaDisplay, QUOTA_LIMITS } from './types';
export class StatusBarManager {
private statusBarItem: vscode.StatusBarItem;
private onDidClick: () => void;
constructor(onDidClick: () => void) {
this.onDidClick = onDidClick;
this.statusBarItem = vscode.window.createStatusBarItem(
vscode.StatusBarAlignment.Right,
100
);
this.statusBarItem.command = 'getdeepin-quota.showPopup';
this.statusBarItem.text = '$(cloud) AI用量';
this.statusBarItem.show();
}
updateNotLoggedIn(): void {
this.statusBarItem.text = '$(cloud) 未登录';
this.statusBarItem.tooltip = new vscode.MarkdownString('**点击登录 GetDeepin AI**');
}
updateWithError(): void {
this.statusBarItem.text = '$(cloud) 获取失败';
this.statusBarItem.tooltip = new vscode.MarkdownString('**获取数据失败**\n\n点击重试或重新登录');
}
updateWithQuota(data: QuotaDisplay): void {
const domesticPercent = Math.round(data.domestic.percent);
const globalPercent = Math.round(data.global.percent);
this.statusBarItem.text = `$(cloud) 国内 ${domesticPercent}% | 国外 ${globalPercent}%`;
this.statusBarItem.tooltip = this.generateTooltipMarkdown(data);
}
private generateTooltipMarkdown(data: QuotaDisplay): vscode.MarkdownString {
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 empty = 20 - filled;
return '█'.repeat(filled) + '░'.repeat(empty);
};
md.appendMarkdown(`### AI 模型用量统计\n\n`);
md.appendMarkdown(`**${data.user.display_name}** (${data.user.job_id}) \n`);
md.appendMarkdown(`${data.user.email}\n\n`);
md.appendMarkdown('---\n\n');
const domesticWarning = data.domestic.percent > 80 ? '⚠️ ' : '';
md.appendMarkdown(`#### ${domesticWarning}国内模型用量\n\n`);
md.appendMarkdown(`\`${getProgressBar(data.domestic.percent)}\` \`${formatPercent(data.domestic.percent)}%\`\n\n`);
md.appendMarkdown(`已用 **${formatNumber(data.domestic.used)}** / ${formatNumber(data.domestic.total)}\n\n`);
md.appendMarkdown(`支持模型: ${data.domestic.models.map(m => `\`${m}\``).join(' ')}\n\n`);
const globalWarning = data.global.percent > 80 ? '⚠️ ' : '';
md.appendMarkdown(`#### ${globalWarning}国外模型用量\n\n`);
md.appendMarkdown(`\`${getProgressBar(data.global.percent)}\` \`${formatPercent(data.global.percent)}%\`\n\n`);
md.appendMarkdown(`已用 **${formatNumber(data.global.used)}** / ${formatNumber(data.global.total)}\n\n`);
md.appendMarkdown(`支持模型: ${data.global.models.map(m => `\`${m}\``).join(' ')}\n\n`);
md.appendMarkdown('---\n\n');
md.appendMarkdown('*点击查看更多操作*');
return md;
}
showPopup(data: QuotaDisplay | null, isLoggedIn: boolean): void {
if (!isLoggedIn) {
this.showLoginPrompt();
return;
}
if (!data) {
this.showErrorPrompt();
return;
}
this.showQuotaQuickPick(data);
}
private showLoginPrompt(): void {
vscode.window.showQuickPick(
[{ label: '$(sign-in) 登录', id: 'login' }],
{ placeHolder: '请先登录 GetDeepin AI' }
).then(selection => {
if (selection?.id === 'login') {
vscode.commands.executeCommand('getdeepin-quota.login');
}
});
}
private showErrorPrompt(): void {
vscode.window.showQuickPick(
[
{ label: '$(refresh) 重试', id: 'refresh' },
{ label: '$(sign-in) 重新登录', id: 'login' }
],
{ placeHolder: '获取用量数据失败' }
).then(selection => {
if (selection?.id === 'refresh') {
vscode.commands.executeCommand('getdeepin-quota.refresh');
} else if (selection?.id === 'login') {
vscode.commands.executeCommand('getdeepin-quota.login');
}
});
}
private showQuotaQuickPick(data: QuotaDisplay): void {
const formatNumber = (n: number) => n.toLocaleString('zh-CN');
const formatPercent = (n: number) => n.toFixed(1);
const items: vscode.QuickPickItem[] = [
{
label: `$(account) ${data.user.display_name} (${data.user.job_id})`,
description: data.user.email
},
{ label: '', kind: vscode.QuickPickItemKind.Separator },
{
label: `$(globe) 国内模型: ${formatPercent(data.domestic.percent)}%`,
description: `已用 ${formatNumber(data.domestic.used)} / ${formatNumber(data.domestic.total)}`,
detail: data.domestic.models.join(', ')
},
{
label: `$(world) 国外模型: ${formatPercent(data.global.percent)}%`,
description: `已用 ${formatNumber(data.global.used)} / ${formatNumber(data.global.total)}`,
detail: data.global.models.join(', ')
},
{ label: '', kind: vscode.QuickPickItemKind.Separator },
{ label: '$(refresh) 刷新', id: 'refresh' } as vscode.QuickPickItem & { id: string },
{ label: '$(sign-out) 登出', id: 'logout' } as vscode.QuickPickItem & { id: string }
];
vscode.window.showQuickPick(items, {
placeHolder: 'AI 模型用量详情'
}).then(selection => {
const item = selection as vscode.QuickPickItem & { id?: string };
if (item?.id === 'refresh') {
vscode.commands.executeCommand('getdeepin-quota.refresh');
} else if (item?.id === 'logout') {
vscode.commands.executeCommand('getdeepin-quota.logout');
}
});
}
dispose(): void {
this.statusBarItem.dispose();
}
}
export function parseQuotaResponse(response: QuotaResponse): QuotaDisplay {
const domestic = response.groups.find(g => g.key === 'domestic')!;
const global = response.groups.find(g => g.key === 'global')!;
return {
user: response.user,
domestic: {
used: QUOTA_LIMITS.domestic - domestic.remaining_tokens,
total: QUOTA_LIMITS.domestic,
percent: ((QUOTA_LIMITS.domestic - domestic.remaining_tokens) / QUOTA_LIMITS.domestic) * 100,
models: domestic.models
},
global: {
used: QUOTA_LIMITS.global - global.remaining_tokens,
total: QUOTA_LIMITS.global,
percent: ((QUOTA_LIMITS.global - global.remaining_tokens) / QUOTA_LIMITS.global) * 100,
models: global.models
}
};
}
+32
View File
@@ -0,0 +1,32 @@
import * as vscode from 'vscode';
const SECRET_KEY = 'getdeepin-quota.credentials';
export class StorageService {
private secrets: vscode.SecretStorage;
constructor(context: vscode.ExtensionContext) {
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 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 deleteCredentials(): Promise<void> {
await this.secrets.delete(SECRET_KEY);
}
}
+44
View File
@@ -0,0 +1,44 @@
export interface User {
job_id: string;
display_name: string;
email: string;
}
export interface Group {
key: 'domestic' | 'global';
label: string;
query_model: string;
models: string[];
remaining_tokens: number;
}
export interface QuotaResponse {
user: User;
groups: Group[];
}
export interface Credentials {
username: string;
password: string;
}
export interface QuotaDisplay {
user: User;
domestic: {
used: number;
total: number;
percent: number;
models: string[];
};
global: {
used: number;
total: number;
percent: number;
models: string[];
};
}
export const QUOTA_LIMITS = {
domestic: 30000000,
global: 10000000
} as const;