commit 4d67f0c8f9d3a0e648886237ae95ee5e33d8b3cf Author: Wang Zichong Date: Wed Apr 22 15:28:45 2026 +0800 init commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5fe00fe --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +out +node_modules +.vscode-test/ +*.vsix diff --git a/.vscodeignore b/.vscodeignore new file mode 100644 index 0000000..dae4940 --- /dev/null +++ b/.vscodeignore @@ -0,0 +1,12 @@ +.vscode/** +.vscode-test/** +src/** +.gitignore +.yarnrc +vsc-extension-quickstart.md +**/tsconfig.json +**/.eslintrc.json +**/*.map +**/*.ts +!node_modules/** +PLAN.md diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..f8e9884 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,58 @@ +{ + "name": "getdeepin-quota", + "version": "0.0.1", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "getdeepin-quota", + "version": "0.0.1", + "devDependencies": { + "@types/node": "^20.10.0", + "@types/vscode": "^1.85.0", + "typescript": "^5.3.0" + }, + "engines": { + "vscode": "^1.85.0" + } + }, + "node_modules/@types/node": { + "version": "20.19.39", + "resolved": "https://registry.npmmirror.com/@types/node/-/node-20.19.39.tgz", + "integrity": "sha512-orrrD74MBUyK8jOAD/r0+lfa1I2MO6I+vAkmAWzMYbCcgrN4lCrmK52gRFQq/JRxfYPfonkr4b0jcY7Olqdqbw==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/@types/vscode": { + "version": "1.116.0", + "resolved": "https://registry.npmmirror.com/@types/vscode/-/vscode-1.116.0.tgz", + "integrity": "sha512-sYHp4MO6BqJ2PD7Hjt0hlIS3tMaYsVPJrd0RUjDJ8HtOYnyJIEej0bLSccM8rE77WrC+Xox/kdBwEFDO8MsxNA==", + "dev": true, + "license": "MIT" + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmmirror.com/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmmirror.com/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..cc8b1a4 --- /dev/null +++ b/package.json @@ -0,0 +1,44 @@ +{ + "name": "getdeepin-quota", + "displayName": "GetDeepin AI Quota", + "description": "显示大模型资源用量情况", + "version": "0.0.1", + "publisher": "getdeepin", + "engines": { + "vscode": "^1.85.0" + }, + "categories": [ + "Other" + ], + "activationEvents": [ + "onStartupFinished" + ], + "main": "./out/extension.js", + "contributes": { + "commands": [ + { + "command": "getdeepin-quota.login", + "title": "GetDeepin AI: 登录" + }, + { + "command": "getdeepin-quota.logout", + "title": "GetDeepin AI: 登出" + }, + { + "command": "getdeepin-quota.refresh", + "title": "GetDeepin AI: 刷新用量" + } + ] + }, + "scripts": { + "vscode:prepublish": "npm run compile", + "compile": "tsc -p ./", + "watch": "tsc -watch -p ./", + "lint": "eslint src --ext ts" + }, + "devDependencies": { + "@types/node": "^20.10.0", + "@types/vscode": "^1.85.0", + "typescript": "^5.3.0" + } +} diff --git a/src/authService.ts b/src/authService.ts new file mode 100644 index 0000000..1a53eab --- /dev/null +++ b/src/authService.ts @@ -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 { + 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 { + const credentials = await this.storageService.getCredentials(); + if (!credentials) { + return false; + } + return this.login(credentials.username, credentials.password); + } + + async logout(): Promise { + 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 { + 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; + } + } +} diff --git a/src/extension.ts b/src/extension.ts new file mode 100644 index 0000000..1061c89 --- /dev/null +++ b/src/extension.ts @@ -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 { + 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 { + await authService.logout(); + currentQuota = null; + statusBar.updateNotLoggedIn(); + vscode.window.showInformationMessage('已登出'); +} + +async function refreshQuota(): Promise { + 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() {} diff --git a/src/statusBar.ts b/src/statusBar.ts new file mode 100644 index 0000000..59b0e1f --- /dev/null +++ b/src/statusBar.ts @@ -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 + } + }; +} diff --git a/src/storageService.ts b/src/storageService.ts new file mode 100644 index 0000000..292450c --- /dev/null +++ b/src/storageService.ts @@ -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 { + 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 { + await this.secrets.delete(SECRET_KEY); + } +} diff --git a/src/types.ts b/src/types.ts new file mode 100644 index 0000000..73cb952 --- /dev/null +++ b/src/types.ts @@ -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; diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..81778eb --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "ES2022", + "lib": ["ES2022"], + "outDir": "out", + "rootDir": "src", + "sourceMap": true, + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "resolveJsonModule": true + }, + "exclude": ["node_modules", ".vscode-test"] +}