Files
TaskPool/web/src/api/index.ts
T

496 lines
17 KiB
TypeScript
Raw Normal View History

2026-01-13 18:18:50 +08:00
// 获取 base URL(从后端注入的全局变量)
const BASE_URL = (window as any).__BASE_URL__ || ''
const API_VERSION = (window as any).__API_VERSION__ || '/api/v1'
const API_BASE_URL = BASE_URL + API_VERSION
2025-12-20 09:30:16 +08:00
interface ApiResponse<T> {
code: number
msg: string
data: T
}
async function request<T>(url: string, options?: RequestInit): Promise<T> {
2026-01-13 18:18:50 +08:00
const res = await fetch(`${API_BASE_URL}${url}`, {
2025-12-20 09:30:16 +08:00
...options,
credentials: 'include', // 携带 Cookie
headers: {
'Content-Type': 'application/json',
...options?.headers
}
})
2026-02-07 21:44:09 +08:00
2025-12-20 09:30:16 +08:00
const json: ApiResponse<T> = await res.json()
2026-02-07 21:44:09 +08:00
2025-12-20 09:30:16 +08:00
if (json.code === 401) {
// 未登录或登录过期,跳转到登录页
2026-01-13 18:18:50 +08:00
window.location.href = BASE_URL + '/login'
2025-12-20 09:30:16 +08:00
throw new Error(json.msg || '请先登录')
}
2026-02-07 21:44:09 +08:00
2025-12-20 09:30:16 +08:00
if (json.code !== 200) {
throw new Error(json.msg || '请求失败')
}
2026-02-07 21:44:09 +08:00
2025-12-20 09:30:16 +08:00
return json.data
}
// 检查登录状态(不触发自动跳转)
export async function checkAuth(): Promise<boolean> {
try {
2026-01-13 18:18:50 +08:00
const res = await fetch(`${API_BASE_URL}/auth/me`, {
2025-12-20 09:30:16 +08:00
credentials: 'include',
headers: { 'Content-Type': 'application/json' }
})
const json: ApiResponse<{ username: string }> = await res.json()
return json.code === 200
} catch {
return false
}
}
export const api = {
auth: {
login: (data: { username: string; password: string }) =>
request<{ user: string }>('/auth/login', { method: 'POST', body: JSON.stringify(data) }),
logout: () => request('/auth/logout', { method: 'POST' }),
me: () => request<{ username: string }>('/auth/me'),
register: (data: { username: string; password: string; email: string }) =>
request('/auth/register', { method: 'POST', body: JSON.stringify(data) })
},
tasks: {
2026-02-27 09:02:00 +08:00
list: (params?: { page?: number; page_size?: number; name?: string; agent_id?: number; tags?: string; type?: string }) => {
2025-12-20 09:30:16 +08:00
const query = new URLSearchParams()
if (params?.page) query.set('page', String(params.page))
if (params?.page_size) query.set('page_size', String(params.page_size))
if (params?.name) query.set('name', params.name)
2026-02-26 20:29:20 +08:00
if (params?.tags) query.set('tags', params.tags)
2025-12-29 19:52:39 +08:00
if (params?.agent_id) query.set('agent_id', String(params.agent_id))
2026-02-27 09:02:00 +08:00
if (params?.type) query.set('type', params.type)
2025-12-20 09:30:16 +08:00
return request<TaskListResponse>(`/tasks?${query}`)
},
create: (data: Partial<Task>) => request<Task>('/tasks', { method: 'POST', body: JSON.stringify(data) }),
update: (id: number, data: Partial<Task>) => request<Task>(`/tasks/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
delete: (id: number) => request(`/tasks/${id}`, { method: 'DELETE' }),
2026-02-10 16:47:18 +08:00
execute: (id: number) => request<ExecutionResult>(`/execute/task/${id}`, { method: 'POST' }),
stop: (logID: number) => request(`/tasks/stop/${logID}`, { method: 'POST' })
2025-12-20 09:30:16 +08:00
},
scripts: {
list: () => request<Script[]>('/scripts'),
create: (data: Partial<Script>) => request<Script>('/scripts', { method: 'POST', body: JSON.stringify(data) }),
update: (id: number, data: Partial<Script>) => request<Script>(`/scripts/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
delete: (id: number) => request(`/scripts/${id}`, { method: 'DELETE' })
},
env: {
list: (params?: { page?: number; page_size?: number; name?: string }) => {
const query = new URLSearchParams()
if (params?.page) query.set('page', String(params.page))
if (params?.page_size) query.set('page_size', String(params.page_size))
if (params?.name) query.set('name', params.name)
return request<EnvListResponse>(`/env?${query}`)
},
2025-12-21 23:34:34 +08:00
all: () => request<EnvVar[]>('/env/all'),
2025-12-20 09:30:16 +08:00
create: (data: Partial<EnvVar>) => request<EnvVar>('/env', { method: 'POST', body: JSON.stringify(data) }),
update: (id: number, data: Partial<EnvVar>) => request<EnvVar>(`/env/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
delete: (id: number) => request(`/env/${id}`, { method: 'DELETE' })
},
execute: {
command: (command: string) => request('/execute/command', { method: 'POST', body: JSON.stringify({ command }) }),
results: () => request('/execute/results')
},
logs: {
2026-02-28 08:40:14 +08:00
list: (params?: { page?: number; page_size?: number; task_id?: number; task_name?: string; status?: string }) => {
2025-12-20 09:30:16 +08:00
const query = new URLSearchParams()
if (params?.page) query.set('page', String(params.page))
if (params?.page_size) query.set('page_size', String(params.page_size))
if (params?.task_id) query.set('task_id', String(params.task_id))
if (params?.task_name) query.set('task_name', params.task_name)
2026-02-28 08:40:14 +08:00
if (params?.status) query.set('status', params.status)
2025-12-20 09:30:16 +08:00
return request<LogListResponse>(`/logs?${query}`)
},
2026-02-07 21:44:09 +08:00
get: (id: number) => request<LogDetail>(`/logs/${id}`),
2026-02-27 09:02:00 +08:00
detail: (id: number) => request<LogDetail>(`/logs/${id}`),
delete: (id: number) => request(`/logs/${id}`, { method: 'DELETE' }),
clear: (taskId?: number) => request('/logs/clear', { method: 'POST', body: JSON.stringify({ task_id: taskId }) })
2025-12-20 09:30:16 +08:00
},
dashboard: {
2025-12-20 12:00:08 +08:00
stats: () => request<Stats>('/stats'),
2025-12-21 21:49:34 +08:00
sentence: () => request<{ sentence: string }>('/sentence'),
2025-12-25 20:28:20 +08:00
sendStats: (days?: number) => request<DailyStats[]>(`/sendstats${days ? `?days=${days}` : ''}`),
taskStats: (days?: number) => request<TaskStatsItem[]>(`/taskstats${days ? `?days=${days}` : ''}`)
2025-12-20 09:30:16 +08:00
},
settings: {
changePassword: (data: { old_password: string; new_password: string }) =>
request('/settings/password', { method: 'POST', body: JSON.stringify(data) }),
2025-12-20 12:00:08 +08:00
getSite: () => request<SiteSettings>('/settings/site'),
2025-12-25 21:46:06 +08:00
getPublicSite: () => request<{ title: string; subtitle: string; icon: string; demo_mode: boolean }>('/settings/public'),
2025-12-20 12:00:08 +08:00
updateSite: (data: SiteSettings) =>
request('/settings/site', { method: 'PUT', body: JSON.stringify(data) }),
2026-02-28 10:52:53 +08:00
generateApiToken: () => request<{ token: string }>('/settings/site/api-token/generate', { method: 'POST' }),
2025-12-22 16:05:07 +08:00
getScheduler: () => request<SchedulerSettings>('/settings/scheduler'),
updateScheduler: (data: SchedulerSettings) =>
request('/settings/scheduler', { method: 'PUT', body: JSON.stringify(data) }),
getPaths: () => request<{ scripts_dir: string }>('/settings/paths'),
2025-12-21 10:23:25 +08:00
getAbout: () => request<AboutInfo>('/settings/about'),
getLoginLogs: (params?: { page?: number; page_size?: number; username?: string }) => {
const query = new URLSearchParams()
if (params?.page) query.set('page', String(params.page))
if (params?.page_size) query.set('page_size', String(params.page_size))
if (params?.username) query.set('username', params.username)
2025-12-21 14:30:59 +08:00
return request<LoginLogListResponse>(`/settings/loginlogs?${query}`)
2025-12-22 11:10:46 +08:00
},
createBackup: () => request('/settings/backup', { method: 'POST' }),
getBackupStatus: () => request<{ has_backup: boolean; backup_time: string }>('/settings/backup/status'),
2026-01-13 18:18:50 +08:00
downloadBackup: () => `${API_BASE_URL}/settings/backup/download`,
2025-12-22 11:10:46 +08:00
restoreBackup: async (file: File) => {
const formData = new FormData()
formData.append('file', file)
2026-01-13 18:18:50 +08:00
const res = await fetch(`${API_BASE_URL}/settings/restore`, {
2025-12-22 11:10:46 +08:00
method: 'POST',
credentials: 'include',
body: formData
})
const json: ApiResponse<null> = await res.json()
if (json.code === 401) {
2026-01-13 18:18:50 +08:00
window.location.href = BASE_URL + '/login'
2025-12-22 11:10:46 +08:00
throw new Error('请先登录')
}
if (json.code !== 200) throw new Error(json.msg || '恢复失败')
2025-12-21 10:23:25 +08:00
}
2025-12-20 09:30:16 +08:00
},
files: {
tree: () => request<FileNode[]>('/files/tree'),
getContent: (path: string) => request<{ path: string; content: string }>(`/files/content?path=${encodeURIComponent(path)}`),
2026-02-09 18:28:14 +08:00
download: (path: string) => `${API_BASE_URL}/files/download?path=${encodeURIComponent(path)}`,
2025-12-20 09:30:16 +08:00
saveContent: (path: string, content: string) => request('/files/content', { method: 'POST', body: JSON.stringify({ path, content }) }),
create: (path: string, isDir: boolean) => request('/files/create', { method: 'POST', body: JSON.stringify({ path, isDir }) }),
delete: (path: string) => request('/files/delete', { method: 'POST', body: JSON.stringify({ path }) }),
rename: (oldPath: string, newPath: string) => request('/files/rename', { method: 'POST', body: JSON.stringify({ oldPath, newPath }) }),
2026-02-10 14:12:15 +08:00
move: (oldPath: string, newPath: string) => request('/files/move', { method: 'POST', body: JSON.stringify({ oldPath, newPath }) }),
2026-02-26 20:29:20 +08:00
copy: (sourcePath: string, targetPath: string) => request('/files/copy', { method: 'POST', body: JSON.stringify({ sourcePath, targetPath }) }),
2025-12-20 09:30:16 +08:00
uploadArchive: async (file: File, targetPath?: string) => {
const formData = new FormData()
formData.append('file', file)
if (targetPath) formData.append('path', targetPath)
2026-02-07 21:44:09 +08:00
2026-01-13 18:18:50 +08:00
const res = await fetch(`${API_BASE_URL}/files/upload`, {
2025-12-20 09:30:16 +08:00
method: 'POST',
credentials: 'include',
body: formData
})
const json: ApiResponse<null> = await res.json()
if (json.code === 401) {
2026-01-13 18:18:50 +08:00
window.location.href = BASE_URL + '/login'
2025-12-20 09:30:16 +08:00
throw new Error('请先登录')
}
if (json.code !== 200) throw new Error(json.msg || '上传失败')
},
uploadFiles: async (files: FileList, paths: string[], targetPath?: string) => {
const formData = new FormData()
for (let i = 0; i < files.length; i++) {
const file = files[i]
if (file) {
formData.append('files', file)
formData.append('paths', paths[i] || file.name)
}
}
if (targetPath) formData.append('path', targetPath)
2026-02-07 21:44:09 +08:00
2026-01-13 18:18:50 +08:00
const res = await fetch(`${API_BASE_URL}/files/uploadfiles`, {
2025-12-20 09:30:16 +08:00
method: 'POST',
credentials: 'include',
body: formData
})
const json: ApiResponse<null> = await res.json()
if (json.code === 401) {
2026-01-13 18:18:50 +08:00
window.location.href = BASE_URL + '/login'
2025-12-20 09:30:16 +08:00
throw new Error('请先登录')
}
if (json.code !== 200) throw new Error(json.msg || '上传失败')
}
2025-12-22 00:09:40 +08:00
},
2025-12-23 23:02:47 +08:00
deps: {
2026-02-13 17:27:55 +08:00
list: (params?: { language?: string; lang_version?: string }) => {
const query = new URLSearchParams()
if (params?.language) query.set('language', params.language)
if (params?.lang_version) query.set('lang_version', params.lang_version)
return request<Dependency[]>(`/deps?${query}`)
2025-12-23 23:02:47 +08:00
},
2026-02-13 17:27:55 +08:00
create: (data: { name: string; version?: string; language: string; lang_version?: string; remark?: string }) =>
2025-12-23 23:02:47 +08:00
request<Dependency>('/deps', { method: 'POST', body: JSON.stringify(data) }),
delete: (id: number) => request(`/deps/${id}`, { method: 'DELETE' }),
2026-02-13 17:27:55 +08:00
install: (data: any) => request<any>('/deps/install', { method: 'POST', body: JSON.stringify(data) }),
getInstallCmd: (data: any) => request<{ command: string }>('/deps/install-cmd', { method: 'POST', body: JSON.stringify(data) }),
uninstall: (id: number) => request<any>(`/deps/uninstall/${id}`, { method: 'POST' }),
2025-12-24 09:57:12 +08:00
reinstall: (id: number) => request(`/deps/reinstall/${id}`, { method: 'POST' }),
2026-02-13 17:27:55 +08:00
reinstallAll: (language: string, lang_version?: string) => {
const query = new URLSearchParams({ language })
if (lang_version) query.set('lang_version', lang_version)
return request(`/deps/reinstall-all?${query}`, { method: 'POST' })
},
getReinstallAllCmd: (language: string, lang_version?: string) => {
const query = new URLSearchParams({ language })
if (lang_version) query.set('lang_version', lang_version)
return request<{ command: string }>(`/deps/reinstall-all-cmd?${query}`, { method: 'POST' })
},
getInstalled: (language: string, lang_version?: string) => {
const query = new URLSearchParams({ language })
if (lang_version) query.set('lang_version', lang_version)
return request<Dependency[]>(`/deps/installed?${query}`)
}
2025-12-27 19:59:15 +08:00
},
agents: {
list: () => request<Agent[]>('/agents'),
getVersion: () => request<{ version: string; platforms: { os: string; arch: string; filename: string }[] }>('/agents/version'),
update: (id: number, data: { name: string; description?: string; enabled: boolean }) =>
request('/agents/' + id, { method: 'PUT', body: JSON.stringify(data) }),
delete: (id: number) => request('/agents/' + id, { method: 'DELETE' }),
forceUpdate: (id: number) => request('/agents/' + id + '/update', { method: 'POST' }),
2026-01-13 18:18:50 +08:00
downloadUrl: (os: string, arch: string) => `${API_BASE_URL}/agent/download?os=${os}&arch=${arch}`,
2025-12-28 11:42:58 +08:00
// 令牌管理
2025-12-30 20:29:04 +08:00
listTokens: () => request<AgentToken[]>('/agents/tokens'),
createToken: (data: { remark?: string; max_uses?: number; expires_at?: string }) =>
request<AgentToken>('/agents/tokens', { method: 'POST', body: JSON.stringify(data) }),
deleteToken: (id: number) => request('/agents/tokens/' + id, { method: 'DELETE' })
2026-02-13 17:27:55 +08:00
},
mise: {
list: () => request<MiseLanguage[]>('/mise/ls'),
sync: () => request<void>('/mise/sync', { method: 'POST' }),
plugins: () => request<string[]>('/mise/plugins'),
2026-02-13 21:16:51 +08:00
versions: (plugin: string) => request<string[]>(`/mise/versions?plugin=${plugin}`),
verifyCommand: (plugin: string, version: string) => request<{ command: string }>(`/mise/verify-cmd?plugin=${plugin}&version=${version}`)
2026-02-27 23:08:44 +08:00
},
terminal: {
cmds: () => request<{ name: string, description: string }[]>('/terminal/cmds')
2025-12-20 09:30:16 +08:00
}
}
export interface FileNode {
name: string
path: string
isDir: boolean
children?: FileNode[]
}
export interface Task {
id: number
name: string
command: string
2026-02-26 20:29:20 +08:00
tags: string
2025-12-25 17:55:54 +08:00
type: string
trigger_type: string
2025-12-25 17:55:54 +08:00
config: string
2025-12-20 09:30:16 +08:00
schedule: string
timeout: number
2025-12-23 23:31:08 +08:00
work_dir: string
2025-12-21 22:19:55 +08:00
clean_config: string
2025-12-21 23:34:34 +08:00
envs: string
2026-02-13 19:26:20 +08:00
languages: { name: string; version: string }[]
2025-12-27 19:59:15 +08:00
agent_id: number | null
2025-12-20 09:30:16 +08:00
enabled: boolean
last_run: string
next_run: string
}
2025-12-25 17:55:54 +08:00
export interface RepoConfig {
source_type: string
source_url: string
target_path: string
branch: string
sparse_path: string
single_file: boolean
proxy: string
proxy_url: string
auth_token: string
2026-02-07 21:44:09 +08:00
concurrency?: number
}
export interface ExecutionResult {
TaskID: number
Success: boolean
Output: string
Error: string
Start: string
End: string
2025-12-25 17:55:54 +08:00
}
2025-12-20 09:30:16 +08:00
export interface TaskListResponse {
data: Task[]
total: number
page: number
page_size: number
}
export interface Script {
id: number
name: string
content: string
}
export interface EnvVar {
id: number
name: string
value: string
remark: string
2026-02-10 15:02:52 +08:00
hidden: boolean
2025-12-20 09:30:16 +08:00
}
export interface EnvListResponse {
data: EnvVar[]
total: number
page: number
page_size: number
}
export interface Stats {
tasks: number
2025-12-24 10:48:23 +08:00
today_execs: number
2025-12-20 09:30:16 +08:00
envs: number
logs: number
scheduled: number
running: number
}
export interface TaskLog {
id: number
task_id: number
task_name: string
2025-12-25 19:16:58 +08:00
task_type: string
2025-12-20 09:30:16 +08:00
command: string
status: string
duration: number
2026-02-08 11:03:11 +08:00
error: string | null
2026-01-01 14:42:33 +08:00
start_time: string | null
end_time: string | null
2025-12-20 09:30:16 +08:00
created_at: string
}
export interface LogListResponse {
data: TaskLog[]
total: number
page: number
page_size: number
}
export interface LogDetail {
id: number
task_id: number
command: string
output: string
2026-02-08 11:03:11 +08:00
error: string | null
2025-12-20 09:30:16 +08:00
status: string
duration: number
2026-01-01 14:42:33 +08:00
start_time: string | null
end_time: string | null
2025-12-20 09:30:16 +08:00
created_at: string
}
export interface AboutInfo {
version: string
build_time: string
mem_usage: string
2025-12-27 13:54:20 +08:00
goroutines: number
2025-12-20 09:30:16 +08:00
uptime: string
task_count: number
log_count: number
env_count: number
}
2025-12-20 12:00:08 +08:00
export interface SiteSettings {
title: string
subtitle: string
icon: string
page_size: string
cookie_days: string
2026-02-28 10:52:53 +08:00
api_token?: string
api_token_expire?: string
2025-12-20 12:00:08 +08:00
}
2025-12-21 10:23:25 +08:00
2025-12-22 16:05:07 +08:00
export interface SchedulerSettings {
worker_count: string
queue_size: string
rate_interval: string
}
2025-12-21 10:23:25 +08:00
export interface LoginLog {
id: number
username: string
ip: string
user_agent: string
status: string
message: string
created_at: string
}
export interface LoginLogListResponse {
data: LoginLog[]
total: number
page: number
page_size: number
}
2025-12-21 21:49:34 +08:00
export interface DailyStats {
day: string
total: number
success: number
failed: number
}
export interface TaskStatsItem {
task_id: number
task_name: string
count: number
}
2025-12-22 00:09:40 +08:00
2025-12-23 23:02:47 +08:00
export interface Dependency {
id: number
2025-12-22 00:09:40 +08:00
name: string
version: string
2026-02-13 17:27:55 +08:00
language: string
lang_version: string
2025-12-23 23:02:47 +08:00
remark: string
2025-12-23 23:10:42 +08:00
log: string
2025-12-23 23:02:47 +08:00
created_at: string
updated_at: string
2025-12-22 00:09:40 +08:00
}
2025-12-27 19:59:15 +08:00
export interface Agent {
id: number
name: string
token: string
2025-12-28 11:42:58 +08:00
machine_id: string
2025-12-27 19:59:15 +08:00
description: string
status: string
last_seen: string
ip: string
version: string
build_time: string
hostname: string
2025-12-28 11:42:58 +08:00
os: string
arch: string
2025-12-27 19:59:15 +08:00
enabled: boolean
created_at: string
updated_at: string
}
2025-12-28 11:42:58 +08:00
2025-12-30 20:29:04 +08:00
export interface AgentToken {
2025-12-28 11:42:58 +08:00
id: number
2025-12-30 20:29:04 +08:00
token: string
2025-12-28 11:42:58 +08:00
remark: string
max_uses: number
used_count: number
expires_at: string | null
enabled: boolean
created_at: string
}
2026-02-13 17:27:55 +08:00
export interface MiseLanguage {
plugin: string
version: string
source: { type?: string; path?: string } | string
active: boolean
install_path?: string
installed_at?: string // 安装日期
}