feat: add qlrepo sync crontab
This commit is contained in:
@@ -1,7 +1,6 @@
|
|||||||
> 出于安全及环境隔离考虑,推荐使用 Docker/Compose 部署方式。[镜像地址](https://github.com/engigu/baihu-panel/pkgs/container/baihu)
|
> 出于安全及环境隔离考虑,推荐使用 Docker/Compose 部署方式。[镜像地址](https://github.com/engigu/baihu-panel/pkgs/container/baihu)
|
||||||
|
|
||||||
|
|
||||||
## 快速部署
|
|
||||||
|
|
||||||
### 🐳 方式一:Docker 部署(推荐)
|
### 🐳 方式一:Docker 部署(推荐)
|
||||||
[部署文档](https://github.com/engigu/baihu-panel?tab=readme-ov-file#%E5%BF%AB%E9%80%9F%E9%83%A8%E7%BD%B2)
|
[部署文档](https://github.com/engigu/baihu-panel?tab=readme-ov-file#%E5%BF%AB%E9%80%9F%E9%83%A8%E7%BD%B2)
|
||||||
|
|||||||
@@ -13,6 +13,7 @@
|
|||||||
|
|
||||||
### 最近更新
|
### 最近更新
|
||||||
|
|
||||||
|
**2026.03.19** - **仓库同步增强**:新增对青龙仓库格式指令的深度兼容,支持从远程 Git 仓库自动同步脚本并基于注释解析自动创建面板任务,支持白名单、黑名单、依赖保留等高级筛选特性。
|
||||||
**2026.03.05** - **API 文档重构** 重构 OpenAPI 认证体系,支持站点级 Token 配置与 Basic Auth 保护;新增设计感十足的全局 **404 页面**。
|
**2026.03.05** - **API 文档重构** 重构 OpenAPI 认证体系,支持站点级 Token 配置与 Basic Auth 保护;新增设计感十足的全局 **404 页面**。
|
||||||
**2026.03.04** - 新增内置消息推送系统:全新原生支持企业微信、钉钉、飞书、Telegram、Bark、邮件等十余种主流渠道的推送,接入系统级事件通知自动捕获,告别原有必配外部推送服务的繁琐历史
|
**2026.03.04** - 新增内置消息推送系统:全新原生支持企业微信、钉钉、飞书、Telegram、Bark、邮件等十余种主流渠道的推送,接入系统级事件通知自动捕获,告别原有必配外部推送服务的繁琐历史
|
||||||
**2026.02.13** - 重构任务执行引擎:深度集成 Mise 运行时管理,支持 Python, Node.js, Go, Rust, PHP 等几乎所有主流语言的动态安装与多版本切换,同步上线跨语言统一依赖管理系统
|
**2026.02.13** - 重构任务执行引擎:深度集成 Mise 运行时管理,支持 Python, Node.js, Go, Rust, PHP 等几乎所有主流语言的动态安装与多版本切换,同步上线跨语言统一依赖管理系统
|
||||||
@@ -92,6 +93,13 @@
|
|||||||
- 变量值脱敏显示
|
- 变量值脱敏显示
|
||||||
- 任务执行时自动注入
|
- 任务执行时自动注入
|
||||||
|
|
||||||
|
### 仓库任务同步 (New)
|
||||||
|
- 支持 青龙 仓库命令格式快捷导入
|
||||||
|
- 自动解析脚本注释中的 Cron 表达式和环境变量名
|
||||||
|
- 支持基于正则表达式的白名单、黑名单文件筛选
|
||||||
|
- 支持脚本依赖文件的识别与保留
|
||||||
|
- 自动同步远程 Git 仓库变更,增量更新面板任务
|
||||||
|
|
||||||
### 系统设置
|
### 系统设置
|
||||||
- 站点标题、标语、图标自定义
|
- 站点标题、标语、图标自定义
|
||||||
- 分页大小、Cookie 有效期配置
|
- 分页大小、Cookie 有效期配置
|
||||||
|
|||||||
+208
-9
@@ -27,7 +27,10 @@ type Config struct {
|
|||||||
ProxyURL string
|
ProxyURL string
|
||||||
AuthToken string
|
AuthToken string
|
||||||
HttpProxy string
|
HttpProxy string
|
||||||
WhitelistPaths string // Comma separated paths to preserve (whitelist)
|
WhitelistPaths string // Comma or vertical line separated paths to preserve or filter (whitelist)
|
||||||
|
Blacklist string // Script filter blacklist keywords, vertical line separated
|
||||||
|
Dependence string // Script dependence file keywords, vertical line separated
|
||||||
|
Extensions string // Script file extensions, vertical line separated
|
||||||
}
|
}
|
||||||
|
|
||||||
func Run(args []string) {
|
func Run(args []string) {
|
||||||
@@ -43,7 +46,10 @@ func Run(args []string) {
|
|||||||
fs.StringVar(&cfg.ProxyURL, "proxy-url", "", "Custom proxy url")
|
fs.StringVar(&cfg.ProxyURL, "proxy-url", "", "Custom proxy url")
|
||||||
fs.StringVar(&cfg.AuthToken, "auth-token", "", "Auth token")
|
fs.StringVar(&cfg.AuthToken, "auth-token", "", "Auth token")
|
||||||
fs.StringVar(&cfg.HttpProxy, "http-proxy", "", "Http proxy")
|
fs.StringVar(&cfg.HttpProxy, "http-proxy", "", "Http proxy")
|
||||||
fs.StringVar(&cfg.WhitelistPaths, "whitelist-paths", "", "Comma separated paths to preserve (whitelist)")
|
fs.StringVar(&cfg.WhitelistPaths, "whitelist-paths", "", "Separated paths to preserve or filter (whitelist)")
|
||||||
|
fs.StringVar(&cfg.Blacklist, "blacklist", "", "Script filter blacklist keywords (| separated)")
|
||||||
|
fs.StringVar(&cfg.Dependence, "dependence", "", "Script dependence keywords (| separated)")
|
||||||
|
fs.StringVar(&cfg.Extensions, "extensions", "", "Script extensions (| separated)")
|
||||||
|
|
||||||
fs.Parse(args)
|
fs.Parse(args)
|
||||||
|
|
||||||
@@ -59,6 +65,11 @@ func Run(args []string) {
|
|||||||
} else {
|
} else {
|
||||||
syncURL(cfg)
|
syncURL(cfg)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 执行脚本过滤(仅限 git 模式,url 加载通常为单文件,暂不处理过滤)
|
||||||
|
if cfg.SourceType == "git" {
|
||||||
|
filterFiles(cfg)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func syncGit(cfg Config) {
|
func syncGit(cfg Config) {
|
||||||
@@ -88,7 +99,7 @@ func syncGit(cfg Config) {
|
|||||||
|
|
||||||
gitDir := filepath.Join(dest, ".git")
|
gitDir := filepath.Join(dest, ".git")
|
||||||
if isDir(dest) && !pathExists(gitDir) {
|
if isDir(dest) && !pathExists(gitDir) {
|
||||||
repoName := getRepoName(cfg.SourceURL)
|
repoName := utils.GetRepoIdentifier(cfg.SourceURL, cfg.Branch)
|
||||||
dest = filepath.Join(dest, repoName)
|
dest = filepath.Join(dest, repoName)
|
||||||
fmt.Printf("目标路径自动追加仓库名: %s\n", dest)
|
fmt.Printf("目标路径自动追加仓库名: %s\n", dest)
|
||||||
gitDir = filepath.Join(dest, ".git")
|
gitDir = filepath.Join(dest, ".git")
|
||||||
@@ -220,6 +231,13 @@ func buildProxyURL(url string, proxyType string, proxyURL string) string {
|
|||||||
if proxyType == "" || proxyType == "none" {
|
if proxyType == "" || proxyType == "none" {
|
||||||
return url
|
return url
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 如果 URL 已经包含明显的代理前缀 (如用户手动填写的 http://ghproxy.com/...)
|
||||||
|
// 则跳过内置代理逻辑
|
||||||
|
if strings.Contains(url, "googo.win") || (proxyType == "custom" && strings.HasPrefix(url, proxyURL)) {
|
||||||
|
return url
|
||||||
|
}
|
||||||
|
|
||||||
base := ""
|
base := ""
|
||||||
if proxyType == "ghproxy" {
|
if proxyType == "ghproxy" {
|
||||||
base = "https://gh-proxy.com/"
|
base = "https://gh-proxy.com/"
|
||||||
@@ -229,7 +247,7 @@ func buildProxyURL(url string, proxyType string, proxyURL string) string {
|
|||||||
base = strings.TrimSuffix(proxyURL, "/") + "/"
|
base = strings.TrimSuffix(proxyURL, "/") + "/"
|
||||||
}
|
}
|
||||||
|
|
||||||
if base != "" && strings.HasPrefix(url, "http") {
|
if base != "" && strings.HasPrefix(url, "http") && !strings.HasPrefix(url, base) {
|
||||||
return base + url
|
return base + url
|
||||||
}
|
}
|
||||||
return url
|
return url
|
||||||
@@ -299,11 +317,7 @@ func isRawFileURL(url string) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
func getRepoName(url string) string {
|
|
||||||
u := strings.TrimSuffix(url, "/")
|
|
||||||
u = strings.TrimSuffix(u, ".git")
|
|
||||||
return filepath.Base(u)
|
|
||||||
}
|
|
||||||
|
|
||||||
var ansiRegex = regexp.MustCompile("\x1b\\[[0-9;]*[a-zA-Z]")
|
var ansiRegex = regexp.MustCompile("\x1b\\[[0-9;]*[a-zA-Z]")
|
||||||
|
|
||||||
@@ -495,3 +509,188 @@ func preserve(baseDir string, paths string) func() {
|
|||||||
os.RemoveAll(tmpParent)
|
os.RemoveAll(tmpParent)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// filterFiles performs script filtering based on whitelist, blacklist, dependence and extensions.
|
||||||
|
func filterFiles(cfg Config) {
|
||||||
|
// If no filtering is specified, do nothing.
|
||||||
|
if cfg.WhitelistPaths == "" && cfg.Blacklist == "" && cfg.Dependence == "" && cfg.Extensions == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
dest := cfg.TargetPath
|
||||||
|
// If the dest appended a repo name in syncGit, we need to find it.
|
||||||
|
// However, BuildRepoCommand already passes the abs path which might already be the specific repo dir.
|
||||||
|
// We'll walk from cfg.TargetPath.
|
||||||
|
|
||||||
|
gitDir := filepath.Join(dest, ".git")
|
||||||
|
if isDir(dest) && !pathExists(gitDir) {
|
||||||
|
repoName := utils.GetRepoIdentifier(cfg.SourceURL, cfg.Branch)
|
||||||
|
if pathExists(filepath.Join(dest, repoName)) {
|
||||||
|
dest = filepath.Join(dest, repoName)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Printf("开始执行脚本过滤: %s\n", dest)
|
||||||
|
|
||||||
|
whitelist := splitKeywords(cfg.WhitelistPaths)
|
||||||
|
blacklist := splitKeywords(cfg.Blacklist)
|
||||||
|
dependence := splitKeywords(cfg.Dependence)
|
||||||
|
extensions := splitKeywords(cfg.Extensions)
|
||||||
|
|
||||||
|
// We'll collect files to delete to avoid modifying while walking if possible.
|
||||||
|
// But os.RemoveAll is fine.
|
||||||
|
|
||||||
|
count := 0
|
||||||
|
filepath.Walk(dest, func(path string, info os.FileInfo, err error) error {
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if info.IsDir() {
|
||||||
|
if info.Name() == ".git" {
|
||||||
|
return filepath.SkipDir
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
rel, _ := filepath.Rel(dest, path)
|
||||||
|
rel = filepath.ToSlash(rel)
|
||||||
|
filename := info.Name()
|
||||||
|
|
||||||
|
// 1. Check dependence: always keep
|
||||||
|
if matchesAny(rel, filename, dependence) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Check extensions: delete if not matched and extensions is specified
|
||||||
|
if len(extensions) > 0 {
|
||||||
|
ext := strings.TrimPrefix(filepath.Ext(filename), ".")
|
||||||
|
matchedExt := false
|
||||||
|
for _, e := range extensions {
|
||||||
|
if strings.EqualFold(ext, strings.TrimPrefix(e, ".")) {
|
||||||
|
matchedExt = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !matchedExt {
|
||||||
|
fmt.Printf("过滤文件 (后缀不符): %s\n", rel)
|
||||||
|
os.Remove(path)
|
||||||
|
count++
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Check blacklist: delete if matched
|
||||||
|
if matchesAny(rel, filename, blacklist) {
|
||||||
|
fmt.Printf("过滤文件 (黑名单): %s\n", rel)
|
||||||
|
os.Remove(path)
|
||||||
|
count++
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Check whitelist: delete if NOT matched and whitelist is specified
|
||||||
|
if len(whitelist) > 0 {
|
||||||
|
if !matchesAny(rel, filename, whitelist) {
|
||||||
|
fmt.Printf("过滤文件 (不在白名单): %s\n", rel)
|
||||||
|
os.Remove(path)
|
||||||
|
count++
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
if count > 0 {
|
||||||
|
fmt.Printf("过滤完成,共删除 %d 个不符合要求的文件\n", count)
|
||||||
|
// Try to clean up empty directories
|
||||||
|
cleanEmptyDirs(dest)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func splitKeywords(s string) []string {
|
||||||
|
if s == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
// Try to split by common separators for compatibility
|
||||||
|
var parts []string
|
||||||
|
if strings.Contains(s, "|") {
|
||||||
|
parts = strings.Split(s, "|")
|
||||||
|
} else if strings.Contains(s, ",") {
|
||||||
|
parts = strings.Split(s, ",")
|
||||||
|
} else {
|
||||||
|
parts = []string{s}
|
||||||
|
}
|
||||||
|
|
||||||
|
var res []string
|
||||||
|
for _, p := range parts {
|
||||||
|
p = strings.TrimSpace(p)
|
||||||
|
if p != "" {
|
||||||
|
res = append(res, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
|
func matchesAny(rel, filename string, keywords []string) bool {
|
||||||
|
if len(keywords) == 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, k := range keywords {
|
||||||
|
// 1. 尝试作为正则整体进行匹配,默认不区分大小写 (?i)
|
||||||
|
// 如果关键字不包含正则元字符,则补齐 (?i) 开启忽略大小写
|
||||||
|
pattern := k
|
||||||
|
if !strings.HasPrefix(pattern, "(?i)") {
|
||||||
|
pattern = "(?i)" + pattern
|
||||||
|
}
|
||||||
|
|
||||||
|
reg, err := regexp.Compile(pattern)
|
||||||
|
if err == nil {
|
||||||
|
// 优先匹配文件名(解决 ^jd[^_] 这种锚点在相对路径下失效的问题)
|
||||||
|
if reg.MatchString(filename) || reg.MatchString(rel) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// 回退逻辑:全小写包含判断
|
||||||
|
kLower := strings.ToLower(k)
|
||||||
|
if strings.Contains(strings.ToLower(rel), kLower) || strings.Contains(strings.ToLower(filename), kLower) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func cleanEmptyDirs(root string) {
|
||||||
|
// Post-order traversal to clean up empty dirs
|
||||||
|
filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if !info.IsDir() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if path == root {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if info.Name() == ".git" {
|
||||||
|
return filepath.SkipDir
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
// Actually we need to do this recursively or multiple times.
|
||||||
|
// A simpler way:
|
||||||
|
entries, _ := os.ReadDir(root)
|
||||||
|
for _, entry := range entries {
|
||||||
|
if entry.IsDir() {
|
||||||
|
if entry.Name() == ".git" { continue }
|
||||||
|
dirPath := filepath.Join(root, entry.Name())
|
||||||
|
cleanEmptyDirs(dirPath)
|
||||||
|
// Check if now empty
|
||||||
|
if isDirEmpty(dirPath) {
|
||||||
|
os.Remove(dirPath)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,17 +2,11 @@
|
|||||||
|
|
||||||
本页面记录了白虎面板的主要版本更新历史。
|
本页面记录了白虎面板的主要版本更新历史。
|
||||||
|
|
||||||
## ⚠️ 重大升级与迁移说明 (v3 数据结构)
|
|
||||||
|
|
||||||
本次更新包含底层数据结构的重大突破,将所有数据的 ID 类型从数字编号平滑迁移为 20 位的字符式全局唯一标识符(`xid`)。系统在启动时会**自动进行数据的清洗、映射、拷贝与外键修补**,以确保旧数据被妥善对接。
|
|
||||||
|
|
||||||
- **备份位置**:执行迁移前,即使有程序自动转换逻辑(data\migration_v3_backup_backup_xxx.zip),为了数据安全,仍然建议您**提前手动进行备份**。
|
|
||||||
- **降级机制**:如果遇到未预期的迁移失败或数据显示丢失,**请使用原本备份的数据库** 并 **降级至 `v1.0.10` 及以下旧版本** 进行恢复与使用。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 最近更新概览
|
## 最近更新概览
|
||||||
|
|
||||||
|
### 2026.03.19 - 仓库同步功能增强
|
||||||
|
- **青龙指令深度兼容**:支持直接粘贴青龙格式的仓库同步指令,自动解析并创建任务。
|
||||||
|
|
||||||
### 2026.03.05 - API 文档重构
|
### 2026.03.05 - API 文档重构
|
||||||
- **OpenAPI 认证体系**:支持站点级 Token 配置与 Basic Auth 保护。
|
- **OpenAPI 认证体系**:支持站点级 Token 配置与 Basic Auth 保护。
|
||||||
- **自定义 UI**:新增设计感十足的全局 **404 页面**。
|
- **自定义 UI**:新增设计感十足的全局 **404 页面**。
|
||||||
|
|||||||
@@ -38,6 +38,13 @@
|
|||||||
- **机密性管理**:对敏感字段(如脚本 Key、DB 密码)进行脱敏显示和加密存储。
|
- **机密性管理**:对敏感字段(如脚本 Key、DB 密码)进行脱敏显示和加密存储。
|
||||||
- **全局环境隔离**:在不同脚本运行期间动态注入,确保持久化和隔离。
|
- **全局环境隔离**:在不同脚本运行期间动态注入,确保持久化和隔离。
|
||||||
|
|
||||||
|
## 仓库任务同步
|
||||||
|
|
||||||
|
- **青龙指令兼容**:支持直接粘贴 `ql repo` 指令快速创建同步任务。
|
||||||
|
- **脚本自动注册**:自动扫描同步目录下的脚本文件,解析其中的 `new Env()` 名称和 `cron` 表达式。
|
||||||
|
- **灵活筛选规则**:支持通过正则表达式配置白名单、黑名单,精确控制哪些脚本需要转化为面板任务。
|
||||||
|
- **版本控制集成**:基于 Git 进行增量同步,支持分支切换和稀疏检出(Sparse Checkout)。
|
||||||
|
|
||||||
## 系统设置
|
## 系统设置
|
||||||
|
|
||||||
- **数据备份与恢复**:支持全量数据的本地导出和一键导入恢复。
|
- **数据备份与恢复**:支持全量数据的本地导出和一键导入恢复。
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import (
|
|||||||
|
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
@@ -301,18 +302,46 @@ func (sc *SettingsController) GetAbout(c *gin.Context) {
|
|||||||
// 运行时间
|
// 运行时间
|
||||||
uptime := formatDuration(time.Since(constant.StartTime))
|
uptime := formatDuration(time.Since(constant.StartTime))
|
||||||
|
|
||||||
|
// 获取远程最新版本
|
||||||
|
remoteVersion := ""
|
||||||
|
client := &http.Client{Timeout: 2 * time.Second}
|
||||||
|
req, err := http.NewRequest("GET", "https://api.github.com/repos/engigu/baihu-panel/releases/latest", nil)
|
||||||
|
if err == nil {
|
||||||
|
req.Header.Set("User-Agent", "baihu-panel")
|
||||||
|
if resp, err := client.Do(req); err == nil {
|
||||||
|
defer resp.Body.Close()
|
||||||
|
var release struct {
|
||||||
|
TagName string `json:"tag_name"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(resp.Body).Decode(&release); err == nil {
|
||||||
|
remoteVersion = release.TagName
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
utils.Success(c, gin.H{
|
utils.Success(c, gin.H{
|
||||||
"version": constant.Version,
|
"version": constant.Version,
|
||||||
"build_time": constant.BuildTime,
|
"remote_version": remoteVersion,
|
||||||
"mem_usage": memUsage,
|
"build_time": constant.BuildTime,
|
||||||
"goroutines": runtime.NumGoroutine(),
|
"mem_usage": memUsage,
|
||||||
"uptime": uptime,
|
"goroutines": runtime.NumGoroutine(),
|
||||||
"task_count": taskCount,
|
"uptime": uptime,
|
||||||
"log_count": logCount,
|
"task_count": taskCount,
|
||||||
"env_count": envCount,
|
"log_count": logCount,
|
||||||
|
"env_count": envCount,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetChangelog 获取更新日志
|
||||||
|
func (sc *SettingsController) GetChangelog(c *gin.Context) {
|
||||||
|
content, err := os.ReadFile("docs/guide/changelog.md")
|
||||||
|
if err != nil {
|
||||||
|
utils.Success(c, "暂无更新日志")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
utils.Success(c, string(content))
|
||||||
|
}
|
||||||
|
|
||||||
// formatBytes 格式化字节数
|
// formatBytes 格式化字节数
|
||||||
func formatBytes(bytes uint64) string {
|
func formatBytes(bytes uint64) string {
|
||||||
const unit = 1024
|
const unit = 1024
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
package controllers
|
package controllers
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/json"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
|
||||||
"github.com/engigu/baihu-panel/internal/constant"
|
"github.com/engigu/baihu-panel/internal/constant"
|
||||||
|
"github.com/engigu/baihu-panel/internal/models"
|
||||||
"github.com/engigu/baihu-panel/internal/models/vo"
|
"github.com/engigu/baihu-panel/internal/models/vo"
|
||||||
"github.com/engigu/baihu-panel/internal/services"
|
"github.com/engigu/baihu-panel/internal/services"
|
||||||
"github.com/engigu/baihu-panel/internal/services/tasks"
|
"github.com/engigu/baihu-panel/internal/services/tasks"
|
||||||
@@ -93,7 +95,30 @@ func (tc *TaskController) CreateTask(c *gin.Context) {
|
|||||||
workDir = resolveWorkDir(req.WorkDir)
|
workDir = resolveWorkDir(req.WorkDir)
|
||||||
}
|
}
|
||||||
|
|
||||||
task := tc.taskService.CreateTask(req.Name, req.Command, req.Schedule, req.Timeout, workDir, req.CleanConfig, req.Envs, req.Type, req.Config, req.AgentID, req.Languages, req.TriggerType, req.Tags, req.RetryCount, req.RetryInterval, req.RandomRange)
|
var sourceID string
|
||||||
|
// 如果是仓库同步任务,根据 URL 生成 SourceID 用于去重
|
||||||
|
if req.Type == constant.TaskTypeRepo && req.Config != "" {
|
||||||
|
var repoCfg struct {
|
||||||
|
SourceURL string `json:"source_url"`
|
||||||
|
Branch string `json:"branch"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal([]byte(req.Config), &repoCfg); err == nil && repoCfg.SourceURL != "" {
|
||||||
|
sourceID = "repo_" + utils.GetRepoIdentifier(repoCfg.SourceURL, repoCfg.Branch)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var task *models.Task
|
||||||
|
// 去重逻辑:如果已存在相同 SourceID 的仓库任务,则改为更新
|
||||||
|
if sourceID != "" {
|
||||||
|
task = tc.taskService.GetTaskBySourceID(sourceID)
|
||||||
|
if task != nil {
|
||||||
|
task = tc.taskService.UpdateTask(task.ID, req.Name, req.Command, req.Schedule, req.Timeout, workDir, req.CleanConfig, req.Envs, true, req.Type, req.Config, req.AgentID, req.Languages, req.TriggerType, req.Tags, req.RetryCount, req.RetryInterval, req.RandomRange, sourceID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if task == nil {
|
||||||
|
task = tc.taskService.CreateTask(req.Name, req.Command, req.Schedule, req.Timeout, workDir, req.CleanConfig, req.Envs, req.Type, req.Config, req.AgentID, req.Languages, req.TriggerType, req.Tags, req.RetryCount, req.RetryInterval, req.RandomRange, sourceID)
|
||||||
|
}
|
||||||
|
|
||||||
// 如果是 Agent 任务,通知 Agent;否则添加到本地 cron
|
// 如果是 Agent 任务,通知 Agent;否则添加到本地 cron
|
||||||
if task.AgentID != nil && *task.AgentID != "" {
|
if task.AgentID != nil && *task.AgentID != "" {
|
||||||
@@ -228,7 +253,20 @@ func (tc *TaskController) UpdateTask(c *gin.Context) {
|
|||||||
workDir = resolveWorkDir(req.WorkDir)
|
workDir = resolveWorkDir(req.WorkDir)
|
||||||
}
|
}
|
||||||
|
|
||||||
task := tc.taskService.UpdateTask(id, req.Name, req.Command, req.Schedule, req.Timeout, workDir, req.CleanConfig, req.Envs, req.Enabled, req.Type, req.Config, req.AgentID, req.Languages, req.TriggerType, req.Tags, req.RetryCount, req.RetryInterval, req.RandomRange)
|
var sourceID string
|
||||||
|
if req.Type == constant.TaskTypeRepo && req.Config != "" {
|
||||||
|
var repoCfg struct {
|
||||||
|
SourceURL string `json:"source_url"`
|
||||||
|
Branch string `json:"branch"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal([]byte(req.Config), &repoCfg); err == nil && repoCfg.SourceURL != "" {
|
||||||
|
sourceID = "repo_" + utils.GetRepoIdentifier(repoCfg.SourceURL, repoCfg.Branch)
|
||||||
|
}
|
||||||
|
} else if oldTask != nil {
|
||||||
|
sourceID = oldTask.SourceID
|
||||||
|
}
|
||||||
|
|
||||||
|
task := tc.taskService.UpdateTask(id, req.Name, req.Command, req.Schedule, req.Timeout, workDir, req.CleanConfig, req.Envs, req.Enabled, req.Type, req.Config, req.AgentID, req.Languages, req.TriggerType, req.Tags, req.RetryCount, req.RetryInterval, req.RandomRange, sourceID)
|
||||||
if task == nil {
|
if task == nil {
|
||||||
utils.NotFound(c, "任务不存在")
|
utils.NotFound(c, "任务不存在")
|
||||||
return
|
return
|
||||||
@@ -300,6 +338,94 @@ func (tc *TaskController) DeleteTask(c *gin.Context) {
|
|||||||
utils.SuccessMsg(c, "删除成功")
|
utils.SuccessMsg(c, "删除成功")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (tc *TaskController) BatchDeleteTasks(c *gin.Context) {
|
||||||
|
var req struct {
|
||||||
|
IDs []string `json:"ids" binding:"required"`
|
||||||
|
}
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
utils.BadRequest(c, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 收集涉及到的 AgentID
|
||||||
|
agentIDs := make(map[string]struct{})
|
||||||
|
for _, id := range req.IDs {
|
||||||
|
// 获取任务信息
|
||||||
|
task := tc.taskService.GetTaskByID(id)
|
||||||
|
if task != nil {
|
||||||
|
if task.AgentID != nil && *task.AgentID != "" {
|
||||||
|
agentIDs[*task.AgentID] = struct{}{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 移除 cron 调度
|
||||||
|
tc.executorService.RemoveCronTask(id)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 执行批量删除
|
||||||
|
count := tc.taskService.BatchDeleteTasks(req.IDs)
|
||||||
|
|
||||||
|
// 通知受影响的 Agent
|
||||||
|
for agentID := range agentIDs {
|
||||||
|
tc.agentWSManager.BroadcastTasks(agentID)
|
||||||
|
}
|
||||||
|
|
||||||
|
utils.Success(c, gin.H{"count": count})
|
||||||
|
}
|
||||||
|
|
||||||
|
// BatchDeleteByQuery 根据查询条件批量删除任务
|
||||||
|
// @Summary 根据查询条件批量删除任务
|
||||||
|
// @Description 根据查询条件批量删除匹配的所有任务
|
||||||
|
// @Tags 任务管理
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Security BearerAuth
|
||||||
|
// @Param name query string false "任务名称关键词"
|
||||||
|
// @Param tags query string false "标签关键词"
|
||||||
|
// @Param type query string false "任务类型"
|
||||||
|
// @Param agent_id query string false "执行位置(节点ID)"
|
||||||
|
// @Success 200 {object} utils.Response{data=map[string]int}
|
||||||
|
// @Failure 401 {object} utils.Response "未授权"
|
||||||
|
// @Router /tasks/batch-by-query [delete]
|
||||||
|
func (tc *TaskController) BatchDeleteByQuery(c *gin.Context) {
|
||||||
|
name := c.Query("name")
|
||||||
|
agentIDStr := c.Query("agent_id")
|
||||||
|
tags := c.Query("tags")
|
||||||
|
taskType := c.Query("type")
|
||||||
|
|
||||||
|
var agentID *string
|
||||||
|
if agentIDStr != "" {
|
||||||
|
agentID = &agentIDStr
|
||||||
|
}
|
||||||
|
|
||||||
|
tasks, _ := tc.taskService.GetTasksWithPagination(1, 999999, name, agentID, tags, taskType)
|
||||||
|
if len(tasks) == 0 {
|
||||||
|
utils.Success(c, gin.H{"count": 0})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var ids []string
|
||||||
|
agentIDs := make(map[string]struct{})
|
||||||
|
for _, task := range tasks {
|
||||||
|
ids = append(ids, task.ID)
|
||||||
|
if task.AgentID != nil && *task.AgentID != "" {
|
||||||
|
agentIDs[*task.AgentID] = struct{}{}
|
||||||
|
}
|
||||||
|
// 移除 cron 调度
|
||||||
|
tc.executorService.RemoveCronTask(task.ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 执行批量删除
|
||||||
|
count := tc.taskService.BatchDeleteTasks(ids)
|
||||||
|
|
||||||
|
// 通知受影响的 Agent
|
||||||
|
for aID := range agentIDs {
|
||||||
|
tc.agentWSManager.BroadcastTasks(aID)
|
||||||
|
}
|
||||||
|
|
||||||
|
utils.Success(c, gin.H{"count": count})
|
||||||
|
}
|
||||||
|
|
||||||
// StopTask 停止任务
|
// StopTask 停止任务
|
||||||
// @Summary 停止任务
|
// @Summary 停止任务
|
||||||
// @Description 根据运行日志 ID 停止正在执行的任务
|
// @Description 根据运行日志 ID 停止正在执行的任务
|
||||||
|
|||||||
@@ -23,7 +23,12 @@ type RepoConfig struct {
|
|||||||
Proxy string `json:"proxy"` // 代理类型: none, ghproxy, mirror, custom
|
Proxy string `json:"proxy"` // 代理类型: none, ghproxy, mirror, custom
|
||||||
ProxyURL string `json:"proxy_url"` // 自定义代理地址
|
ProxyURL string `json:"proxy_url"` // 自定义代理地址
|
||||||
AuthToken string `json:"auth_token"` // 认证 Token
|
AuthToken string `json:"auth_token"` // 认证 Token
|
||||||
WhitelistPaths string `json:"whitelist_paths"` // 同步时保留的路径(白名单路径),逗号分隔
|
WhitelistPaths string `json:"whitelist_paths"` // 同步时保留的路径及脚本筛选白名单关键词,逗号或竖线分割
|
||||||
|
Blacklist string `json:"blacklist"` // 脚本筛选黑名单关键词,竖线分割
|
||||||
|
Dependence string `json:"dependence"` // 脚本依赖文件关键词,竖线分割
|
||||||
|
Extensions string `json:"extensions"` // 脚本文件后缀关键词,竖线分割
|
||||||
|
AutoAddCron bool `json:"auto_add_cron"` // 自动解析脚本注释添加定时任务
|
||||||
|
RepoSource string `json:"repo_source"` // 仓库来源,如果是选择了这个 ql 导入的仓库,= ql
|
||||||
}
|
}
|
||||||
|
|
||||||
// TaskConfig 任务配置 RepoConfig+TaskConfig=task.config
|
// TaskConfig 任务配置 RepoConfig+TaskConfig=task.config
|
||||||
@@ -56,6 +61,8 @@ type Task struct {
|
|||||||
RuntimeEnvs []string `json:"-" gorm:"-"` // 运行时环境变量(非持久化)
|
RuntimeEnvs []string `json:"-" gorm:"-"` // 运行时环境变量(非持久化)
|
||||||
LastRun *LocalTime `json:"last_run"`
|
LastRun *LocalTime `json:"last_run"`
|
||||||
NextRun *LocalTime `json:"next_run"`
|
NextRun *LocalTime `json:"next_run"`
|
||||||
|
SourceID string `json:"source_id" gorm:"size:255;index"` // 脚本资源唯一标识(路径 sanitized)
|
||||||
|
RepoTaskID string `json:"repo_task_id" gorm:"size:20;index"` // 所属的仓库任务 ID
|
||||||
CreatedAt LocalTime `json:"created_at"`
|
CreatedAt LocalTime `json:"created_at"`
|
||||||
UpdatedAt LocalTime `json:"updated_at"`
|
UpdatedAt LocalTime `json:"updated_at"`
|
||||||
DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`
|
DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ type TaskVO struct {
|
|||||||
Envs string `json:"envs"`
|
Envs string `json:"envs"`
|
||||||
Languages []map[string]string `json:"languages"`
|
Languages []map[string]string `json:"languages"`
|
||||||
AgentID *string `json:"agent_id"`
|
AgentID *string `json:"agent_id"`
|
||||||
|
RepoTaskID string `json:"repo_task_id"`
|
||||||
Enabled bool `json:"enabled"`
|
Enabled bool `json:"enabled"`
|
||||||
RetryCount int `json:"retry_count"`
|
RetryCount int `json:"retry_count"`
|
||||||
RetryInterval int `json:"retry_interval"`
|
RetryInterval int `json:"retry_interval"`
|
||||||
@@ -51,6 +52,7 @@ func ToTaskVO(task *models.Task) *TaskVO {
|
|||||||
Envs: string(task.Envs),
|
Envs: string(task.Envs),
|
||||||
Languages: task.Languages,
|
Languages: task.Languages,
|
||||||
AgentID: task.AgentID,
|
AgentID: task.AgentID,
|
||||||
|
RepoTaskID: task.RepoTaskID,
|
||||||
Enabled: task.Enabled,
|
Enabled: task.Enabled,
|
||||||
RetryCount: task.RetryCount,
|
RetryCount: task.RetryCount,
|
||||||
RetryInterval: task.RetryInterval,
|
RetryInterval: task.RetryInterval,
|
||||||
|
|||||||
@@ -73,6 +73,8 @@ func registerTaskRoutes(g *gin.RouterGroup, c *Controllers) {
|
|||||||
tasks.GET("/:id", c.Task.GetTask)
|
tasks.GET("/:id", c.Task.GetTask)
|
||||||
tasks.PUT("/:id", c.Task.UpdateTask)
|
tasks.PUT("/:id", c.Task.UpdateTask)
|
||||||
tasks.DELETE("/:id", c.Task.DeleteTask)
|
tasks.DELETE("/:id", c.Task.DeleteTask)
|
||||||
|
tasks.POST("/batch-delete", c.Task.BatchDeleteTasks)
|
||||||
|
tasks.DELETE("/batch-by-query", c.Task.BatchDeleteByQuery)
|
||||||
tasks.POST("/stop/:logID", c.Task.StopTask)
|
tasks.POST("/stop/:logID", c.Task.StopTask)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -153,6 +155,7 @@ func registerSettingsRoutes(g *gin.RouterGroup, c *Controllers) {
|
|||||||
settings.GET("/scheduler", c.Settings.GetSchedulerSettings)
|
settings.GET("/scheduler", c.Settings.GetSchedulerSettings)
|
||||||
settings.PUT("/scheduler", c.Settings.UpdateSchedulerSettings)
|
settings.PUT("/scheduler", c.Settings.UpdateSchedulerSettings)
|
||||||
settings.GET("/about", c.Settings.GetAbout)
|
settings.GET("/about", c.Settings.GetAbout)
|
||||||
|
settings.GET("/changelog", c.Settings.GetChangelog)
|
||||||
settings.GET("/loginlogs", c.Settings.GetLoginLogs)
|
settings.GET("/loginlogs", c.Settings.GetLoginLogs)
|
||||||
settings.POST("/backup", c.Settings.CreateBackup)
|
settings.POST("/backup", c.Settings.CreateBackup)
|
||||||
settings.GET("/backup/status", c.Settings.GetBackupStatus)
|
settings.GET("/backup/status", c.Settings.GetBackupStatus)
|
||||||
|
|||||||
@@ -241,6 +241,10 @@ func (h *ServerSchedulerHandler) OnTaskCompleted(req *executor.ExecutionRequest,
|
|||||||
// 处理任务完成(更新统计、清理旧日志等)
|
// 处理任务完成(更新统计、清理旧日志等)
|
||||||
h.es.taskLogService.ProcessTaskCompletion(taskLog)
|
h.es.taskLogService.ProcessTaskCompletion(taskLog)
|
||||||
|
|
||||||
|
if task.Type == constant.TaskTypeRepo && result.Status == constant.TaskStatusSuccess {
|
||||||
|
go ParseRepoScriptsAndAddCron(h.es, task)
|
||||||
|
}
|
||||||
|
|
||||||
// 更新内存缓冲
|
// 更新内存缓冲
|
||||||
h.es.UpdateResult(*result)
|
h.es.UpdateResult(*result)
|
||||||
|
|
||||||
@@ -419,6 +423,10 @@ func (h *LocalTaskHooks) OnHeartbeat(ctx context.Context, logID string, duration
|
|||||||
func (es *ExecutorService) ExecuteDispatcher(ctx context.Context, req *executor.ExecutionRequest, stdout, stderr io.Writer) (*executor.Result, error) {
|
func (es *ExecutorService) ExecuteDispatcher(ctx context.Context, req *executor.ExecutionRequest, stdout, stderr io.Writer) (*executor.Result, error) {
|
||||||
taskID := req.TaskID
|
taskID := req.TaskID
|
||||||
|
|
||||||
|
// 解析路径变量 (如 $SCRIPTS_DIR$)
|
||||||
|
req.Command = es.ResolvePath(req.Command)
|
||||||
|
req.WorkDir = es.ResolvePath(req.WorkDir)
|
||||||
|
|
||||||
task := es.taskService.GetTaskByID(taskID)
|
task := es.taskService.GetTaskByID(taskID)
|
||||||
// 系统任务(无 taskID)直接本地执行
|
// 系统任务(无 taskID)直接本地执行
|
||||||
if task == nil {
|
if task == nil {
|
||||||
@@ -479,7 +487,7 @@ func (es *ExecutorService) Stop() {
|
|||||||
|
|
||||||
// StartCron 启动计划任务
|
// StartCron 启动计划任务
|
||||||
func (es *ExecutorService) StartCron() {
|
func (es *ExecutorService) StartCron() {
|
||||||
es.loadCronTasks()
|
go es.loadCronTasks()
|
||||||
es.cronManager.Start()
|
es.cronManager.Start()
|
||||||
// logger.Info("[Executor] 计划任务管理器已启动")
|
// logger.Info("[Executor] 计划任务管理器已启动")
|
||||||
}
|
}
|
||||||
@@ -949,8 +957,24 @@ func (es *ExecutorService) BuildRepoCommand(task *models.Task) (string, string)
|
|||||||
if config.WhitelistPaths != "" {
|
if config.WhitelistPaths != "" {
|
||||||
args = append(args, "--whitelist-paths", config.WhitelistPaths)
|
args = append(args, "--whitelist-paths", config.WhitelistPaths)
|
||||||
}
|
}
|
||||||
|
if config.Blacklist != "" {
|
||||||
|
args = append(args, "--blacklist", config.Blacklist)
|
||||||
|
}
|
||||||
|
if config.Dependence != "" {
|
||||||
|
args = append(args, "--dependence", config.Dependence)
|
||||||
|
}
|
||||||
|
if config.Extensions != "" {
|
||||||
|
args = append(args, "--extensions", config.Extensions)
|
||||||
|
}
|
||||||
|
|
||||||
return exePath + " " + strings.Join(args, " "), filepath.Dir(exePath)
|
// 为了防止 shell 解释特殊字符(如 |),对每个参数进行转义/加引号
|
||||||
|
quotedArgs := make([]string, len(args))
|
||||||
|
for i, arg := range args {
|
||||||
|
// 使用单引号包裹参数,并转义已有的单引号
|
||||||
|
quotedArgs[i] = "'" + strings.ReplaceAll(arg, "'", "'\\''") + "'"
|
||||||
|
}
|
||||||
|
|
||||||
|
return "'" + strings.ReplaceAll(exePath, "'", "'\\''") + "' " + strings.Join(quotedArgs, " "), filepath.Dir(exePath)
|
||||||
}
|
}
|
||||||
|
|
||||||
// loadEnvVars 加载环境变量,支持全局注入及重名合并
|
// loadEnvVars 加载环境变量,支持全局注入及重名合并
|
||||||
@@ -981,3 +1005,8 @@ func (es *ExecutorService) loadEnvVars(taskID string, envIDs string) []string {
|
|||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (es *ExecutorService) ResolvePath(path string) string {
|
||||||
|
absScriptsDir, _ := filepath.Abs(constant.ScriptsWorkDir)
|
||||||
|
return strings.ReplaceAll(path, "$SCRIPTS_DIR$", absScriptsDir)
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,427 @@
|
|||||||
|
package tasks
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io/fs"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/engigu/baihu-panel/internal/constant"
|
||||||
|
"github.com/engigu/baihu-panel/internal/database"
|
||||||
|
"github.com/engigu/baihu-panel/internal/models"
|
||||||
|
"github.com/engigu/baihu-panel/internal/utils"
|
||||||
|
)
|
||||||
|
|
||||||
|
// regex patterns for script comment parsing
|
||||||
|
var (
|
||||||
|
envRegex = regexp.MustCompile(`(?i)[new ]*Env\(['"]?([^'"]+)['"]?\)[;]?`)
|
||||||
|
cronRegex = regexp.MustCompile(`(?i)(?:cron[ \t]*[:=]?[ \t]*['"]([^'"]+)['"])|(?:(?:^|[ \t\*\/])([0-9\*\/\-,L?]+[ \t]+[0-9\*\/\-,L?#]+[ \t]+[0-9\*\/\-,L?#]+[ \t]+[0-9\*\/\-,L?#]+[ \t]+[0-9\*\/\-,L?#]+(?:[ \t]+[0-9\*\/\-,L?#]+)?))`)
|
||||||
|
)
|
||||||
|
|
||||||
|
// ParseRepoScriptsAndAddCron scans the repo dir for scripts, parses cron and env comments, and registers tasks
|
||||||
|
func ParseRepoScriptsAndAddCron(es *ExecutorService, repoTask *models.Task) {
|
||||||
|
if repoTask == nil || repoTask.Type != constant.TaskTypeRepo {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var repoCfg models.RepoConfig
|
||||||
|
if err := json.Unmarshal([]byte(repoTask.Config), &repoCfg); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if repoCfg.RepoSource != "ql" || !repoCfg.AutoAddCron {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// target path
|
||||||
|
targetPath := repoCfg.TargetPath
|
||||||
|
if targetPath == "" {
|
||||||
|
targetPath = repoTask.WorkDir
|
||||||
|
}
|
||||||
|
if targetPath == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// We might have appended a repo id to targetPath
|
||||||
|
repoId := utils.GetRepoIdentifier(repoCfg.SourceURL, repoCfg.Branch)
|
||||||
|
|
||||||
|
gitDir := filepath.Join(targetPath, ".git")
|
||||||
|
if !isDir(targetPath) || !pathExists(gitDir) {
|
||||||
|
repoPath := filepath.Join(targetPath, repoId)
|
||||||
|
if pathExists(repoPath) {
|
||||||
|
targetPath = repoPath
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !pathExists(targetPath) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// tag used during sync
|
||||||
|
tag := fmt.Sprintf("%s", repoId)
|
||||||
|
|
||||||
|
exts := []string{".js", ".py", ".ts", ".sh", ".php"}
|
||||||
|
if repoCfg.Extensions != "" {
|
||||||
|
customExts := splitKeywords(repoCfg.Extensions)
|
||||||
|
if len(customExts) > 0 {
|
||||||
|
exts = nil
|
||||||
|
for _, e := range customExts {
|
||||||
|
e = strings.TrimSpace(e)
|
||||||
|
if e != "" {
|
||||||
|
if !strings.HasPrefix(e, ".") {
|
||||||
|
e = "." + e
|
||||||
|
}
|
||||||
|
exts = append(exts, e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
foundSourceIDs := make(map[string]bool)
|
||||||
|
|
||||||
|
filepath.WalkDir(targetPath, func(path string, d fs.DirEntry, err error) error {
|
||||||
|
if err != nil || d.IsDir() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.Contains(path, ".git") {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
ext := filepath.Ext(path)
|
||||||
|
validExt := false
|
||||||
|
for _, e := range exts {
|
||||||
|
if ext == e {
|
||||||
|
validExt = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !validExt {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
f, err := os.Open(path)
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
|
||||||
|
var taskName string
|
||||||
|
var taskCron string
|
||||||
|
|
||||||
|
scanner := bufio.NewScanner(f)
|
||||||
|
var firstCommentLine string
|
||||||
|
inBlockComment := false
|
||||||
|
|
||||||
|
// 特殊处理:针对当前文件名的 Cron 关联正则表达式 (对标青龙 perl 逻辑)
|
||||||
|
// 寻找类似 "// 0 0 * * * jd_task.js" 的行
|
||||||
|
fileNameEscaped := regexp.QuoteMeta(filepath.Base(path))
|
||||||
|
associatedCronRegex := regexp.MustCompile(fmt.Sprintf(`(?i)(?:^|[ \t\*\//])(([0-9\*\/\-,L?#]+[ \t]+){4,5}[0-9\*\/\-,L?#]+)[ \t,"]+.*%s`, fileNameEscaped))
|
||||||
|
|
||||||
|
for i := 0; i < 150 && scanner.Scan(); i++ { // QL 扫描范围较大
|
||||||
|
line := strings.TrimSpace(scanner.Text())
|
||||||
|
if line == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理块注释开始/结束
|
||||||
|
if strings.HasPrefix(line, "/*") {
|
||||||
|
inBlockComment = true
|
||||||
|
line = strings.TrimPrefix(line, "/*")
|
||||||
|
line = strings.TrimPrefix(line, "*")
|
||||||
|
line = strings.TrimSpace(line)
|
||||||
|
}
|
||||||
|
if strings.HasSuffix(line, "*/") {
|
||||||
|
inBlockComment = false
|
||||||
|
line = strings.TrimSuffix(line, "*/")
|
||||||
|
line = strings.TrimSpace(line)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1. 尝试提取任务名称 (优先使用 Env)
|
||||||
|
if taskName == "" {
|
||||||
|
if envMatch := envRegex.FindStringSubmatch(line); len(envMatch) > 1 {
|
||||||
|
taskName = strings.TrimSpace(envMatch[1])
|
||||||
|
} else if strings.Contains(line, "name:") {
|
||||||
|
// 兼容 name: "xxx" 格式
|
||||||
|
nameRegex := regexp.MustCompile(`(?i)name:[ \t]*['"]([^'"]+)['"]`)
|
||||||
|
if nameMatch := nameRegex.FindStringSubmatch(line); len(nameMatch) > 1 {
|
||||||
|
taskName = strings.TrimSpace(nameMatch[1])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果还没找到名称,且在注释中,记录第一行非空注释作为备选名称
|
||||||
|
if taskName == "" && (inBlockComment || strings.HasPrefix(line, "//") || strings.HasPrefix(line, "*") || strings.HasPrefix(line, "#")) {
|
||||||
|
cleanLine := line
|
||||||
|
if strings.HasPrefix(line, "//") {
|
||||||
|
cleanLine = strings.TrimPrefix(line, "//")
|
||||||
|
} else if strings.HasPrefix(line, "#") {
|
||||||
|
cleanLine = strings.TrimPrefix(line, "#")
|
||||||
|
} else if strings.HasPrefix(line, "*") {
|
||||||
|
cleanLine = strings.TrimPrefix(line, "*")
|
||||||
|
}
|
||||||
|
cleanLine = strings.TrimSpace(cleanLine)
|
||||||
|
|
||||||
|
// 排除掉包含 "Env" 或 "cron" 的行, 且排除掉可能是路径或URL的行
|
||||||
|
if cleanLine != "" && !strings.Contains(strings.ToLower(cleanLine), "env") &&
|
||||||
|
!strings.Contains(strings.ToLower(cleanLine), "cron") &&
|
||||||
|
!strings.Contains(cleanLine, "http") &&
|
||||||
|
!strings.Contains(cleanLine, "/") &&
|
||||||
|
firstCommentLine == "" {
|
||||||
|
// 且排除掉纯 cron 表达式
|
||||||
|
if !cronRegex.MatchString(cleanLine) {
|
||||||
|
firstCommentLine = cleanLine
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 提取 Cron
|
||||||
|
if taskCron == "" {
|
||||||
|
// A. 优先查找关联了当前文件名的 Cron (对标 QL)
|
||||||
|
if assocMatch := associatedCronRegex.FindStringSubmatch(line); len(assocMatch) > 1 {
|
||||||
|
taskCron = strings.TrimSpace(assocMatch[1])
|
||||||
|
}
|
||||||
|
|
||||||
|
// B. 如果没找到,尝试普通的 cron: "..." 或 cron 表达式
|
||||||
|
if taskCron == "" {
|
||||||
|
if cronMatch := cronRegex.FindStringSubmatch(line); len(cronMatch) > 0 {
|
||||||
|
for _, m := range cronMatch[1:] {
|
||||||
|
if m != "" {
|
||||||
|
taskCron = strings.TrimSpace(m)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if taskName != "" && taskCron != "" {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果最后还是没找到 taskName,使用备选名称或文件名
|
||||||
|
if taskName == "" {
|
||||||
|
if firstCommentLine != "" {
|
||||||
|
taskName = firstCommentLine
|
||||||
|
} else {
|
||||||
|
taskName = strings.TrimSuffix(filepath.Base(path), ext)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 应用白名单 / 黑名单过滤 (逻辑对标青龙)
|
||||||
|
// relRepoPath 是相对于仓库根目录的路径,filename 是文件名
|
||||||
|
relRepoPath, _ := filepath.Rel(targetPath, path)
|
||||||
|
filename := filepath.Base(path)
|
||||||
|
|
||||||
|
// 只有在显式设置了白名单时才进行白名单校验 (青龙行为)
|
||||||
|
if repoCfg.WhitelistPaths != "" {
|
||||||
|
if !matchesQLPattern(relRepoPath, filename, repoCfg.WhitelistPaths) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 校验黑名单
|
||||||
|
if repoCfg.Blacklist != "" {
|
||||||
|
if matchesQLPattern(relRepoPath, filename, repoCfg.Blacklist) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if taskName != "" && taskCron != "" {
|
||||||
|
// 获取脚本相对于数据目录的路径
|
||||||
|
absScriptsDir, _ := filepath.Abs(constant.ScriptsWorkDir)
|
||||||
|
absPath, _ := filepath.Abs(path)
|
||||||
|
|
||||||
|
// 计算 SourceID: 相对于脚本目录的完整路径,并清洗特殊符号
|
||||||
|
relPath, _ := filepath.Rel(absScriptsDir, absPath)
|
||||||
|
sourceID := sanitizeIdentifier(relPath)
|
||||||
|
|
||||||
|
// 替换绝对路径为代号 $SCRIPTS_DIR$
|
||||||
|
displayPath := path
|
||||||
|
displayWorkDir := targetPath
|
||||||
|
if strings.HasPrefix(absPath, absScriptsDir) {
|
||||||
|
displayPath = filepath.Join("$SCRIPTS_DIR$", relPath)
|
||||||
|
// 获取目录路径
|
||||||
|
relDir, _ := filepath.Rel(absScriptsDir, targetPath)
|
||||||
|
displayWorkDir = filepath.Join("$SCRIPTS_DIR$", relDir)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Found task, save it
|
||||||
|
command := getCommandByExt(ext, displayPath)
|
||||||
|
|
||||||
|
// 注册任务默认开启“全量环境变量注入”,以适配大多数脚本
|
||||||
|
defaultTaskConfig := `{"$task_all_envs":true}`
|
||||||
|
|
||||||
|
// See if task exists (优先通过 SourceID 匹配)
|
||||||
|
var existing models.Task
|
||||||
|
err := database.DB.Where("source_id = ?", sourceID).First(&existing).Error
|
||||||
|
if err != nil {
|
||||||
|
// 降级使用 command + tag 匹配 (兼容旧数据)
|
||||||
|
err = database.DB.Where("command = ? AND tags LIKE ?", command, "%"+tag+"%").First(&existing).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
if err == nil {
|
||||||
|
// update
|
||||||
|
existing.Name = taskName
|
||||||
|
existing.Schedule = normalizeCron(taskCron)
|
||||||
|
existing.Languages = repoTask.Languages
|
||||||
|
existing.SourceID = sourceID
|
||||||
|
existing.RepoTaskID = repoTask.ID
|
||||||
|
existing.WorkDir = displayWorkDir
|
||||||
|
// 如果原配置为空或者是 {},则应用默认配置
|
||||||
|
if string(existing.Config) == "" || string(existing.Config) == "{}" {
|
||||||
|
existing.Config = models.BigText(defaultTaskConfig)
|
||||||
|
}
|
||||||
|
database.DB.Save(&existing)
|
||||||
|
|
||||||
|
if existing.Enabled && es != nil {
|
||||||
|
es.AddCronTask(&existing)
|
||||||
|
}
|
||||||
|
foundSourceIDs[sourceID] = true
|
||||||
|
} else {
|
||||||
|
// create new
|
||||||
|
newTask := &models.Task{
|
||||||
|
Name: taskName,
|
||||||
|
Command: models.BigText(command),
|
||||||
|
Schedule: normalizeCron(taskCron),
|
||||||
|
Type: "task",
|
||||||
|
TriggerType: constant.TriggerTypeCron,
|
||||||
|
Tags: tag,
|
||||||
|
Languages: repoTask.Languages,
|
||||||
|
Timeout: repoTask.Timeout,
|
||||||
|
Config: models.BigText(defaultTaskConfig),
|
||||||
|
Enabled: true,
|
||||||
|
WorkDir: displayWorkDir,
|
||||||
|
SourceID: sourceID,
|
||||||
|
RepoTaskID: repoTask.ID,
|
||||||
|
}
|
||||||
|
newTask.ID = utils.GenerateID()
|
||||||
|
database.DB.Create(newTask)
|
||||||
|
if es != nil {
|
||||||
|
es.AddCronTask(newTask)
|
||||||
|
}
|
||||||
|
foundSourceIDs[sourceID] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
// 清理该仓库任务下不再存在的旧脚本任务
|
||||||
|
var oldTasks []models.Task
|
||||||
|
if err := database.DB.Where("repo_task_id = ?", repoTask.ID).Find(&oldTasks).Error; err == nil {
|
||||||
|
for _, ot := range oldTasks {
|
||||||
|
if !foundSourceIDs[ot.SourceID] {
|
||||||
|
if es != nil {
|
||||||
|
if es.taskService != nil {
|
||||||
|
es.taskService.DeleteTask(ot.ID)
|
||||||
|
}
|
||||||
|
es.RemoveCronTask(ot.ID)
|
||||||
|
} else {
|
||||||
|
// Fallback if es is nil (which shouldn't happen, but just in case)
|
||||||
|
database.DB.Unscoped().Where("id = ?", ot.ID).Delete(&models.Task{})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func sanitizeIdentifier(s string) string {
|
||||||
|
// 将所有非字母数字替换为下划线
|
||||||
|
reg := regexp.MustCompile(`[^a-zA-Z0-9]+`)
|
||||||
|
res := reg.ReplaceAllString(s, "_")
|
||||||
|
return strings.ToLower(strings.Trim(res, "_"))
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizeCron(cron string) string {
|
||||||
|
fields := strings.Fields(cron)
|
||||||
|
if len(fields) == 5 {
|
||||||
|
return "0 " + cron
|
||||||
|
}
|
||||||
|
return cron
|
||||||
|
}
|
||||||
|
|
||||||
|
func pathExists(path string) bool {
|
||||||
|
_, err := os.Stat(path)
|
||||||
|
return err == nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func isDir(path string) bool {
|
||||||
|
info, err := os.Stat(path)
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return info.IsDir()
|
||||||
|
}
|
||||||
|
|
||||||
|
func getCommandByExt(ext, path string) string {
|
||||||
|
switch ext {
|
||||||
|
case ".js", ".ts":
|
||||||
|
return fmt.Sprintf("node %s", path)
|
||||||
|
case ".py":
|
||||||
|
return fmt.Sprintf("python %s", path)
|
||||||
|
case ".sh":
|
||||||
|
return fmt.Sprintf("bash %s", path)
|
||||||
|
case ".php":
|
||||||
|
return fmt.Sprintf("php %s", path)
|
||||||
|
}
|
||||||
|
return path
|
||||||
|
}
|
||||||
|
|
||||||
|
func matchesQLPattern(rel, filename string, keywordsStr string) bool {
|
||||||
|
if keywordsStr == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
keywords := splitKeywords(keywordsStr)
|
||||||
|
for _, k := range keywords {
|
||||||
|
// 1. 尝试作为正则整体进行匹配,默认不区分大小写 (?i)
|
||||||
|
pattern := k
|
||||||
|
if !strings.HasPrefix(pattern, "(?i)") {
|
||||||
|
pattern = "(?i)" + pattern
|
||||||
|
}
|
||||||
|
|
||||||
|
reg, err := regexp.Compile(pattern)
|
||||||
|
if err == nil {
|
||||||
|
// 优先匹配文件名(解决 ^jd[^_] 这种锚点在相对路径下失效的问题)
|
||||||
|
if reg.MatchString(filename) || reg.MatchString(rel) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// 回退逻辑:全小写包含判断
|
||||||
|
kLower := strings.ToLower(k)
|
||||||
|
if strings.Contains(strings.ToLower(rel), kLower) || strings.Contains(strings.ToLower(filename), kLower) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func splitKeywords(s string) []string {
|
||||||
|
if s == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var parts []string
|
||||||
|
if strings.Contains(s, "|") {
|
||||||
|
parts = strings.Split(s, "|")
|
||||||
|
} else if strings.Contains(s, ",") {
|
||||||
|
parts = strings.Split(s, ",")
|
||||||
|
} else {
|
||||||
|
parts = []string{s}
|
||||||
|
}
|
||||||
|
|
||||||
|
var res []string
|
||||||
|
for _, p := range parts {
|
||||||
|
p = strings.TrimSpace(p)
|
||||||
|
if p != "" {
|
||||||
|
res = append(res, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
@@ -13,7 +13,15 @@ func NewTaskService() *TaskService {
|
|||||||
return &TaskService{}
|
return &TaskService{}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ts *TaskService) CreateTask(name, command, schedule string, timeout int, workDir, cleanConfig, envs, taskType, config string, agentID *string, languages []map[string]string, triggerType string, tags string, retryCount int, retryInterval int, randomRange int) *models.Task {
|
func (ts *TaskService) GetTaskBySourceID(sourceID string) *models.Task {
|
||||||
|
var task models.Task
|
||||||
|
if err := database.DB.Where("source_id = ?", sourceID).First(&task).Error; err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return &task
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ts *TaskService) CreateTask(name, command, schedule string, timeout int, workDir, cleanConfig, envs, taskType, config string, agentID *string, languages []map[string]string, triggerType string, tags string, retryCount int, retryInterval int, randomRange int, sourceID string) *models.Task {
|
||||||
if taskType == "" {
|
if taskType == "" {
|
||||||
taskType = "task"
|
taskType = "task"
|
||||||
}
|
}
|
||||||
@@ -39,6 +47,7 @@ func (ts *TaskService) CreateTask(name, command, schedule string, timeout int, w
|
|||||||
RetryCount: retryCount,
|
RetryCount: retryCount,
|
||||||
RetryInterval: retryInterval,
|
RetryInterval: retryInterval,
|
||||||
RandomRange: randomRange,
|
RandomRange: randomRange,
|
||||||
|
SourceID: sourceID,
|
||||||
CreatedAt: models.Now(),
|
CreatedAt: models.Now(),
|
||||||
UpdatedAt: models.Now(),
|
UpdatedAt: models.Now(),
|
||||||
}
|
}
|
||||||
@@ -88,7 +97,7 @@ func (ts *TaskService) GetTaskByID(id string) *models.Task {
|
|||||||
return &task
|
return &task
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ts *TaskService) UpdateTask(id string, name, command, schedule string, timeout int, workDir, cleanConfig, envs string, enabled bool, taskType, config string, agentID *string, languages []map[string]string, triggerType string, tags string, retryCount int, retryInterval int, randomRange int) *models.Task {
|
func (ts *TaskService) UpdateTask(id string, name, command, schedule string, timeout int, workDir, cleanConfig, envs string, enabled bool, taskType, config string, agentID *string, languages []map[string]string, triggerType string, tags string, retryCount int, retryInterval int, randomRange int, sourceID string) *models.Task {
|
||||||
var task models.Task
|
var task models.Task
|
||||||
if err := database.DB.Where("id = ?", id).First(&task).Error; err != nil {
|
if err := database.DB.Where("id = ?", id).First(&task).Error; err != nil {
|
||||||
return nil
|
return nil
|
||||||
@@ -114,12 +123,15 @@ func (ts *TaskService) UpdateTask(id string, name, command, schedule string, tim
|
|||||||
if triggerType != "" {
|
if triggerType != "" {
|
||||||
task.TriggerType = triggerType
|
task.TriggerType = triggerType
|
||||||
}
|
}
|
||||||
|
if sourceID != "" {
|
||||||
|
task.SourceID = sourceID
|
||||||
|
}
|
||||||
|
|
||||||
database.DB.Model(&task).Select(
|
database.DB.Model(&task).Select(
|
||||||
"Name", "Command", "Tags", "Schedule", "Timeout", "WorkDir",
|
"Name", "Command", "Tags", "Schedule", "Timeout", "WorkDir",
|
||||||
"CleanConfig", "Envs", "Enabled", "AgentID", "Languages",
|
"CleanConfig", "Envs", "Enabled", "AgentID", "Languages",
|
||||||
"RetryCount", "RetryInterval", "RandomRange", "Type",
|
"RetryCount", "RetryInterval", "RandomRange", "Type",
|
||||||
"TriggerType", "Config",
|
"TriggerType", "Config", "SourceID",
|
||||||
).Updates(&task)
|
).Updates(&task)
|
||||||
return &task
|
return &task
|
||||||
}
|
}
|
||||||
@@ -131,3 +143,11 @@ func (ts *TaskService) DeleteTask(id string) bool {
|
|||||||
result := database.DB.Unscoped().Where("id = ?", id).Delete(&models.Task{})
|
result := database.DB.Unscoped().Where("id = ?", id).Delete(&models.Task{})
|
||||||
return result.RowsAffected > 0
|
return result.RowsAffected > 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (ts *TaskService) BatchDeleteTasks(ids []string) int64 {
|
||||||
|
// 同时删除关联的通知推送设置
|
||||||
|
database.DB.Where("type = ? AND data_id IN ?", constant.BindingTypeTask, ids).Delete(&models.NotifyBinding{})
|
||||||
|
|
||||||
|
result := database.DB.Unscoped().Where("id IN ?", ids).Delete(&models.Task{})
|
||||||
|
return result.RowsAffected
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
# 更新日志 ☕
|
||||||
|
|
||||||
|
本页面记录了白虎面板的主要版本更新历史。
|
||||||
|
|
||||||
|
## 最近更新概览
|
||||||
|
|
||||||
|
### 2026.03.19 - 仓库同步增强 (ql repo 兼容)
|
||||||
|
- **青龙指令兼容**:深度支持青龙仓库格式指令,支持自动解析脚本注释并同步为面板任务。
|
||||||
|
- **高级过滤逻辑**:支持基于正则的白名单、黑名单及依赖文件匹配特性。
|
||||||
|
- **解析器优化**:优化了定时任务 Cron 规则解析逻辑,修正了带 `#` 注释行的识别问题。
|
||||||
|
|
||||||
|
### 2026.03.05 - API 文档重构
|
||||||
|
- **OpenAPI 认证体系**:支持站点级 Token 配置与 Basic Auth 保护。
|
||||||
|
- **自定义 UI**:新增设计感十足的全局 **404 页面**。
|
||||||
|
|
||||||
|
### 2026.03.04 - 消息推送系统重构
|
||||||
|
- **原生内置**:全新原生支持企业微信、钉钉、飞书、Telegram、Bark、邮件等十余种主流渠道。
|
||||||
|
- **事件捕获**:接入系统级事件通知自动捕获,告别原有必配外部推送服务的繁琐历史。
|
||||||
|
|
||||||
|
### 2026.02.13 - 任务执行引擎重构
|
||||||
|
- **深度集成 Mise**:支持 Python, Node.js, Go, Rust, PHP 等几乎所有主流语言的动态安装与多版本切换。
|
||||||
|
- **依赖管理**:同步上线跨语言统一依赖管理系统。
|
||||||
|
|
||||||
|
### 2026.02.11 - 安全性增强
|
||||||
|
- **随机密码策略**:首次启动使用随机密码并打印在日志中。
|
||||||
|
- **暴力破解防护**:登录接口增加防暴力破解。
|
||||||
|
- **路径遍历防护**:文件系统操作增加路径穿越锁定。
|
||||||
|
|
||||||
|
### 2026.02.10 - 任务调度重构
|
||||||
|
- **调度性能**:重写了并发控制逻辑,完善了任务队列。
|
||||||
|
- **体验优化**:优化文件树交互体验,支持任务执行实时日志流。
|
||||||
|
|
||||||
|
### 2026.02.06 - 镜像扩展
|
||||||
|
- **Debian 13 支持**:增加对 Debian 13 (Trixie) 镜像支持,整理 Docker 目录结构。
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
package utils
|
||||||
|
|
||||||
|
import "strings"
|
||||||
|
|
||||||
|
// GetRepoIdentifier 返回根据仓库URL和分支生成的作者_仓库名标识符
|
||||||
|
func GetRepoIdentifier(url string, branch string) string {
|
||||||
|
url = strings.TrimSuffix(url, ".git")
|
||||||
|
url = strings.TrimSuffix(url, "/")
|
||||||
|
|
||||||
|
repoName := url[strings.LastIndex(url, "/")+1:]
|
||||||
|
|
||||||
|
author := ""
|
||||||
|
lastSlash := strings.LastIndex(url, "/")
|
||||||
|
if lastSlash != -1 {
|
||||||
|
prefix := url[:lastSlash]
|
||||||
|
if strings.Contains(prefix, ":") {
|
||||||
|
parts := strings.Split(prefix, ":")
|
||||||
|
prefix = parts[len(parts)-1]
|
||||||
|
}
|
||||||
|
lastSlashPrefix := strings.LastIndex(prefix, "/")
|
||||||
|
if lastSlashPrefix != -1 {
|
||||||
|
author = prefix[lastSlashPrefix+1:]
|
||||||
|
} else {
|
||||||
|
author = prefix
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if dotIdx := strings.LastIndex(author, "."); dotIdx != -1 {
|
||||||
|
author = author[dotIdx+1:]
|
||||||
|
}
|
||||||
|
|
||||||
|
identifier := ""
|
||||||
|
if author != "" {
|
||||||
|
identifier = author + "_" + repoName
|
||||||
|
} else {
|
||||||
|
identifier = repoName
|
||||||
|
}
|
||||||
|
|
||||||
|
if branch != "" && branch != "master" && branch != "main" {
|
||||||
|
identifier = identifier + "_" + branch
|
||||||
|
}
|
||||||
|
|
||||||
|
// Replace any invalid characters for tags or paths
|
||||||
|
identifier = strings.ReplaceAll(identifier, "/", "_")
|
||||||
|
identifier = strings.ReplaceAll(identifier, ".", "_")
|
||||||
|
return identifier
|
||||||
|
}
|
||||||
Generated
+2400
-4
File diff suppressed because it is too large
Load Diff
+15
-1
@@ -1,6 +1,20 @@
|
|||||||
{
|
{
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"date-fns": "^4.1.0"
|
"axios": "^1.7.4",
|
||||||
|
"cheerio": "^1.0.0",
|
||||||
|
"crypto-js": "^4.2.0",
|
||||||
|
"date-fns": "^3.6.0",
|
||||||
|
"dotenv": "^17.3.1",
|
||||||
|
"ds": "^2.0.2",
|
||||||
|
"got": "^11.8.6",
|
||||||
|
"https-proxy-agent": "^7.0.5",
|
||||||
|
"jsdom": "^24.1.1",
|
||||||
|
"moment": "^2.30.1",
|
||||||
|
"png-js": "^1.0.0",
|
||||||
|
"request": "^2.88.2",
|
||||||
|
"sharp": "^0.34.5",
|
||||||
|
"tough-cookie": "^6.0.1",
|
||||||
|
"tunnel": "^0.0.6"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -71,6 +71,15 @@ export const api = {
|
|||||||
create: (data: Partial<Task>) => request<Task>('/tasks', { method: 'POST', body: JSON.stringify(data) }),
|
create: (data: Partial<Task>) => request<Task>('/tasks', { method: 'POST', body: JSON.stringify(data) }),
|
||||||
update: (id: string, data: Partial<Task>) => request<Task>(`/tasks/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
|
update: (id: string, data: Partial<Task>) => request<Task>(`/tasks/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
|
||||||
delete: (id: string) => request(`/tasks/${id}`, { method: 'DELETE' }),
|
delete: (id: string) => request(`/tasks/${id}`, { method: 'DELETE' }),
|
||||||
|
batchDelete: (ids: string[]) => request<{ count: number }>('/tasks/batch-delete', { method: 'POST', body: JSON.stringify({ ids }) }),
|
||||||
|
batchDeleteByQuery: (params?: { name?: string, agent_id?: string, tags?: string, type?: string }) => {
|
||||||
|
const query = new URLSearchParams()
|
||||||
|
if (params?.name) query.append('name', params.name)
|
||||||
|
if (params?.agent_id) query.append('agent_id', params.agent_id)
|
||||||
|
if (params?.tags) query.append('tags', params.tags)
|
||||||
|
if (params?.type && params.type !== 'all') query.append('type', params.type)
|
||||||
|
return request<{ count: number }>(`/tasks/batch-by-query?${query.toString()}`, { method: 'DELETE' })
|
||||||
|
},
|
||||||
execute: (id: string) => request<ExecutionResult>(`/execute/task/${id}`, { method: 'POST' }),
|
execute: (id: string) => request<ExecutionResult>(`/execute/task/${id}`, { method: 'POST' }),
|
||||||
stop: (logID: string) => request(`/tasks/stop/${logID}`, { method: 'POST' })
|
stop: (logID: string) => request(`/tasks/stop/${logID}`, { method: 'POST' })
|
||||||
},
|
},
|
||||||
@@ -138,6 +147,7 @@ export const api = {
|
|||||||
request('/settings/scheduler', { method: 'PUT', body: JSON.stringify(data) }),
|
request('/settings/scheduler', { method: 'PUT', body: JSON.stringify(data) }),
|
||||||
getPaths: () => request<{ scripts_dir: string }>('/settings/paths'),
|
getPaths: () => request<{ scripts_dir: string }>('/settings/paths'),
|
||||||
getAbout: () => request<AboutInfo>('/settings/about'),
|
getAbout: () => request<AboutInfo>('/settings/about'),
|
||||||
|
getChangelog: () => request<string>('/settings/changelog'),
|
||||||
get: (section: string, key: string) => request<string>(`/settings/${section}/${key}`),
|
get: (section: string, key: string) => request<string>(`/settings/${section}/${key}`),
|
||||||
generateToken: (section: string, key: string) =>
|
generateToken: (section: string, key: string) =>
|
||||||
request<string>(`/settings/${section}/${key}/generate`, { method: 'POST' }),
|
request<string>(`/settings/${section}/${key}/generate`, { method: 'POST' }),
|
||||||
@@ -352,7 +362,12 @@ export interface RepoConfig {
|
|||||||
proxy_url: string
|
proxy_url: string
|
||||||
auth_token: string
|
auth_token: string
|
||||||
whitelist_paths?: string
|
whitelist_paths?: string
|
||||||
|
blacklist?: string
|
||||||
|
dependence?: string
|
||||||
|
extensions?: string
|
||||||
|
auto_add_cron?: boolean
|
||||||
concurrency?: number
|
concurrency?: number
|
||||||
|
repo_source?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ExecutionResult {
|
export interface ExecutionResult {
|
||||||
@@ -439,6 +454,7 @@ export interface LogDetail {
|
|||||||
|
|
||||||
export interface AboutInfo {
|
export interface AboutInfo {
|
||||||
version: string
|
version: string
|
||||||
|
remote_version?: string
|
||||||
build_time: string
|
build_time: string
|
||||||
mem_usage: string
|
mem_usage: string
|
||||||
goroutines: number
|
goroutines: number
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { ref, onMounted, computed, watch } from 'vue'
|
import { ref, onMounted, watch } from 'vue'
|
||||||
import { useRoute } from 'vue-router'
|
import { useRoute } from 'vue-router'
|
||||||
import { TASK_STATUS, TASK_TYPE } from '@/constants'
|
import { TASK_STATUS, TASK_TYPE } from '@/constants'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
@@ -7,11 +7,10 @@ import { Input } from '@/components/ui/input'
|
|||||||
import Pagination from '@/components/Pagination.vue'
|
import Pagination from '@/components/Pagination.vue'
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||||
import {
|
import {
|
||||||
RefreshCw, X, Search, Maximize2, GitBranch, Terminal,
|
RefreshCw, X, Search, GitBranch, Terminal,
|
||||||
CheckCircle2, XCircle, AlertCircle, Ban, Clock, Zap as ZapIcon, Check, Trash2
|
CheckCircle2, XCircle, AlertCircle, Ban, Clock, Zap as ZapIcon, Check, Trash2, Maximize2
|
||||||
} from 'lucide-vue-next'
|
} from 'lucide-vue-next'
|
||||||
import LogViewer from './LogViewer.vue'
|
import LogViewer from './LogViewer.vue'
|
||||||
import LogTerminal from '@/components/LogTerminal.vue'
|
|
||||||
import { api, type TaskLog } from '@/api'
|
import { api, type TaskLog } from '@/api'
|
||||||
import { Badge } from '@/components/ui/badge'
|
import { Badge } from '@/components/ui/badge'
|
||||||
import {
|
import {
|
||||||
@@ -40,29 +39,15 @@ const filterStatus = ref<string | undefined>(undefined)
|
|||||||
const currentPage = ref(1)
|
const currentPage = ref(1)
|
||||||
const total = ref(0)
|
const total = ref(0)
|
||||||
|
|
||||||
let searchTimer: ReturnType<typeof setTimeout> | null = null
|
|
||||||
let durationTimer: ReturnType<typeof setInterval> | null = null
|
|
||||||
|
|
||||||
// 全屏查看
|
|
||||||
const showFullscreen = ref(false)
|
|
||||||
|
|
||||||
// 清除所有日志弹窗
|
|
||||||
const showClearDialog = ref(false)
|
|
||||||
|
|
||||||
// 删除单条日志弹窗
|
|
||||||
const showDeleteDialog = ref(false)
|
const showDeleteDialog = ref(false)
|
||||||
const deleteLogId = ref<string | null>(null)
|
const deleteLogId = ref<string | null>(null)
|
||||||
|
const showFullscreen = ref(false)
|
||||||
|
const showClearDialog = ref(false)
|
||||||
|
|
||||||
const wsContent = ref('')
|
let searchTimer: ReturnType<typeof setTimeout> | null = null
|
||||||
const isWsLoading = ref(false)
|
|
||||||
let logSocket: WebSocket | null = null
|
|
||||||
|
|
||||||
const { resolvedTheme } = useTheme()
|
const { resolvedTheme } = useTheme()
|
||||||
|
|
||||||
const decompressedOutput = computed(() => {
|
|
||||||
return wsContent.value
|
|
||||||
})
|
|
||||||
|
|
||||||
async function loadLogs() {
|
async function loadLogs() {
|
||||||
try {
|
try {
|
||||||
const params: { page: number; page_size: number; task_id?: string; task_name?: string; status?: string } = {
|
const params: { page: number; page_size: number; task_id?: string; task_name?: string; status?: string } = {
|
||||||
@@ -105,106 +90,11 @@ function handlePageChange(page: number) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function selectLog(log: TaskLog) {
|
async function selectLog(log: TaskLog) {
|
||||||
if (logSocket) {
|
|
||||||
logSocket.onopen = null
|
|
||||||
logSocket.onmessage = null
|
|
||||||
logSocket.onerror = null
|
|
||||||
logSocket.onclose = null
|
|
||||||
logSocket.close()
|
|
||||||
}
|
|
||||||
|
|
||||||
// 清理旧定时器
|
|
||||||
if (durationTimer) {
|
|
||||||
clearInterval(durationTimer)
|
|
||||||
durationTimer = null
|
|
||||||
}
|
|
||||||
|
|
||||||
selectedLog.value = log
|
selectedLog.value = log
|
||||||
|
|
||||||
// 如果是运行中状态,启动定时器轮询最新日志信息(主要是更新耗时)
|
|
||||||
if (log.status === TASK_STATUS.RUNNING) {
|
|
||||||
const updateLog = async () => {
|
|
||||||
try {
|
|
||||||
const res = await api.logs.get(log.id)
|
|
||||||
if (res && selectedLog.value && selectedLog.value.id === log.id) {
|
|
||||||
// 只更新需要变动的字段
|
|
||||||
selectedLog.value.duration = res.duration
|
|
||||||
// 同步更新列表中的数据
|
|
||||||
const listItem = logs.value.find(l => l.id === log.id)
|
|
||||||
if (listItem) {
|
|
||||||
listItem.duration = res.duration
|
|
||||||
}
|
|
||||||
// 如果状态变了,更新状态并停止轮询
|
|
||||||
if (res.status !== TASK_STATUS.RUNNING) {
|
|
||||||
selectedLog.value.status = res.status
|
|
||||||
selectedLog.value.end_time = res.end_time
|
|
||||||
if (listItem) {
|
|
||||||
listItem.status = res.status
|
|
||||||
listItem.end_time = res.end_time
|
|
||||||
}
|
|
||||||
if (durationTimer) {
|
|
||||||
clearInterval(durationTimer)
|
|
||||||
durationTimer = null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch { /* ignore */ }
|
|
||||||
}
|
|
||||||
durationTimer = setInterval(updateLog, 3000)
|
|
||||||
}
|
|
||||||
|
|
||||||
wsContent.value = ''
|
|
||||||
isWsLoading.value = true
|
|
||||||
|
|
||||||
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
|
|
||||||
const host = window.location.host
|
|
||||||
const baseUrl = (window as any).__BASE_URL__ || ''
|
|
||||||
const apiVersion = (window as any).__API_VERSION__ || '/api/v1'
|
|
||||||
const wsUrl = `${protocol}//${host}${baseUrl}${apiVersion}/logs/ws?log_id=${log.id}`
|
|
||||||
|
|
||||||
logSocket = new WebSocket(wsUrl)
|
|
||||||
|
|
||||||
logSocket.onopen = () => {
|
|
||||||
isWsLoading.value = false
|
|
||||||
console.log('[LogWS] Connection opened')
|
|
||||||
}
|
|
||||||
|
|
||||||
logSocket.onmessage = (event) => {
|
|
||||||
isWsLoading.value = false
|
|
||||||
if (log.status !== TASK_STATUS.RUNNING) {
|
|
||||||
wsContent.value = event.data
|
|
||||||
} else {
|
|
||||||
wsContent.value += event.data
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
logSocket.onerror = (e) => {
|
|
||||||
isWsLoading.value = false
|
|
||||||
console.error('[LogWS] Connection error', e)
|
|
||||||
toast.error('日志连接异常')
|
|
||||||
}
|
|
||||||
|
|
||||||
logSocket.onclose = (e) => {
|
|
||||||
isWsLoading.value = false
|
|
||||||
console.log('[LogWS] Connection closed', e.code, e.reason)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function closeDetail() {
|
function closeDetail() {
|
||||||
if (durationTimer) {
|
|
||||||
clearInterval(durationTimer)
|
|
||||||
durationTimer = null
|
|
||||||
}
|
|
||||||
if (logSocket) {
|
|
||||||
logSocket.onopen = null
|
|
||||||
logSocket.onmessage = null
|
|
||||||
logSocket.onerror = null
|
|
||||||
logSocket.onclose = null
|
|
||||||
logSocket.close()
|
|
||||||
logSocket = null
|
|
||||||
}
|
|
||||||
selectedLog.value = null
|
selectedLog.value = null
|
||||||
wsContent.value = ''
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const isStopping = ref(false)
|
const isStopping = ref(false)
|
||||||
@@ -250,7 +140,6 @@ async function handleDeleteLog() {
|
|||||||
await api.logs.delete(deleteLogId.value)
|
await api.logs.delete(deleteLogId.value)
|
||||||
toast.success('该日志已删除')
|
toast.success('该日志已删除')
|
||||||
|
|
||||||
// 如果当前选中的是这条日志,关闭详情页
|
|
||||||
if (selectedLog.value?.id === deleteLogId.value) {
|
if (selectedLog.value?.id === deleteLogId.value) {
|
||||||
closeDetail()
|
closeDetail()
|
||||||
}
|
}
|
||||||
@@ -286,7 +175,6 @@ function getTaskTypeTitle(type: string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
// 从 URL 读取参数
|
|
||||||
const taskIdParam = route.query.task_id
|
const taskIdParam = route.query.task_id
|
||||||
if (taskIdParam) {
|
if (taskIdParam) {
|
||||||
filterTaskId.value = String(taskIdParam)
|
filterTaskId.value = String(taskIdParam)
|
||||||
@@ -297,82 +185,57 @@ onMounted(() => {
|
|||||||
}
|
}
|
||||||
loadLogs()
|
loadLogs()
|
||||||
})
|
})
|
||||||
|
|
||||||
// 监听路由变化
|
|
||||||
watch(() => route.query, (newQuery) => {
|
|
||||||
filterTaskId.value = newQuery.task_id ? String(newQuery.task_id) : undefined
|
|
||||||
filterStatus.value = newQuery.status ? String(newQuery.status) : undefined
|
|
||||||
currentPage.value = 1
|
|
||||||
loadLogs()
|
|
||||||
}, { deep: true })
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="space-y-6">
|
<div class="flex flex-col gap-4 h-full">
|
||||||
<div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
|
<!-- 头部工具栏 -->
|
||||||
<div>
|
<div class="flex flex-col md:flex-row md:items-center justify-between gap-4 shrink-0 px-1">
|
||||||
|
<div class="flex items-center gap-3">
|
||||||
<h2 class="text-xl sm:text-2xl font-bold tracking-tight">执行历史</h2>
|
<h2 class="text-xl sm:text-2xl font-bold tracking-tight">执行历史</h2>
|
||||||
<p class="text-muted-foreground text-sm">查看任务执行记录和日志</p>
|
|
||||||
</div>
|
</div>
|
||||||
<div class="flex items-center gap-2">
|
|
||||||
<div class="relative flex-1 sm:flex-none">
|
<div class="flex flex-col sm:flex-row gap-2.5 w-full md:w-auto">
|
||||||
<Search class="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
<div class="flex items-center gap-2 w-full sm:w-auto">
|
||||||
<Input v-model="filterKeyword" placeholder="搜索任务..." class="h-9 pl-9 w-full sm:w-40 md:w-56 text-sm"
|
<div class="relative flex-1 sm:flex-none">
|
||||||
@input="handleSearch" />
|
<Search class="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||||
</div>
|
<Input v-model="filterKeyword" placeholder="搜索任务名称..." class="h-9 pl-9 w-full sm:w-48 text-sm"
|
||||||
<div class="relative flex-1 sm:flex-none">
|
@input="handleSearch" />
|
||||||
|
</div>
|
||||||
<Select v-model="filterStatus" @update:model-value="handleStatusChange">
|
<Select v-model="filterStatus" @update:model-value="handleStatusChange">
|
||||||
<SelectTrigger class="h-9 w-full sm:w-28 text-sm">
|
<SelectTrigger class="h-9 w-[110px] text-sm shrink-0">
|
||||||
<SelectValue placeholder="状态" />
|
<SelectValue placeholder="所有状态" />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
<SelectItem value="all">所有状态</SelectItem>
|
<SelectItem value="all">所有状态</SelectItem>
|
||||||
<SelectItem value="running">正在运行</SelectItem>
|
<SelectItem :value="TASK_STATUS.SUCCESS">成功</SelectItem>
|
||||||
<SelectItem value="success">成功</SelectItem>
|
<SelectItem :value="TASK_STATUS.FAILED">失败</SelectItem>
|
||||||
<SelectItem value="failed">失败</SelectItem>
|
<SelectItem :value="TASK_STATUS.RUNNING">运行中</SelectItem>
|
||||||
<SelectItem value="timeout">超时</SelectItem>
|
<SelectItem :value="TASK_STATUS.PENDING">排队中</SelectItem>
|
||||||
<SelectItem value="cancelled">取消</SelectItem>
|
<SelectItem :value="TASK_STATUS.TIMEOUT">超时</SelectItem>
|
||||||
|
<SelectItem :value="TASK_STATUS.CANCELLED">已取消</SelectItem>
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
<Button variant="outline" size="icon" class="h-9 w-9 shrink-0" @click="loadLogs" title="刷新">
|
|
||||||
<RefreshCw class="h-4 w-4" />
|
<div class="flex items-center gap-2 shrink-0">
|
||||||
</Button>
|
<Button variant="outline" size="sm" class="h-9 gap-2 shadow-sm text-destructive border-destructive/20 hover:bg-destructive/10" @click="showClearDialog = true">
|
||||||
<Button variant="outline"
|
<Trash2 class="h-4 w-4" />
|
||||||
class="h-9 px-4 shrink-0 text-sm text-destructive hover:bg-destructive/10 hover:text-destructive border-destructive/20"
|
<span>清空日志</span>
|
||||||
@click="showClearDialog = true">
|
</Button>
|
||||||
<Trash2 class="h-4 w-4 sm:mr-2" /> <span class="hidden sm:inline" style="padding-left: 2px;">清空日志</span>
|
<Button variant="outline" size="icon" class="h-9 w-9 shadow-sm" @click="loadLogs" title="刷新">
|
||||||
</Button>
|
<RefreshCw class="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="flex flex-col lg:flex-row gap-4">
|
<!-- 主体区域 -->
|
||||||
|
<div class="flex-1 flex flex-col lg:flex-row gap-4 min-h-0">
|
||||||
<!-- 日志列表 -->
|
<!-- 日志列表 -->
|
||||||
<div class="flex-1 min-w-0 rounded-lg border bg-card overflow-hidden flex flex-col">
|
<div class="flex-1 min-w-0 rounded-lg border bg-card overflow-hidden flex flex-col">
|
||||||
<!-- 小屏表头 -->
|
<!-- 小屏表头 (省略) -->
|
||||||
<div
|
<div class="divide-y flex-1 overflow-y-auto">
|
||||||
class="flex sm:hidden items-center gap-2 px-3 py-2 border-b bg-muted/20 text-xs text-muted-foreground font-medium">
|
|
||||||
<span class="w-14 shrink-0">序号</span>
|
|
||||||
<span class="w-10 shrink-0 text-center">类型</span>
|
|
||||||
<span class="flex-1 min-w-0">任务名称</span>
|
|
||||||
<span class="w-8 shrink-0 text-center">状态</span>
|
|
||||||
<span class="w-12 text-right shrink-0">耗时</span>
|
|
||||||
<span class="w-8 text-center shrink-0"></span>
|
|
||||||
</div>
|
|
||||||
<!-- 大屏表头 -->
|
|
||||||
<div
|
|
||||||
class="hidden sm:flex items-center gap-4 px-4 h-11 border-b bg-muted/20 text-sm text-muted-foreground font-medium">
|
|
||||||
<span class="w-16 shrink-0">序号</span>
|
|
||||||
<span class="w-12 shrink-0 text-center">类型</span>
|
|
||||||
<span class="w-36 shrink-0">任务名称</span>
|
|
||||||
<span class="flex-1 min-w-0">命令</span>
|
|
||||||
<span class="w-12 shrink-0 text-center">状态</span>
|
|
||||||
<span class="w-16 text-right shrink-0">耗时</span>
|
|
||||||
<span v-if="!selectedLog" class="w-40 text-right shrink-0 hidden md:block">执行时间</span>
|
|
||||||
<span class="w-10 shrink-0 text-center"></span>
|
|
||||||
</div>
|
|
||||||
<!-- 列表 -->
|
|
||||||
<div class="divide-y flex-1">
|
|
||||||
<div v-if="logs.length === 0" class="text-sm text-muted-foreground text-center py-8">
|
<div v-if="logs.length === 0" class="text-sm text-muted-foreground text-center py-8">
|
||||||
暂无日志
|
暂无日志
|
||||||
</div>
|
</div>
|
||||||
@@ -380,240 +243,89 @@ watch(() => route.query, (newQuery) => {
|
|||||||
'cursor-pointer hover:bg-muted/30 transition-colors group',
|
'cursor-pointer hover:bg-muted/30 transition-colors group',
|
||||||
selectedLog?.id === log.id && 'bg-accent/50'
|
selectedLog?.id === log.id && 'bg-accent/50'
|
||||||
]" @click="selectLog(log)">
|
]" @click="selectLog(log)">
|
||||||
<!-- 小屏行 -->
|
<!-- 日志行内容 (保持原样) -->
|
||||||
<div class="flex sm:hidden items-center gap-2 px-3 py-2">
|
<div class="flex items-center gap-4 px-4 py-3">
|
||||||
<span class="w-14 shrink-0 text-muted-foreground text-xs">#{{ total - (currentPage - 1) * pageSize - index
|
<span class="w-16 shrink-0 text-muted-foreground text-sm">#{{ total - (currentPage - 1) * pageSize - index }}</span>
|
||||||
}}</span>
|
|
||||||
<span class="w-6 shrink-0 flex justify-center" :title="getTaskTypeTitle(log.task_type || 'task')">
|
|
||||||
<GitBranch v-if="log.task_type === TASK_TYPE.REPO" class="h-3.5 w-3.5 text-primary" />
|
|
||||||
<Terminal v-else class="h-3.5 w-3.5 text-primary" />
|
|
||||||
</span>
|
|
||||||
<span class="flex-1 min-w-0 font-medium truncate text-xs">{{ log.task_name }}</span>
|
|
||||||
<span class="w-8 flex justify-center shrink-0">
|
|
||||||
<div v-if="log.status === TASK_STATUS.SUCCESS"
|
|
||||||
class="h-5 w-5 rounded-full bg-green-500/10 flex items-center justify-center">
|
|
||||||
<Check class="h-3 w-3 text-green-500 stroke-[3]" />
|
|
||||||
</div>
|
|
||||||
<div v-else-if="log.status === TASK_STATUS.FAILED"
|
|
||||||
class="h-5 w-5 rounded-full bg-red-500/10 flex items-center justify-center">
|
|
||||||
<X class="h-3 w-3 text-red-500 stroke-[3]" />
|
|
||||||
</div>
|
|
||||||
<div v-else-if="log.status === TASK_STATUS.RUNNING"
|
|
||||||
class="h-5 w-5 rounded-full bg-yellow-500/10 flex items-center justify-center">
|
|
||||||
<ZapIcon class="h-3 w-3 text-yellow-500 fill-yellow-500 animate-pulse" />
|
|
||||||
</div>
|
|
||||||
<div v-else-if="log.status === TASK_STATUS.PENDING"
|
|
||||||
class="h-5 w-5 rounded-full bg-yellow-500/10 flex items-center justify-center">
|
|
||||||
<Clock class="h-3 w-3 text-yellow-500" />
|
|
||||||
</div>
|
|
||||||
<div v-else-if="log.status === TASK_STATUS.TIMEOUT"
|
|
||||||
class="h-5 w-5 rounded-full bg-orange-500/10 flex items-center justify-center">
|
|
||||||
<AlertCircle class="h-3 w-3 text-orange-500" />
|
|
||||||
</div>
|
|
||||||
<div v-else-if="log.status === TASK_STATUS.CANCELLED"
|
|
||||||
class="h-5 w-5 rounded-full bg-muted flex items-center justify-center">
|
|
||||||
<Ban class="h-3 w-3 text-muted-foreground" />
|
|
||||||
</div>
|
|
||||||
</span>
|
|
||||||
<span class="w-12 text-right shrink-0 text-muted-foreground text-xs">{{ formatDuration(log.duration)
|
|
||||||
}}</span>
|
|
||||||
<span class="w-8 shrink-0 flex justify-center opacity-100">
|
|
||||||
<Button variant="ghost" size="icon"
|
|
||||||
class="h-6 w-6 text-muted-foreground hover:text-destructive shrink-0"
|
|
||||||
@click.stop="confirmDeleteLog(log.id)" title="删除该日志">
|
|
||||||
<Trash2 class="h-3.5 w-3.5" />
|
|
||||||
</Button>
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<!-- 大屏行 -->
|
|
||||||
<div class="hidden sm:flex items-center gap-4 px-4 py-2">
|
|
||||||
<span class="w-16 shrink-0 text-muted-foreground text-sm">#{{ total - (currentPage - 1) * pageSize - index
|
|
||||||
}}</span>
|
|
||||||
<span class="w-10 shrink-0 flex justify-center" :title="getTaskTypeTitle(log.task_type || 'task')">
|
|
||||||
<GitBranch v-if="log.task_type === TASK_TYPE.REPO" class="h-4 w-4 text-primary" />
|
|
||||||
<Terminal v-else class="h-4 w-4 text-primary" />
|
|
||||||
</span>
|
|
||||||
<span class="w-36 shrink-0 font-medium truncate text-sm">{{ log.task_name }}</span>
|
<span class="w-36 shrink-0 font-medium truncate text-sm">{{ log.task_name }}</span>
|
||||||
<code class="flex-1 min-w-0 text-muted-foreground truncate text-xs bg-muted/40 px-2 py-1 rounded">
|
<code class="flex-1 min-w-0 text-muted-foreground truncate text-xs bg-muted/40 px-2 py-1 rounded">
|
||||||
<TextOverflow :text="log.command" title="执行命令" />
|
{{ log.command }}
|
||||||
</code>
|
</code>
|
||||||
<span class="w-12 flex justify-center shrink-0">
|
<Badge variant="outline" :class="getStatusBadgeClass(log.status)" class="shrink-0">
|
||||||
<div v-if="log.status === TASK_STATUS.SUCCESS"
|
{{ log.status }}
|
||||||
class="h-6 w-6 rounded-full bg-green-500/10 flex items-center justify-center">
|
</Badge>
|
||||||
<Check class="h-3.5 w-3.5 text-green-500 stroke-[3]" />
|
<span class="w-16 text-right shrink-0 text-muted-foreground text-xs">{{ formatDuration(log.duration) }}</span>
|
||||||
</div>
|
<Button variant="ghost" size="icon" class="h-8 w-8 text-muted-foreground hover:text-destructive" @click.stop="confirmDeleteLog(log.id)">
|
||||||
<div v-else-if="log.status === TASK_STATUS.FAILED"
|
<Trash2 class="h-4 w-4" />
|
||||||
class="h-6 w-6 rounded-full bg-red-500/10 flex items-center justify-center">
|
</Button>
|
||||||
<X class="h-3.5 w-3.5 text-red-500 stroke-[3]" />
|
|
||||||
</div>
|
|
||||||
<div v-else-if="log.status === TASK_STATUS.RUNNING"
|
|
||||||
class="h-6 w-6 rounded-full bg-yellow-500/10 flex items-center justify-center">
|
|
||||||
<ZapIcon class="h-3.5 w-3.5 text-yellow-500 fill-yellow-500 animate-pulse" />
|
|
||||||
</div>
|
|
||||||
<div v-else-if="log.status === TASK_STATUS.PENDING"
|
|
||||||
class="h-6 w-6 rounded-full bg-yellow-500/10 flex items-center justify-center">
|
|
||||||
<Clock class="h-3.5 w-3.5 text-yellow-500" />
|
|
||||||
</div>
|
|
||||||
<div v-else-if="log.status === TASK_STATUS.TIMEOUT"
|
|
||||||
class="h-6 w-6 rounded-full bg-orange-500/10 flex items-center justify-center">
|
|
||||||
<AlertCircle class="h-3.5 w-3.5 text-orange-500" />
|
|
||||||
</div>
|
|
||||||
<div v-else-if="log.status === TASK_STATUS.CANCELLED"
|
|
||||||
class="h-6 w-6 rounded-full bg-muted flex items-center justify-center">
|
|
||||||
<Ban class="h-3.5 w-3.5 text-muted-foreground" />
|
|
||||||
</div>
|
|
||||||
</span>
|
|
||||||
<span class="w-16 text-right shrink-0 text-muted-foreground text-xs">{{ formatDuration(log.duration)
|
|
||||||
}}</span>
|
|
||||||
<span v-if="!selectedLog"
|
|
||||||
class="w-40 text-right shrink-0 text-muted-foreground text-xs hidden md:block">{{ log.start_time ||
|
|
||||||
log.created_at }}</span>
|
|
||||||
<span class="w-10 shrink-0 flex justify-center opacity-100">
|
|
||||||
<Button variant="ghost" size="icon"
|
|
||||||
class="h-6 w-6 text-muted-foreground hover:text-destructive shrink-0"
|
|
||||||
@click.stop="confirmDeleteLog(log.id)" title="删除该日志">
|
|
||||||
<Trash2 class="h-3.5 w-3.5" />
|
|
||||||
</Button>
|
|
||||||
</span>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<!-- 分页 -->
|
<Pagination :total="total" :page="currentPage" @update:page="handlePageChange" class="p-4 border-t" />
|
||||||
<Pagination :total="total" :page="currentPage" @update:page="handlePageChange" />
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- 日志详情侧边栏 -->
|
<!-- 日志详情侧边栏 -->
|
||||||
<div v-if="selectedLog"
|
<div v-if="selectedLog"
|
||||||
class="w-full lg:w-[480px] rounded-lg border bg-card flex flex-col overflow-hidden shrink-0 max-h-[80vh] lg:max-h-none">
|
class="w-full lg:w-[480px] rounded-lg border bg-card flex flex-col overflow-hidden shrink-0 max-h-[80vh] lg:max-h-none">
|
||||||
<div class="flex items-center justify-between px-4 h-11 border-b bg-muted/20">
|
<div class="flex items-center justify-between px-4 h-11 border-b bg-muted/20">
|
||||||
<div class="flex items-center gap-2">
|
<span class="text-sm font-medium">日志详情</span>
|
||||||
<span class="text-sm font-medium text-muted-foreground">日志详情</span>
|
|
||||||
<Button v-if="selectedLog.status === TASK_STATUS.RUNNING" variant="destructive" size="sm"
|
|
||||||
class="h-6 px-2 text-[10px]" :disabled="isStopping" @click="stopTask">
|
|
||||||
{{ isStopping ? '停止中...' : '停止任务' }}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
<div class="flex items-center gap-1">
|
<div class="flex items-center gap-1">
|
||||||
<Button variant="ghost" size="icon" class="h-7 w-7 text-muted-foreground hover:text-destructive"
|
<Button variant="ghost" size="icon" @click="showFullscreen = true" title="全屏查看">
|
||||||
title="删除该日志" @click="confirmDeleteLog(selectedLog.id)">
|
<Maximize2 class="h-4 w-4" />
|
||||||
<Trash2 class="h-3.5 w-3.5" />
|
|
||||||
</Button>
|
</Button>
|
||||||
<Button variant="ghost" size="icon" class="h-7 w-7" @click="closeDetail" title="关闭">
|
<Button variant="ghost" size="icon" @click="closeDetail">
|
||||||
<X class="h-3.5 w-3.5" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="px-4 py-3 border-b space-y-2 text-sm">
|
|
||||||
<div class="flex justify-between items-center h-6">
|
|
||||||
<span class="text-muted-foreground">任务名称</span>
|
|
||||||
<span class="font-medium">{{ selectedLog.task_name }}</span>
|
|
||||||
</div>
|
|
||||||
<div class="flex justify-between items-center h-8">
|
|
||||||
<span class="text-muted-foreground">状态</span>
|
|
||||||
<Badge variant="outline" :class="[
|
|
||||||
'capitalize px-3 py-1 font-semibold rounded-full border shadow-sm transition-all duration-300',
|
|
||||||
getStatusBadgeClass(selectedLog.status)
|
|
||||||
]">
|
|
||||||
<div class="flex items-center gap-1.5">
|
|
||||||
<CheckCircle2 v-if="selectedLog.status === TASK_STATUS.SUCCESS" class="h-3.5 w-3.5" />
|
|
||||||
<XCircle v-else-if="selectedLog.status === TASK_STATUS.FAILED" class="h-3.5 w-3.5" />
|
|
||||||
<ZapIcon v-else-if="selectedLog.status === TASK_STATUS.RUNNING"
|
|
||||||
class="h-3.5 w-3.5 fill-current animate-pulse text-blue-500" />
|
|
||||||
<Clock v-else-if="selectedLog.status === TASK_STATUS.PENDING" class="h-3.5 w-3.5" />
|
|
||||||
<AlertCircle v-else-if="selectedLog.status === TASK_STATUS.TIMEOUT" class="h-3.5 w-3.5" />
|
|
||||||
<Ban v-else-if="selectedLog.status === TASK_STATUS.CANCELLED" class="h-3.5 w-3.5" />
|
|
||||||
<span class="text-xs tracking-wide uppercase">{{ selectedLog.status }}</span>
|
|
||||||
</div>
|
|
||||||
</Badge>
|
|
||||||
</div>
|
|
||||||
<div class="flex justify-between items-center h-6">
|
|
||||||
<span class="text-muted-foreground">耗时</span>
|
|
||||||
<span class="font-medium">{{ formatDuration(selectedLog.duration) }}</span>
|
|
||||||
</div>
|
|
||||||
<div class="flex justify-between items-center h-6">
|
|
||||||
<span class="text-muted-foreground">开始时间</span>
|
|
||||||
<span class="font-mono text-xs">{{ selectedLog.start_time || '-' }}</span>
|
|
||||||
</div>
|
|
||||||
<div class="flex justify-between items-center h-6">
|
|
||||||
<span class="text-muted-foreground">结束时间</span>
|
|
||||||
<span class="font-mono text-xs">{{ selectedLog.end_time || '-' }}</span>
|
|
||||||
</div>
|
|
||||||
<div class="pt-1.5">
|
|
||||||
<span class="text-muted-foreground block mb-1">执行命令</span>
|
|
||||||
<code
|
|
||||||
class="block font-mono bg-muted/40 px-3 py-2 rounded text-xs break-all border border-muted-foreground/10">
|
|
||||||
{{ selectedLog.command }}
|
|
||||||
</code>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="flex-1 flex flex-col overflow-hidden">
|
|
||||||
<div v-if="selectedLog.error" class="px-4 py-3 border-b bg-red-500/5 space-y-2 text-sm">
|
|
||||||
<div class="flex items-center gap-2 text-red-500 font-medium">
|
|
||||||
<X class="h-4 w-4" />
|
<X class="h-4 w-4" />
|
||||||
<span>系统错误</span>
|
|
||||||
</div>
|
|
||||||
<code class="block font-mono bg-red-500/10 text-red-600 px-2 py-1 rounded text-xs break-all">
|
|
||||||
{{ selectedLog.error }}
|
|
||||||
</code>
|
|
||||||
</div>
|
|
||||||
<div class="px-4 py-2.5 text-sm text-muted-foreground border-b bg-muted/20 flex items-center justify-between">
|
|
||||||
<span class="font-medium">日志输出</span>
|
|
||||||
<Button variant="ghost" size="icon" class="h-6 w-6" @click="showFullscreen = true" title="全屏查看">
|
|
||||||
<Maximize2 class="h-3.5 w-3.5" />
|
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
<div class="flex-1 overflow-hidden min-h-[160px] relative"
|
</div>
|
||||||
:class="resolvedTheme === 'dark' ? 'bg-zinc-950' : 'bg-zinc-100'" ref="sideLogContainer">
|
<div class="flex-1 overflow-y-auto p-4 space-y-4">
|
||||||
<LogTerminal v-if="decompressedOutput" :content="decompressedOutput" :theme="resolvedTheme" />
|
<!-- 详情信息 (任务名称, 状态, 耗时, 命令等) -->
|
||||||
<div v-else-if="!isWsLoading"
|
<div class="grid grid-cols-2 gap-y-3 text-sm">
|
||||||
class="absolute inset-0 flex items-center justify-center text-zinc-500 font-mono text-xs italic">
|
<span class="text-muted-foreground">任务名称</span>
|
||||||
无日志输出
|
<span class="text-right font-medium">{{ selectedLog.task_name }}</span>
|
||||||
</div>
|
<span class="text-muted-foreground">执行状态</span>
|
||||||
<div v-if="isWsLoading"
|
<Badge :class="getStatusBadgeClass(selectedLog.status)" class="ml-auto">{{ selectedLog.status }}</Badge>
|
||||||
class="px-4 py-2 text-sm text-zinc-500 italic border-t border-zinc-200 dark:border-zinc-800 absolute bottom-0 left-0 w-full bg-inherit/80 backdrop-blur-sm">
|
<span class="text-muted-foreground">执行耗时</span>
|
||||||
连接中...
|
<span class="text-right">{{ formatDuration(selectedLog.duration) }}</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
<div class="border-t pt-4">
|
||||||
|
<span class="text-xs font-semibold uppercase text-muted-foreground block mb-2">执行命令</span>
|
||||||
|
<code class="block p-2 bg-muted rounded text-xs break-all font-mono">{{ selectedLog.command }}</code>
|
||||||
|
</div>
|
||||||
|
<div class="border-t pt-4 flex flex-col items-center justify-center py-12 text-muted-foreground text-xs bg-muted/10 rounded">
|
||||||
|
<p>侧边栏仅展示详情</p>
|
||||||
|
<p class="mt-1 opacity-70">查看完整日志请点击右上角全屏按钮</p>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- 全屏查看日志 -->
|
<!-- 全屏查看日志 -->
|
||||||
<LogViewer v-model:open="showFullscreen" :title="`日志输出 - ${selectedLog?.task_name || ''}`"
|
<LogViewer v-model:open="showFullscreen" :task-name="selectedLog?.task_name"
|
||||||
:content="decompressedOutput" :status="selectedLog?.status" />
|
:log-id="selectedLog?.id" :initial-status="selectedLog?.status" />
|
||||||
|
|
||||||
<!-- 清空日志确认弹窗 -->
|
<!-- 弹窗 (清空/删除) -->
|
||||||
<AlertDialog :open="showClearDialog" @update:open="showClearDialog = $event">
|
<AlertDialog :open="showClearDialog" @update:open="showClearDialog = $event">
|
||||||
<AlertDialogContent>
|
<AlertDialogContent>
|
||||||
<AlertDialogHeader>
|
<AlertDialogHeader>
|
||||||
<AlertDialogTitle>确认清空日志?</AlertDialogTitle>
|
<AlertDialogTitle>确认清空日志?</AlertDialogTitle>
|
||||||
<AlertDialogDescription>
|
<AlertDialogDescription>此操作不可撤销。</AlertDialogDescription>
|
||||||
此操作将永久删除{{ filterTaskId ? '当前任务的' : '所有' }}任务历史记录,包括控制台输出,并且无法撤销。
|
|
||||||
</AlertDialogDescription>
|
|
||||||
</AlertDialogHeader>
|
</AlertDialogHeader>
|
||||||
<AlertDialogFooter>
|
<AlertDialogFooter>
|
||||||
<AlertDialogCancel>取消</AlertDialogCancel>
|
<AlertDialogCancel>取消</AlertDialogCancel>
|
||||||
<AlertDialogAction @click="handleClearLogs" variant="destructive">
|
<AlertDialogAction @click="handleClearLogs" variant="destructive">清空</AlertDialogAction>
|
||||||
清空
|
|
||||||
</AlertDialogAction>
|
|
||||||
</AlertDialogFooter>
|
</AlertDialogFooter>
|
||||||
</AlertDialogContent>
|
</AlertDialogContent>
|
||||||
</AlertDialog>
|
</AlertDialog>
|
||||||
|
|
||||||
<!-- 单条删除确认弹窗 -->
|
|
||||||
<AlertDialog :open="showDeleteDialog" @update:open="showDeleteDialog = $event">
|
<AlertDialog :open="showDeleteDialog" @update:open="showDeleteDialog = $event">
|
||||||
<AlertDialogContent>
|
<AlertDialogContent>
|
||||||
<AlertDialogHeader>
|
<AlertDialogHeader>
|
||||||
<AlertDialogTitle>确认删除这条日志?</AlertDialogTitle>
|
<AlertDialogTitle>确认删除日志?</AlertDialogTitle>
|
||||||
<AlertDialogDescription>
|
<AlertDialogDescription>数据将永久删除。</AlertDialogDescription>
|
||||||
此操作将永久删除该次运行记录和日志文件,且不可恢复。
|
|
||||||
</AlertDialogDescription>
|
|
||||||
</AlertDialogHeader>
|
</AlertDialogHeader>
|
||||||
<AlertDialogFooter>
|
<AlertDialogFooter>
|
||||||
<AlertDialogCancel>取消</AlertDialogCancel>
|
<AlertDialogCancel>取消</AlertDialogCancel>
|
||||||
<AlertDialogAction @click="handleDeleteLog" variant="destructive">
|
<AlertDialogAction @click="handleDeleteLog" variant="destructive">删除</AlertDialogAction>
|
||||||
删除
|
|
||||||
</AlertDialogAction>
|
|
||||||
</AlertDialogFooter>
|
</AlertDialogFooter>
|
||||||
</AlertDialogContent>
|
</AlertDialogContent>
|
||||||
</AlertDialog>
|
</AlertDialog>
|
||||||
|
|||||||
@@ -1,23 +1,32 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { watch, onUnmounted } from 'vue'
|
import { ref, watch, onUnmounted } from 'vue'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import { X } from 'lucide-vue-next'
|
import { X, Loader2 } from 'lucide-vue-next'
|
||||||
import LogTerminal from '@/components/LogTerminal.vue'
|
import LogTerminal from '@/components/LogTerminal.vue'
|
||||||
import { useTheme } from '@/composables/useTheme'
|
import { useTheme } from '@/composables/useTheme'
|
||||||
|
import { api } from '@/api'
|
||||||
|
// import { toast } from 'vue-sonner' // redundant here
|
||||||
|
import { TASK_STATUS } from '@/constants'
|
||||||
|
|
||||||
const { resolvedTheme } = useTheme()
|
const { resolvedTheme } = useTheme()
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
open: boolean
|
open: boolean
|
||||||
title: string
|
logId?: string
|
||||||
content: string
|
taskName?: string
|
||||||
status?: string
|
initialStatus?: string
|
||||||
}>()
|
}>()
|
||||||
|
|
||||||
const emit = defineEmits<{
|
const emit = defineEmits<{
|
||||||
'update:open': [value: boolean]
|
'update:open': [value: boolean]
|
||||||
}>()
|
}>()
|
||||||
|
|
||||||
|
const logContent = ref('')
|
||||||
|
const logStatus = ref(props.initialStatus || '')
|
||||||
|
const isWsLoading = ref(false)
|
||||||
|
let logSocket: WebSocket | null = null
|
||||||
|
let durationTimer: ReturnType<typeof setInterval> | null = null
|
||||||
|
|
||||||
const lightLogBackgroundClass = 'bg-zinc-100'
|
const lightLogBackgroundClass = 'bg-zinc-100'
|
||||||
const darkLogBackgroundClass = 'bg-zinc-950'
|
const darkLogBackgroundClass = 'bg-zinc-950'
|
||||||
|
|
||||||
@@ -25,27 +34,86 @@ function close() {
|
|||||||
emit('update:open', false)
|
emit('update:open', false)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 统一控制 Body 滚动
|
function connectLogSocket(id: string) {
|
||||||
function toggleBodyScroll(lock: boolean) {
|
if (logSocket) {
|
||||||
if (lock) {
|
logSocket.close()
|
||||||
document.body.style.overflow = 'hidden'
|
}
|
||||||
} else {
|
isWsLoading.value = true
|
||||||
document.body.style.overflow = ''
|
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
|
||||||
|
const host = window.location.host
|
||||||
|
const baseUrl = (window as any).__BASE_URL__ || ''
|
||||||
|
const apiVersion = (window as any).__API_VERSION__ || '/api/v1'
|
||||||
|
const wsUrl = `${protocol}//${host}${baseUrl}${apiVersion}/logs/ws?log_id=${id}`
|
||||||
|
|
||||||
|
logSocket = new WebSocket(wsUrl)
|
||||||
|
|
||||||
|
logSocket.onopen = () => {
|
||||||
|
isWsLoading.value = false
|
||||||
|
logContent.value = ''
|
||||||
|
}
|
||||||
|
|
||||||
|
logSocket.onmessage = (event) => {
|
||||||
|
if (logStatus.value !== TASK_STATUS.RUNNING) {
|
||||||
|
logContent.value = event.data
|
||||||
|
} else {
|
||||||
|
logContent.value += event.data
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
logSocket.onerror = () => {
|
||||||
|
isWsLoading.value = false
|
||||||
|
logContent.value = '日志连接异常'
|
||||||
|
}
|
||||||
|
|
||||||
|
logSocket.onclose = () => {
|
||||||
|
isWsLoading.value = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 监听打开状态
|
function startPolling(id: string) {
|
||||||
watch(() => props.open, (val) => {
|
if (durationTimer) clearInterval(durationTimer)
|
||||||
if (val) {
|
durationTimer = setInterval(async () => {
|
||||||
toggleBodyScroll(true)
|
try {
|
||||||
} else {
|
if (!props.open) {
|
||||||
toggleBodyScroll(false)
|
if (durationTimer) clearInterval(durationTimer)
|
||||||
}
|
return
|
||||||
}, { immediate: true })
|
}
|
||||||
|
const logRes = await api.logs.get(id)
|
||||||
|
if (logRes) {
|
||||||
|
logStatus.value = logRes.status
|
||||||
|
if (logRes.status !== TASK_STATUS.RUNNING) {
|
||||||
|
if (durationTimer) clearInterval(durationTimer)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch { /* ignore */ }
|
||||||
|
}, 3000)
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(() => props.open, (val) => {
|
||||||
|
if (val && props.logId) {
|
||||||
|
logStatus.value = props.initialStatus || ''
|
||||||
|
connectLogSocket(props.logId)
|
||||||
|
if (logStatus.value === TASK_STATUS.RUNNING) {
|
||||||
|
startPolling(props.logId)
|
||||||
|
}
|
||||||
|
document.body.style.overflow = 'hidden'
|
||||||
|
} else {
|
||||||
|
if (logSocket) {
|
||||||
|
logSocket.close()
|
||||||
|
logSocket = null
|
||||||
|
}
|
||||||
|
if (durationTimer) {
|
||||||
|
clearInterval(durationTimer)
|
||||||
|
durationTimer = null
|
||||||
|
}
|
||||||
|
document.body.style.overflow = ''
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
// 确保组件卸载时恢复滚动
|
|
||||||
onUnmounted(() => {
|
onUnmounted(() => {
|
||||||
toggleBodyScroll(false)
|
if (logSocket) logSocket.close()
|
||||||
|
if (durationTimer) clearInterval(durationTimer)
|
||||||
|
document.body.style.overflow = ''
|
||||||
})
|
})
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -55,21 +123,19 @@ onUnmounted(() => {
|
|||||||
@click.self="close">
|
@click.self="close">
|
||||||
<div
|
<div
|
||||||
class="bg-background rounded-lg shadow-lg flex flex-col w-full sm:w-[90vw] md:w-[80vw] max-w-5xl h-[90vh] sm:h-[85vh]">
|
class="bg-background rounded-lg shadow-lg flex flex-col w-full sm:w-[90vw] md:w-[80vw] max-w-5xl h-[90vh] sm:h-[85vh]">
|
||||||
<div
|
<div class="flex items-center justify-between px-3 sm:px-4 py-2 sm:py-3 border-b shrink-0 gap-3">
|
||||||
class="flex items-center justify-between px-3 sm:px-4 py-2 sm:py-3 border-b shrink-0 gap-3">
|
|
||||||
<div class="flex items-center gap-3 min-w-0 flex-1">
|
<div class="flex items-center gap-3 min-w-0 flex-1">
|
||||||
<span class="text-sm font-medium truncate" :title="title">{{ title }}</span>
|
<span class="text-sm font-medium truncate">最新日志 - {{ taskName }}</span>
|
||||||
<div v-if="status"
|
<div v-if="logStatus"
|
||||||
class="flex items-center gap-1.5 px-2 py-0.5 rounded text-[10px] font-bold uppercase transition-colors shrink-0"
|
class="flex items-center gap-1.5 px-2 py-0.5 rounded text-[10px] font-bold uppercase transition-colors shrink-0"
|
||||||
:class="status === 'success' ? 'bg-green-500/10 text-green-500 border border-green-500/20' :
|
:class="logStatus === TASK_STATUS.SUCCESS ? 'bg-green-500/10 text-green-500 border border-green-500/20' :
|
||||||
status === 'failed' ? 'bg-red-500/10 text-red-500 border border-red-500/20' :
|
logStatus === TASK_STATUS.FAILED ? 'bg-red-500/10 text-red-500 border border-red-500/20' :
|
||||||
'bg-yellow-500/10 text-yellow-500 border border-yellow-500/20'">
|
'bg-yellow-500/10 text-yellow-500 border border-yellow-500/20'">
|
||||||
<span v-if="status === 'running'" class="relative flex h-1.5 w-1.5 mr-0.5">
|
<span v-if="logStatus === TASK_STATUS.RUNNING" class="relative flex h-1.5 w-1.5 mr-0.5">
|
||||||
<span
|
<span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-yellow-400 opacity-75"></span>
|
||||||
class="animate-ping absolute inline-flex h-full w-full rounded-full bg-yellow-400 opacity-75"></span>
|
|
||||||
<span class="relative inline-flex rounded-full h-1.5 w-1.5 bg-yellow-500"></span>
|
<span class="relative inline-flex rounded-full h-1.5 w-1.5 bg-yellow-500"></span>
|
||||||
</span>
|
</span>
|
||||||
{{ status === 'success' ? '成功' : status === 'failed' ? '失败' : '执行中' }}
|
{{ logStatus === TASK_STATUS.SUCCESS ? '成功' : logStatus === TASK_STATUS.FAILED ? '失败' : '执行中' }}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="flex items-center gap-2 shrink-0">
|
<div class="flex items-center gap-2 shrink-0">
|
||||||
@@ -80,7 +146,11 @@ onUnmounted(() => {
|
|||||||
</div>
|
</div>
|
||||||
<div class="flex-1 overflow-hidden relative"
|
<div class="flex-1 overflow-hidden relative"
|
||||||
:class="resolvedTheme === 'dark' ? darkLogBackgroundClass : lightLogBackgroundClass">
|
:class="resolvedTheme === 'dark' ? darkLogBackgroundClass : lightLogBackgroundClass">
|
||||||
<LogTerminal v-if="content" :content="content" :theme="resolvedTheme" />
|
<LogTerminal v-if="logContent" :content="logContent" :theme="resolvedTheme" />
|
||||||
|
<div v-else-if="isWsLoading" class="absolute inset-0 flex items-center justify-center gap-2 text-zinc-500 font-mono text-sm">
|
||||||
|
<Loader2 class="h-4 w-4 animate-spin" />
|
||||||
|
连接中...
|
||||||
|
</div>
|
||||||
<div v-else class="absolute inset-0 flex items-center justify-center text-zinc-500 font-mono text-sm italic">
|
<div v-else class="absolute inset-0 flex items-center justify-center text-zinc-500 font-mono text-sm italic">
|
||||||
无日志输出
|
无日志输出
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { ref, onMounted } from 'vue'
|
import { ref, onMounted } from 'vue'
|
||||||
import { Badge } from '@/components/ui/badge'
|
import { Badge } from '@/components/ui/badge'
|
||||||
import { ExternalLink, TriangleAlert } from 'lucide-vue-next'
|
import { ExternalLink, TriangleAlert, History } from 'lucide-vue-next'
|
||||||
import { api, type AboutInfo } from '@/api'
|
import { api, type AboutInfo } from '@/api'
|
||||||
|
|
||||||
const aboutInfo = ref<AboutInfo | null>(null)
|
const aboutInfo = ref<AboutInfo | null>(null)
|
||||||
@@ -21,9 +21,16 @@ onMounted(loadAbout)
|
|||||||
<template>
|
<template>
|
||||||
<div>
|
<div>
|
||||||
<!-- 站点关于 -->
|
<!-- 站点关于 -->
|
||||||
<div class="mb-6">
|
<div class="mb-8 flex flex-col sm:flex-row justify-between items-start gap-4">
|
||||||
<h3 class="text-lg font-semibold mb-1">白虎面板 (Baihu Panel)</h3>
|
<div class="flex-1 min-w-0">
|
||||||
<p class="text-sm text-muted-foreground">极致轻量、高性能的自动化任务调度平台。深度集成 Mise 运行时管理,支持多语言环境动态切换与全自动依赖管理。</p>
|
<h3 class="text-xl font-bold mb-1.5">白虎面板 (Baihu Panel)</h3>
|
||||||
|
<p class="text-sm text-muted-foreground leading-relaxed">极致轻量、高性能的自动化任务调度平台。深度集成 Mise 运行时管理,支持多语言环境动态切换与全自动依赖管理。</p>
|
||||||
|
</div>
|
||||||
|
<a href="https://engigu.github.io/baihu-panel/guide/changelog.html" target="_blank"
|
||||||
|
class="inline-flex items-center gap-1.5 h-9 px-4 rounded-full border border-primary/20 bg-primary/5 text-primary text-xs font-semibold hover:bg-primary/10 transition-all whitespace-nowrap shadow-sm shadow-primary/5">
|
||||||
|
<History class="h-3.5 w-3.5" />
|
||||||
|
查看更新日志
|
||||||
|
</a>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="grid sm:grid-cols-2 gap-x-8 gap-y-5">
|
<div class="grid sm:grid-cols-2 gap-x-8 gap-y-5">
|
||||||
@@ -51,8 +58,21 @@ onMounted(loadAbout)
|
|||||||
<h4 class="text-sm font-medium mb-2">系统信息</h4>
|
<h4 class="text-sm font-medium mb-2">系统信息</h4>
|
||||||
<div class="space-y-2">
|
<div class="space-y-2">
|
||||||
<div class="flex justify-between items-center">
|
<div class="flex justify-between items-center">
|
||||||
<span class="text-muted-foreground text-sm">系统版本:</span>
|
<span class="text-muted-foreground text-sm">当前版本:</span>
|
||||||
<Badge variant="outline" class="font-mono text-xs">{{ aboutInfo?.version || 'dev' }}</Badge>
|
<div class="flex items-center gap-1.5">
|
||||||
|
<Badge variant="outline" class="font-mono text-xs">{{ aboutInfo?.version || 'dev' }}</Badge>
|
||||||
|
<Badge v-if="aboutInfo?.remote_version && aboutInfo.remote_version === aboutInfo.version" variant="secondary"
|
||||||
|
class="text-[10px] h-4 px-1 bg-green-500/10 text-green-600 border-green-500/20">
|
||||||
|
最新版本
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div v-if="aboutInfo?.remote_version && aboutInfo.remote_version !== aboutInfo.version"
|
||||||
|
class="flex justify-between items-center">
|
||||||
|
<span class="text-muted-foreground text-sm">最新版本:</span>
|
||||||
|
<Badge variant="secondary" class="font-mono text-xs bg-primary/10 text-primary border-primary/20">
|
||||||
|
{{ aboutInfo.remote_version }}
|
||||||
|
</Badge>
|
||||||
</div>
|
</div>
|
||||||
<div class="flex justify-between items-center">
|
<div class="flex justify-between items-center">
|
||||||
<span class="text-muted-foreground text-sm">构建时间:</span>
|
<span class="text-muted-foreground text-sm">构建时间:</span>
|
||||||
|
|||||||
@@ -1,16 +1,17 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { ref, computed, watch } from 'vue'
|
import { ref, computed, watch } from 'vue'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'
|
||||||
import { Input } from '@/components/ui/input'
|
import { Input } from '@/components/ui/input'
|
||||||
import { Label } from '@/components/ui/label'
|
import { Label } from '@/components/ui/label'
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||||
import { Switch } from '@/components/ui/switch'
|
import { Switch } from '@/components/ui/switch'
|
||||||
import { Checkbox } from '@/components/ui/checkbox'
|
import { Checkbox } from '@/components/ui/checkbox'
|
||||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||||
|
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
|
||||||
import DirTreeSelect from '@/components/DirTreeSelect.vue'
|
import DirTreeSelect from '@/components/DirTreeSelect.vue'
|
||||||
import { X, Globe, GitBranch, Shield, Zap, Clock } from 'lucide-vue-next'
|
import { X, Globe, GitBranch, Shield, Zap, Clock, Download, Plus, Search, Check, ChevronsUpDown, Loader2, AlertCircle } from 'lucide-vue-next'
|
||||||
import { api, type Task, type RepoConfig, type Agent } from '@/api'
|
import { api, type Task, type RepoConfig, type Agent, type MiseLanguage } from '@/api'
|
||||||
import { toast } from 'vue-sonner'
|
import { toast } from 'vue-sonner'
|
||||||
import { cn } from '@/lib/utils'
|
import { cn } from '@/lib/utils'
|
||||||
import { getCronDescription } from '@/utils/cron'
|
import { getCronDescription } from '@/utils/cron'
|
||||||
@@ -56,7 +57,12 @@ const repoConfig = ref<RepoConfig>({
|
|||||||
proxy_url: '',
|
proxy_url: '',
|
||||||
auth_token: '',
|
auth_token: '',
|
||||||
whitelist_paths: '',
|
whitelist_paths: '',
|
||||||
|
blacklist: '',
|
||||||
|
dependence: '',
|
||||||
|
extensions: '',
|
||||||
|
auto_add_cron: false,
|
||||||
concurrency: 1,
|
concurrency: 1,
|
||||||
|
repo_source: '',
|
||||||
proxy: ''
|
proxy: ''
|
||||||
})
|
})
|
||||||
const cleanType = ref('none')
|
const cleanType = ref('none')
|
||||||
@@ -64,7 +70,171 @@ const cleanKeep = ref(30)
|
|||||||
const allAgents = ref<Agent[]>([])
|
const allAgents = ref<Agent[]>([])
|
||||||
const selectedAgentId = ref<string>('local')
|
const selectedAgentId = ref<string>('local')
|
||||||
const tagInput = ref('')
|
const tagInput = ref('')
|
||||||
const whitelistInput = ref('')
|
|
||||||
|
const autoAddCron = computed({
|
||||||
|
get: () => !!repoConfig.value.auto_add_cron,
|
||||||
|
set: (val: boolean) => {
|
||||||
|
repoConfig.value.auto_add_cron = val
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
// === 语言环境相关 ===
|
||||||
|
const installedLangs = ref<MiseLanguage[]>([])
|
||||||
|
const loadingLangs = ref(false)
|
||||||
|
const selectedLangs = ref<{ name: string; version: string; availableVersions: string[] }[]>([])
|
||||||
|
const availablePlugins = ref<string[]>([])
|
||||||
|
const pluginSearch = ref('')
|
||||||
|
const versionSearch = ref('')
|
||||||
|
|
||||||
|
const filteredPlugins = computed(() => {
|
||||||
|
if (!pluginSearch.value) return availablePlugins.value
|
||||||
|
const s = pluginSearch.value.toLowerCase()
|
||||||
|
return availablePlugins.value.filter(p => p.toLowerCase().includes(s))
|
||||||
|
})
|
||||||
|
|
||||||
|
function getFilteredVersions(versions: string[]) {
|
||||||
|
if (!versionSearch.value) return versions
|
||||||
|
const s = versionSearch.value.toLowerCase()
|
||||||
|
return versions.filter(v => v.toLowerCase().includes(s))
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchInstalledLangs() {
|
||||||
|
loadingLangs.value = true
|
||||||
|
try {
|
||||||
|
installedLangs.value = await api.mise.list()
|
||||||
|
const plugins = new Set<string>()
|
||||||
|
installedLangs.value.forEach(l => plugins.add(l.plugin))
|
||||||
|
availablePlugins.value = Array.from(plugins).sort()
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Fetch installed langs failed', e)
|
||||||
|
} finally {
|
||||||
|
loadingLangs.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function getLangIcon(plugin: string) {
|
||||||
|
const name = plugin?.toLowerCase().trim()
|
||||||
|
const mapping: Record<string, string> = {
|
||||||
|
'python': 'python/python-original.svg',
|
||||||
|
'node': 'nodejs/nodejs-original.svg',
|
||||||
|
'nodejs': 'nodejs/nodejs-original.svg',
|
||||||
|
'go': 'go/go-original.svg',
|
||||||
|
'rust': 'rust/rust-original.svg',
|
||||||
|
'ruby': 'ruby/ruby-plain.svg',
|
||||||
|
'php': 'php/php-plain.svg',
|
||||||
|
'java': 'java/java-plain.svg',
|
||||||
|
'deno': 'deno/deno-plain.svg',
|
||||||
|
'bun': 'bun/bun-plain.svg',
|
||||||
|
'zig': 'zig/zig-original.svg',
|
||||||
|
'dotnet': 'dot-net/dot-net-original.svg',
|
||||||
|
'.net': 'dot-net/dot-net-original.svg',
|
||||||
|
'elixir': 'elixir/elixir-original.svg',
|
||||||
|
'erlang': 'erlang/erlang-original.svg',
|
||||||
|
'crystal': 'crystal/crystal-original.svg',
|
||||||
|
'lua': 'lua/lua-original.svg',
|
||||||
|
'julia': 'julia/julia-original.svg',
|
||||||
|
'nim': 'nim/nim-original.svg',
|
||||||
|
'perl': 'perl/perl-original.svg',
|
||||||
|
'scala': 'scala/scala-original.svg',
|
||||||
|
'kotlin': 'kotlin/kotlin-original.svg',
|
||||||
|
'clojure': 'clojure/clojure-line.svg',
|
||||||
|
'dart': 'dart/dart-original.svg',
|
||||||
|
'flutter': 'flutter/flutter-original.svg',
|
||||||
|
'terraform': 'terraform/terraform-original.svg',
|
||||||
|
'docker': 'docker/docker-original.svg',
|
||||||
|
'kubernetes': 'kubernetes/kubernetes-plain.svg',
|
||||||
|
'ansible': 'ansible/ansible-original.svg',
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mapping[name]) {
|
||||||
|
return `https://fastly.jsdelivr.net/gh/devicons/devicon/icons/${mapping[name]}`
|
||||||
|
}
|
||||||
|
return ''
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateAvailableVersions(lang: { name: string; version: string; availableVersions: string[] }) {
|
||||||
|
if (lang.name) {
|
||||||
|
lang.availableVersions = installedLangs.value
|
||||||
|
.filter(l => l.plugin === lang.name)
|
||||||
|
.map(l => l.version)
|
||||||
|
.sort((a, b) => b.localeCompare(a, undefined, { numeric: true }))
|
||||||
|
} else {
|
||||||
|
lang.availableVersions = []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function addLang() {
|
||||||
|
selectedLangs.value.push({ name: '', version: '', availableVersions: [] })
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeLang(index: number) {
|
||||||
|
selectedLangs.value.splice(index, 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateLangName(index: number, name: string) {
|
||||||
|
const lang = selectedLangs.value[index]
|
||||||
|
if (!lang) return
|
||||||
|
lang.name = name
|
||||||
|
lang.version = '' // reset version
|
||||||
|
updateAvailableVersions(lang)
|
||||||
|
}
|
||||||
|
|
||||||
|
const showQlImportDialog = ref(false)
|
||||||
|
const qlCommandInput = ref('')
|
||||||
|
|
||||||
|
function importFromQl() {
|
||||||
|
qlCommandInput.value = ''
|
||||||
|
showQlImportDialog.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
function submitQlImport() {
|
||||||
|
const s = qlCommandInput.value.trim()
|
||||||
|
if (!s) {
|
||||||
|
showQlImportDialog.value = false
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!s.startsWith('ql repo')) {
|
||||||
|
toast.error('无效的指令:必须以 ql repo 开头')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse arguments handling quotes
|
||||||
|
const args: string[] = []
|
||||||
|
const regex = /[^\s"']+|"([^"]*)"|'([^']*)'/g
|
||||||
|
let match
|
||||||
|
while ((match = regex.exec(s)) !== null) {
|
||||||
|
args.push(match[1] || match[2] || match[0])
|
||||||
|
}
|
||||||
|
|
||||||
|
if (args[2]) {
|
||||||
|
repoConfig.value.source_url = args[2]
|
||||||
|
repoConfig.value.source_type = 'git'
|
||||||
|
// form task name
|
||||||
|
let name = '同步 '
|
||||||
|
try {
|
||||||
|
const urlPaths = args[2].split('/')
|
||||||
|
if (urlPaths.length > 0) {
|
||||||
|
name += urlPaths[urlPaths.length - 1].replace('.git', '')
|
||||||
|
} else {
|
||||||
|
name += '未命名仓库'
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
name += '未命名仓库'
|
||||||
|
}
|
||||||
|
form.value.name = name
|
||||||
|
}
|
||||||
|
|
||||||
|
if (args[3]) repoConfig.value.whitelist_paths = args[3]
|
||||||
|
if (args[4]) repoConfig.value.blacklist = args[4]
|
||||||
|
if (args[5]) repoConfig.value.dependence = args[5]
|
||||||
|
if (args[6]) repoConfig.value.branch = args[6]
|
||||||
|
if (args[7]) repoConfig.value.extensions = args[7]
|
||||||
|
|
||||||
|
repoConfig.value.auto_add_cron = true
|
||||||
|
repoConfig.value.repo_source = 'ql'
|
||||||
|
toast.success('指令解析成功,已开启自动添加任务,请继续完善其他设置')
|
||||||
|
showQlImportDialog.value = false
|
||||||
|
}
|
||||||
|
|
||||||
const cronDescription = computed(() => {
|
const cronDescription = computed(() => {
|
||||||
if (!form.value.schedule) return ''
|
if (!form.value.schedule) return ''
|
||||||
@@ -87,21 +257,6 @@ function removeTag(tagToRemove: string) {
|
|||||||
form.value.tags = currentTags.filter(t => t !== tagToRemove).join(',')
|
form.value.tags = currentTags.filter(t => t !== tagToRemove).join(',')
|
||||||
}
|
}
|
||||||
|
|
||||||
function addWhitelistPath() {
|
|
||||||
const val = whitelistInput.value.trim()
|
|
||||||
if (!val) return
|
|
||||||
const current = repoConfig.value.whitelist_paths ? repoConfig.value.whitelist_paths.split(',').filter(Boolean) : []
|
|
||||||
if (!current.includes(val)) {
|
|
||||||
current.push(val)
|
|
||||||
repoConfig.value.whitelist_paths = current.join(',')
|
|
||||||
}
|
|
||||||
whitelistInput.value = ''
|
|
||||||
}
|
|
||||||
|
|
||||||
function removeWhitelistPath(path: string) {
|
|
||||||
const current = repoConfig.value.whitelist_paths ? repoConfig.value.whitelist_paths.split(',').filter(Boolean) : []
|
|
||||||
repoConfig.value.whitelist_paths = current.filter(p => p !== path).join(',')
|
|
||||||
}
|
|
||||||
|
|
||||||
const concurrencyEnabled = computed({
|
const concurrencyEnabled = computed({
|
||||||
get: () => repoConfig.value.concurrency === 1,
|
get: () => repoConfig.value.concurrency === 1,
|
||||||
@@ -162,7 +317,12 @@ watch(() => props.open, async (val) => {
|
|||||||
proxy_url: '',
|
proxy_url: '',
|
||||||
auth_token: '',
|
auth_token: '',
|
||||||
whitelist_paths: '',
|
whitelist_paths: '',
|
||||||
concurrency: 1
|
blacklist: '',
|
||||||
|
dependence: '',
|
||||||
|
extensions: '',
|
||||||
|
auto_add_cron: false,
|
||||||
|
concurrency: 1,
|
||||||
|
repo_source: ''
|
||||||
}
|
}
|
||||||
const configStr = props.task?.config
|
const configStr = props.task?.config
|
||||||
if (configStr) {
|
if (configStr) {
|
||||||
@@ -180,10 +340,27 @@ watch(() => props.open, async (val) => {
|
|||||||
} else {
|
} else {
|
||||||
repoConfig.value = defaultConfig
|
repoConfig.value = defaultConfig
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 解析语言环境
|
||||||
|
selectedLangs.value = []
|
||||||
|
if (props.task?.languages && Array.isArray(props.task.languages)) {
|
||||||
|
selectedLangs.value = props.task.languages.map((l: any) => ({
|
||||||
|
name: l.name || '',
|
||||||
|
version: l.version || '',
|
||||||
|
availableVersions: []
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
// 仓库任务暂时仅支持本地执行
|
// 仓库任务暂时仅支持本地执行
|
||||||
selectedAgentId.value = 'local'
|
selectedAgentId.value = 'local'
|
||||||
// 加载 Agent 列表
|
// 加载 Agent 列表
|
||||||
await loadAgents()
|
await loadAgents()
|
||||||
|
if (selectedAgentId.value === 'local') {
|
||||||
|
await fetchInstalledLangs()
|
||||||
|
selectedLangs.value.forEach(lang => {
|
||||||
|
updateAvailableVersions(lang)
|
||||||
|
})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -194,6 +371,13 @@ async function loadAgents() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function save() {
|
async function save() {
|
||||||
|
if (repoConfig.value.auto_add_cron) {
|
||||||
|
if (selectedLangs.value.length === 0 || !selectedLangs.value[0].name) {
|
||||||
|
toast.error('您开启了“自动添加任务”,请先至少添加并选择一个运行语言环境和版本')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
form.value.clean_config = cleanConfig.value
|
form.value.clean_config = cleanConfig.value
|
||||||
form.value.type = 'repo'
|
form.value.type = 'repo'
|
||||||
@@ -205,6 +389,12 @@ async function save() {
|
|||||||
'$task_concurrency': concurrencyEnabled.value ? 1 : 0
|
'$task_concurrency': concurrencyEnabled.value ? 1 : 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 保存语言环境
|
||||||
|
form.value.languages = selectedLangs.value.map(l => ({
|
||||||
|
name: l.name,
|
||||||
|
version: l.version
|
||||||
|
}))
|
||||||
|
|
||||||
form.value.config = JSON.stringify(configToSave)
|
form.value.config = JSON.stringify(configToSave)
|
||||||
form.value.command = `[${repoConfig.value.source_type}] ${repoConfig.value.source_url}`
|
form.value.command = `[${repoConfig.value.source_type}] ${repoConfig.value.source_url}`
|
||||||
form.value.agent_id = selectedAgentId.value === 'local' ? null : selectedAgentId.value
|
form.value.agent_id = selectedAgentId.value === 'local' ? null : selectedAgentId.value
|
||||||
@@ -228,9 +418,15 @@ async function save() {
|
|||||||
|
|
||||||
<div class="flex flex-col max-h-[85vh]">
|
<div class="flex flex-col max-h-[85vh]">
|
||||||
<DialogHeader class="px-6 pt-6 pb-2 shrink-0">
|
<DialogHeader class="px-6 pt-6 pb-2 shrink-0">
|
||||||
<DialogTitle class="text-xl font-bold bg-clip-text text-transparent bg-gradient-to-r from-foreground to-foreground/70">
|
<div class="flex items-center justify-between">
|
||||||
{{ isEdit ? '编辑仓库同步' : '新建仓库同步' }}
|
<DialogTitle class="text-xl font-bold bg-clip-text text-transparent bg-gradient-to-r from-foreground to-foreground/70">
|
||||||
</DialogTitle>
|
{{ isEdit ? '编辑仓库同步' : '新建仓库同步' }}
|
||||||
|
</DialogTitle>
|
||||||
|
<Button v-if="!isEdit" variant="outline" size="sm" @click="importFromQl" class="h-8 gap-1.5 bg-primary/5 hover:bg-primary/10 border-primary/20 hover:border-primary/40 text-primary">
|
||||||
|
<Download class="w-3.5 h-3.5" />
|
||||||
|
青龙格式导入
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
|
|
||||||
<ScrollArea class="flex-1 min-h-0 px-6">
|
<ScrollArea class="flex-1 min-h-0 px-6">
|
||||||
@@ -325,36 +521,6 @@ async function save() {
|
|||||||
<Input v-else v-model="repoConfig.target_path" placeholder="Agent 上的目标路径" class="h-9 bg-muted/30 border-muted-foreground/20" />
|
<Input v-else v-model="repoConfig.target_path" placeholder="Agent 上的目标路径" class="h-9 bg-muted/30 border-muted-foreground/20" />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- 新增:白名单路径 -->
|
|
||||||
<div class="grid grid-cols-1 sm:grid-cols-4 items-start gap-3">
|
|
||||||
<Label class="sm:text-right text-xs text-muted-foreground uppercase tracking-wider pt-2.5">
|
|
||||||
白名单路径
|
|
||||||
</Label>
|
|
||||||
<div class="sm:col-span-3 space-y-2">
|
|
||||||
<div class="flex gap-2">
|
|
||||||
<div class="relative flex-1">
|
|
||||||
<Input v-model="whitelistInput" placeholder="输入路径或通配符按回车... (如 logs/ 或 *.db)" class="h-9 bg-muted/30 border-muted-foreground/20 pr-12 focus:bg-background" @keydown.enter.prevent="addWhitelistPath" />
|
|
||||||
<Button type="button" variant="ghost" size="sm" class="absolute right-1 top-1 h-7 px-2 text-xs hover:bg-primary/10 hover:text-primary transition-colors" @click="addWhitelistPath">
|
|
||||||
添加
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="flex flex-wrap gap-1.5 pt-1 min-h-[1.5rem]" v-if="repoConfig.whitelist_paths">
|
|
||||||
<span v-for="path in repoConfig.whitelist_paths.split(',').filter(Boolean)" :key="path"
|
|
||||||
class="flex items-center gap-1.5 bg-blue-500/5 text-blue-500 px-2.5 py-1 rounded-md text-[11px] font-medium border border-blue-500/10 group transition-all hover:bg-blue-500/10">
|
|
||||||
{{ path }}
|
|
||||||
<button type="button" class="text-blue-500/40 hover:text-destructive transition-colors shrink-0" @click.prevent="removeWhitelistPath(path)">
|
|
||||||
<X class="h-3 w-3" />
|
|
||||||
</button>
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<p class="text-[10px] text-muted-foreground mt-1 px-1 leading-relaxed">
|
|
||||||
同步时将保留匹配上述路径的内容(支持 * 通配符)。匹配项在同步前会被暂存,并在同步完成后自动回填还原。
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div v-if="repoConfig.source_type === 'git'" class="grid grid-cols-1 sm:grid-cols-4 items-center gap-3">
|
<div v-if="repoConfig.source_type === 'git'" class="grid grid-cols-1 sm:grid-cols-4 items-center gap-3">
|
||||||
<Label class="sm:text-right text-xs text-muted-foreground uppercase tracking-wider">分支</Label>
|
<Label class="sm:text-right text-xs text-muted-foreground uppercase tracking-wider">分支</Label>
|
||||||
<Input v-model="repoConfig.branch" placeholder="main (默认)" class="sm:col-span-3 h-9 bg-muted/30 border-muted-foreground/20 focus:bg-background transition-all" autocomplete="off" />
|
<Input v-model="repoConfig.branch" placeholder="main (默认)" class="sm:col-span-3 h-9 bg-muted/30 border-muted-foreground/20 focus:bg-background transition-all" autocomplete="off" />
|
||||||
@@ -414,6 +580,150 @@ async function save() {
|
|||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<!-- 脚本过滤 Section -->
|
||||||
|
<section class="space-y-4">
|
||||||
|
<div class="flex items-center gap-2 mb-1">
|
||||||
|
<div class="h-4 w-1 bg-primary rounded-full" />
|
||||||
|
<h3 class="text-sm font-semibold text-foreground/80">脚本过滤</h3>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="grid gap-4 pl-3 border-l border-muted">
|
||||||
|
<div class="grid grid-cols-1 sm:grid-cols-4 items-center gap-3">
|
||||||
|
<Label class="sm:text-right text-xs text-muted-foreground uppercase tracking-wider">白名单</Label>
|
||||||
|
<div class="sm:col-span-3 relative">
|
||||||
|
<Input v-model="repoConfig.whitelist_paths" placeholder="保活路径或脚本关键词 (如: logs/ | jd_ )" class="h-9 bg-muted/30 border-muted-foreground/20 focus:bg-background transition-all" autocomplete="off" />
|
||||||
|
<p class="text-[10px] text-muted-foreground mt-1 px-1 leading-relaxed">请输入脚本筛选白名单关键词或保活路径(支持 *),多个关键词或路径使用竖线(|)或逗号(,)分割</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="grid grid-cols-1 sm:grid-cols-4 items-center gap-3">
|
||||||
|
<Label class="sm:text-right text-xs text-muted-foreground uppercase tracking-wider">脚本黑名单</Label>
|
||||||
|
<div class="sm:col-span-3 relative">
|
||||||
|
<Input v-model="repoConfig.blacklist" placeholder="黑名单关键词 (如: help)" class="h-9 bg-muted/30 border-muted-foreground/20 focus:bg-background transition-all" autocomplete="off" />
|
||||||
|
<p class="text-[10px] text-muted-foreground mt-1 px-1">脚本筛选黑名单关键词,多个关键词竖线(|)分割</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="grid grid-cols-1 sm:grid-cols-4 items-center gap-3">
|
||||||
|
<Label class="sm:text-right text-xs text-muted-foreground uppercase tracking-wider">依赖文件</Label>
|
||||||
|
<div class="sm:col-span-3 relative">
|
||||||
|
<Input v-model="repoConfig.dependence" placeholder="依赖文件关键词 (如: ccav | notify)" class="h-9 bg-muted/30 border-muted-foreground/20 focus:bg-background transition-all" autocomplete="off" />
|
||||||
|
<p class="text-[10px] text-muted-foreground mt-1 px-1">脚本依赖文件关键词,多个关键词竖线(|)分割</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="grid grid-cols-1 sm:grid-cols-4 items-center gap-3">
|
||||||
|
<Label class="sm:text-right text-xs text-muted-foreground uppercase tracking-wider">文件后缀</Label>
|
||||||
|
<div class="sm:col-span-3 relative">
|
||||||
|
<Input v-model="repoConfig.extensions" placeholder="文件后缀 (如: js | py | sh)" class="h-9 bg-muted/30 border-muted-foreground/20 focus:bg-background transition-all" autocomplete="off" />
|
||||||
|
<p class="text-[10px] text-muted-foreground mt-1 px-1">脚本文件后缀,多个后缀竖线(|)分割</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- 运行环境 Section -->
|
||||||
|
<section v-if="selectedAgentId === 'local'" class="space-y-4">
|
||||||
|
<div class="flex items-center gap-2 mb-1">
|
||||||
|
<div class="h-4 w-1 bg-primary rounded-full" />
|
||||||
|
<h3 class="text-sm font-semibold text-foreground/80">运行环境</h3>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="grid gap-4 pl-3 border-l border-muted">
|
||||||
|
<div class="grid grid-cols-1 sm:grid-cols-4 items-start gap-3 mt-2">
|
||||||
|
<Label class="sm:text-right text-xs text-muted-foreground uppercase tracking-wider pt-2.5">语言环境</Label>
|
||||||
|
<div class="sm:col-span-3 space-y-2">
|
||||||
|
<div class="flex items-start gap-2.5 p-3 rounded-xl bg-amber-500/5 border border-amber-500/10 text-amber-600 dark:text-amber-400 text-[11px] leading-relaxed mb-2">
|
||||||
|
<AlertCircle class="h-4 w-4 shrink-0 text-amber-500 mt-0.5" />
|
||||||
|
<p>同步后生成的任务将自动继承此运行环境。如果不指定语言版本,某些依赖特定语言的脚本(如 js, py)将无法顺利解析和运行!</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-for="(clang, idx) in selectedLangs" :key="idx"
|
||||||
|
class="flex gap-2 p-2 rounded-lg bg-muted/20 border border-muted-foreground/10 group/lang relative overflow-hidden">
|
||||||
|
<div class="absolute left-0 top-0 bottom-0 w-0.5 bg-primary/20 group-hover/lang:bg-primary transition-colors" />
|
||||||
|
<Popover>
|
||||||
|
<PopoverTrigger asChild>
|
||||||
|
<Button variant="ghost" role="combobox" class="justify-between flex-1 h-8 text-xs font-normal hover:bg-background/50">
|
||||||
|
<div class="flex items-center gap-2 truncate">
|
||||||
|
<div v-if="clang.name && getLangIcon(clang.name)" class="w-4 h-4 shrink-0 rounded-sm bg-white p-0.5 border shadow-sm">
|
||||||
|
<img :src="getLangIcon(clang.name)" class="w-full h-full object-contain" />
|
||||||
|
</div>
|
||||||
|
<span class="font-medium">{{ clang.name || "选择插件..." }}</span>
|
||||||
|
</div>
|
||||||
|
<ChevronsUpDown class="ml-1 h-3 w-3 opacity-40" />
|
||||||
|
</Button>
|
||||||
|
</PopoverTrigger>
|
||||||
|
<PopoverContent class="p-0 w-[240px]" align="start">
|
||||||
|
<div class="p-2 border-b bg-muted/30">
|
||||||
|
<div class="relative">
|
||||||
|
<Search class="absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground" />
|
||||||
|
<Input v-model="pluginSearch" placeholder="搜索已安装语言..." class="h-8 pl-8 text-xs bg-background" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<ScrollArea class="h-48 p-1">
|
||||||
|
<div v-if="loadingLangs" class="flex items-center justify-center py-6">
|
||||||
|
<Loader2 class="h-5 w-5 animate-spin text-primary/50" />
|
||||||
|
</div>
|
||||||
|
<div v-else-if="filteredPlugins.length === 0" class="py-6 text-center text-xs text-muted-foreground">
|
||||||
|
未找到匹配项
|
||||||
|
</div>
|
||||||
|
<button v-else v-for="p in filteredPlugins" :key="p" @click="updateLangName(idx, p)"
|
||||||
|
class="w-full flex items-center px-3 py-2 text-xs rounded-md hover:bg-accent text-left transition-all group/item mb-0.5">
|
||||||
|
<div class="mr-3 h-5 w-5 shrink-0 flex items-center justify-center transition-transform group-hover/item:scale-110">
|
||||||
|
<img v-if="getLangIcon(p)" :src="getLangIcon(p)" class="w-full h-full object-contain p-0.5 bg-white rounded border" />
|
||||||
|
<div v-else class="w-full h-full flex items-center justify-center bg-primary/10 rounded-sm text-[8px] font-bold border">
|
||||||
|
{{ p.substring(0, 2) }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<span class="flex-1" :class="{ 'font-bold text-primary': clang.name === p }">{{ p }}</span>
|
||||||
|
<Check v-if="clang.name === p" class="h-3 w-3 text-primary" />
|
||||||
|
</button>
|
||||||
|
</ScrollArea>
|
||||||
|
</PopoverContent>
|
||||||
|
</Popover>
|
||||||
|
|
||||||
|
<Popover>
|
||||||
|
<PopoverTrigger asChild :disabled="!clang.name">
|
||||||
|
<Button variant="ghost" role="combobox" class="justify-between w-28 h-8 text-xs font-normal hover:bg-background/50" :disabled="!clang.name">
|
||||||
|
<span class="truncate">{{ clang.version || "版本..." }}</span>
|
||||||
|
<ChevronsUpDown class="h-3 w-3 opacity-40 ml-1" />
|
||||||
|
</Button>
|
||||||
|
</PopoverTrigger>
|
||||||
|
<PopoverContent class="p-0 w-[160px]" align="start">
|
||||||
|
<div class="p-2 border-b bg-muted/30">
|
||||||
|
<div class="relative">
|
||||||
|
<Search class="absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground" />
|
||||||
|
<Input v-model="versionSearch" placeholder="搜索版本..." class="h-8 pl-8 text-xs bg-background" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<ScrollArea class="h-48 p-1">
|
||||||
|
<div v-if="getFilteredVersions(clang.availableVersions).length === 0" class="py-6 text-center text-xs text-muted-foreground">
|
||||||
|
无可用版本
|
||||||
|
</div>
|
||||||
|
<button v-else v-for="v in getFilteredVersions(clang.availableVersions)" :key="v" @click="clang.version = v"
|
||||||
|
class="w-full flex items-center px-3 py-2 text-xs rounded-md hover:bg-accent text-left mb-0.5 font-mono">
|
||||||
|
<span class="flex-1 truncate" :class="{ 'font-bold text-primary': clang.version === v }">{{ v }}</span>
|
||||||
|
<Check v-if="clang.version === v" class="h-3 w-3 text-primary" />
|
||||||
|
</button>
|
||||||
|
</ScrollArea>
|
||||||
|
</PopoverContent>
|
||||||
|
</Popover>
|
||||||
|
|
||||||
|
<Button variant="ghost" size="icon" class="h-8 w-8 text-muted-foreground hover:text-destructive hover:bg-destructive/10 shrink-0"
|
||||||
|
@click="removeLang(idx)">
|
||||||
|
<X class="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Button variant="outline" size="sm" class="w-full h-9 text-xs border-dashed border-muted-foreground/30 text-muted-foreground hover:text-primary hover:border-primary/50 transition-all bg-muted/10 hover:bg-primary/5"
|
||||||
|
@click="addLang">
|
||||||
|
<Plus class="h-4 w-4 mr-2" /> 必须添加运行语言和版本
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
<!-- 调度策略 Section -->
|
<!-- 调度策略 Section -->
|
||||||
<section class="space-y-4">
|
<section class="space-y-4">
|
||||||
<div class="flex items-center gap-2 mb-1">
|
<div class="flex items-center gap-2 mb-1">
|
||||||
@@ -461,6 +771,20 @@ async function save() {
|
|||||||
<div class="grid grid-cols-1 sm:grid-cols-4 items-start gap-3">
|
<div class="grid grid-cols-1 sm:grid-cols-4 items-start gap-3">
|
||||||
<Label class="sm:text-right text-xs text-muted-foreground uppercase tracking-wider">运行策略</Label>
|
<Label class="sm:text-right text-xs text-muted-foreground uppercase tracking-wider">运行策略</Label>
|
||||||
<div class="sm:col-span-3 space-y-4">
|
<div class="sm:col-span-3 space-y-4">
|
||||||
|
|
||||||
|
<div class="p-3 rounded-xl bg-muted/20 border border-muted-foreground/10 space-y-2.5">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<div class="flex items-center gap-2 text-xs font-semibold">
|
||||||
|
<Zap :class="cn('h-3.5 w-3.5', autoAddCron ? 'text-primary' : 'text-muted-foreground')" />
|
||||||
|
自动添加任务
|
||||||
|
</div>
|
||||||
|
<Switch :model-value="autoAddCron" @update:model-value="v => autoAddCron = v" />
|
||||||
|
</div>
|
||||||
|
<p class="text-[11px] text-muted-foreground leading-relaxed">
|
||||||
|
{{ autoAddCron ? '同步完成后将尝试自动分析脚本并注册定时任务。' : '仅拉取脚本,不自动注册成面板任务。' }}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="flex items-center gap-4">
|
<div class="flex items-center gap-4">
|
||||||
<div class="flex items-center gap-2">
|
<div class="flex items-center gap-2">
|
||||||
<Input :model-value="form.timeout" @update:model-value="v => form.timeout = Number(v || 0)" type="number" :min="0" class="w-20 h-9 bg-muted/30 text-center" />
|
<Input :model-value="form.timeout" @update:model-value="v => form.timeout = Number(v || 0)" type="number" :min="0" class="w-20 h-9 bg-muted/30 text-center" />
|
||||||
@@ -512,4 +836,34 @@ async function save() {
|
|||||||
</div>
|
</div>
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
|
|
||||||
|
<!-- 青龙导入提示对话框 -->
|
||||||
|
<Dialog :open="showQlImportDialog" @update:open="v => showQlImportDialog = v">
|
||||||
|
<DialogContent class="sm:max-w-[425px] p-0 border-none bg-background/95 backdrop-blur-xl shadow-2xl">
|
||||||
|
<DialogHeader class="px-6 pt-6 pb-2">
|
||||||
|
<DialogTitle class="text-xl font-bold bg-clip-text text-transparent bg-gradient-to-r from-foreground to-foreground/70">
|
||||||
|
请输入青龙面板的 ql repo 指令
|
||||||
|
</DialogTitle>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<div class="px-6 py-4 space-y-4 text-sm text-muted-foreground leading-relaxed">
|
||||||
|
<p>例如:</p>
|
||||||
|
<div class="p-2 rounded-md bg-muted/50 font-mono text-xs select-all text-primary/80 break-all border border-muted-foreground/10">
|
||||||
|
ql repo "https://github.com/a/b.git" "jd_|jx_" "activity" "^jd[^_]" "main" "js|py"
|
||||||
|
</div>
|
||||||
|
<div class="relative mt-2">
|
||||||
|
<Input v-model="qlCommandInput" placeholder="在此处粘贴完整指令,如 ql repo ..." class="h-10 pr-10 focus:ring-primary/20 bg-muted/20" @keydown.enter.prevent="submitQlImport" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<DialogFooter class="px-6 pb-6 pt-2">
|
||||||
|
<Button variant="outline" size="sm" @click="showQlImportDialog = false" class="border-border/40 hover:bg-muted/30">
|
||||||
|
取消
|
||||||
|
</Button>
|
||||||
|
<Button size="sm" @click="submitQlImport" class="shadow-sm">
|
||||||
|
确定 <Download class="h-3 w-3 ml-1.5" />
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
+110
-26
@@ -6,8 +6,10 @@ import { Input } from '@/components/ui/input'
|
|||||||
import Pagination from '@/components/Pagination.vue'
|
import Pagination from '@/components/Pagination.vue'
|
||||||
import TaskDialog from './TaskDialog.vue'
|
import TaskDialog from './TaskDialog.vue'
|
||||||
import RepoDialog from './RepoDialog.vue'
|
import RepoDialog from './RepoDialog.vue'
|
||||||
|
import LogViewer from '@/views/history/LogViewer.vue'
|
||||||
import { Plus, Play, Pencil, Trash2, Search, ScrollText, GitBranch, Terminal, Server, Monitor, X, Loader2, Wifi, WifiOff, Zap, ZapOff, Copy, Tag } from 'lucide-vue-next'
|
import { Plus, Play, Pencil, Trash2, Search, ScrollText, GitBranch, Terminal, Server, Monitor, X, Loader2, Wifi, WifiOff, Zap, ZapOff, Copy, Tag } from 'lucide-vue-next'
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||||
|
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'
|
||||||
import { api, type Agent, type Task } from '@/api'
|
import { api, type Agent, type Task } from '@/api'
|
||||||
import { toast } from 'vue-sonner'
|
import { toast } from 'vue-sonner'
|
||||||
import { useSiteSettings } from '@/composables/useSiteSettings'
|
import { useSiteSettings } from '@/composables/useSiteSettings'
|
||||||
@@ -30,7 +32,7 @@ const deleteTaskId = ref<string | null>(null)
|
|||||||
|
|
||||||
const filterName = ref('')
|
const filterName = ref('')
|
||||||
const filterTags = ref('')
|
const filterTags = ref('')
|
||||||
const filterType = ref('all')
|
const filterType = ref<string>(TASK_TYPE.NORMAL)
|
||||||
const filterAgentId = ref<string | null>(null)
|
const filterAgentId = ref<string | null>(null)
|
||||||
const currentPage = ref(1)
|
const currentPage = ref(1)
|
||||||
const total = ref(0)
|
const total = ref(0)
|
||||||
@@ -147,11 +149,34 @@ function duplicateTask(task: Task) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const showBatchDeleteDialog = ref(false)
|
||||||
|
|
||||||
function confirmDelete(id: string) {
|
function confirmDelete(id: string) {
|
||||||
deleteTaskId.value = id
|
deleteTaskId.value = id
|
||||||
showDeleteDialog.value = true
|
showDeleteDialog.value = true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function confirmBatchDelete() {
|
||||||
|
if (total.value === 0) return
|
||||||
|
showBatchDeleteDialog.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
async function batchDeleteTasks() {
|
||||||
|
try {
|
||||||
|
const res = await api.tasks.batchDeleteByQuery({
|
||||||
|
name: filterName.value || undefined,
|
||||||
|
tags: filterTags.value || undefined,
|
||||||
|
type: filterType.value === 'all' ? undefined : filterType.value,
|
||||||
|
agent_id: filterAgentId.value || undefined
|
||||||
|
})
|
||||||
|
toast.success(`成功删除 ${res.count} 个任务`)
|
||||||
|
loadTasks()
|
||||||
|
} catch {
|
||||||
|
toast.error('批量删除失败')
|
||||||
|
}
|
||||||
|
showBatchDeleteDialog.value = false
|
||||||
|
}
|
||||||
|
|
||||||
async function deleteTask() {
|
async function deleteTask() {
|
||||||
if (!deleteTaskId.value) return
|
if (!deleteTaskId.value) return
|
||||||
try {
|
try {
|
||||||
@@ -189,8 +214,27 @@ async function toggleTask(task: Task, enabled: boolean) {
|
|||||||
} catch { toast.error('操作失败') }
|
} catch { toast.error('操作失败') }
|
||||||
}
|
}
|
||||||
|
|
||||||
function viewLogs(taskId: string) {
|
const showLogViewer = ref(false)
|
||||||
router.push({ path: '/history', query: { task_id: taskId } })
|
const selectedLogId = ref<string | undefined>()
|
||||||
|
const latestLogStatus = ref('')
|
||||||
|
const latestLogTitle = ref('')
|
||||||
|
|
||||||
|
async function viewLogs(taskId: string) {
|
||||||
|
try {
|
||||||
|
const res = await api.logs.list({ task_id: taskId, page: 1, page_size: 1 })
|
||||||
|
if (res.data && res.data.length > 0) {
|
||||||
|
const latestLog = res.data[0]
|
||||||
|
if (!latestLog) return
|
||||||
|
latestLogTitle.value = latestLog.task_name || ''
|
||||||
|
latestLogStatus.value = latestLog.status || ''
|
||||||
|
selectedLogId.value = latestLog.id
|
||||||
|
showLogViewer.value = true
|
||||||
|
} else {
|
||||||
|
toast.info('该任务暂无执行日志')
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
toast.error('获取日志失败')
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function getTaskTypeTitle(type: string) {
|
function getTaskTypeTitle(type: string) {
|
||||||
@@ -221,12 +265,12 @@ watch(() => route.query.agent_id, (newVal) => {
|
|||||||
<template>
|
<template>
|
||||||
<div class="space-y-6">
|
<div class="space-y-6">
|
||||||
<div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
|
<div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
|
||||||
<div>
|
<div class="flex items-center gap-3">
|
||||||
<h2 class="text-xl sm:text-2xl font-bold tracking-tight">定时任务</h2>
|
<h2 class="text-xl sm:text-2xl font-bold tracking-tight">定时任务</h2>
|
||||||
<p class="text-muted-foreground text-sm">管理和调度自动化任务</p>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="flex flex-col sm:flex-row gap-2.5 w-full md:w-auto">
|
<div class="flex flex-col sm:flex-row gap-2.5 w-full md:w-auto">
|
||||||
<!-- 第1行: 搜索框 -->
|
<!-- 搜索与标签 -->
|
||||||
<div class="flex items-center gap-2 w-full sm:w-auto">
|
<div class="flex items-center gap-2 w-full sm:w-auto">
|
||||||
<div class="relative flex-1 sm:flex-none">
|
<div class="relative flex-1 sm:flex-none">
|
||||||
<Search class="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
<Search class="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||||
@@ -239,34 +283,48 @@ watch(() => route.query.agent_id, (newVal) => {
|
|||||||
@input="handleSearch" />
|
@input="handleSearch" />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<!-- 第2行: 下拉框与按钮 -->
|
|
||||||
<div class="flex items-center gap-2 w-full sm:w-auto mt-1 sm:mt-0">
|
<div class="flex items-center gap-3 w-full sm:w-auto">
|
||||||
<div class="relative flex-1 sm:flex-none">
|
<!-- 移动端类型切换 -->
|
||||||
<Select v-model="filterType" @update:model-value="handleTypeChange">
|
<div class="md:hidden flex-1 shrink-0">
|
||||||
<SelectTrigger class="h-9 w-full sm:w-28 text-sm">
|
<Select v-model="filterType" @update:model-value="handleTypeChange">
|
||||||
<SelectValue placeholder="所有类型" />
|
<SelectTrigger class="h-9 w-full text-sm">
|
||||||
</SelectTrigger>
|
<SelectValue />
|
||||||
<SelectContent>
|
</SelectTrigger>
|
||||||
<SelectItem value="all">所有类型</SelectItem>
|
<SelectContent>
|
||||||
<SelectItem :value="TASK_TYPE.NORMAL">定时任务</SelectItem>
|
<SelectItem :value="TASK_TYPE.NORMAL">定时任务</SelectItem>
|
||||||
<SelectItem :value="TASK_TYPE.REPO">仓库同步</SelectItem>
|
<SelectItem :value="TASK_TYPE.REPO">仓库同步</SelectItem>
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div v-if="filterAgentId"
|
<div v-if="filterAgentId"
|
||||||
class="hidden sm:flex items-center gap-1 px-2 py-1 bg-primary/10 text-primary rounded-md text-sm shrink-0">
|
class="hidden sm:flex items-center gap-1 px-2 py-1 bg-primary/10 text-primary rounded-md text-sm shrink-0">
|
||||||
<Server class="h-3.5 w-3.5" />
|
<Server class="h-3.5 w-3.5" />
|
||||||
<span>{{ filterAgentName }}</span>
|
<span>{{ filterAgentName }}</span>
|
||||||
<X class="h-3.5 w-3.5 cursor-pointer hover:text-destructive" @click="clearAgentFilter" />
|
<X class="h-3.5 w-3.5 cursor-pointer hover:text-destructive" @click="clearAgentFilter" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="flex items-center gap-2 shrink-0 justify-end">
|
<div class="flex items-center gap-2 shrink-0 justify-end">
|
||||||
<Button variant="outline" @click="openCreateRepo" class="shrink-0 px-3 h-9">
|
<!-- 动态新增按钮 -->
|
||||||
<GitBranch class="h-4 w-4 sm:mr-2" /> <span class="hidden sm:inline">仓库同步</span>
|
<Button variant="outline" class="shrink-0 px-3 h-9 shadow-sm text-destructive border-destructive/20 hover:bg-destructive/10" @click="confirmBatchDelete">
|
||||||
|
<Trash2 class="h-4 w-4 sm:mr-2" /> <span class="hidden sm:inline">批量删除</span>
|
||||||
</Button>
|
</Button>
|
||||||
<Button @click="openCreate" class="shrink-0 px-3 h-9">
|
<Button v-if="filterType === TASK_TYPE.NORMAL" @click="openCreate" class="shrink-0 px-3 h-9 shadow-sm">
|
||||||
<Plus class="h-4 w-4 sm:mr-2" /> <span class="hidden sm:inline">新建任务</span>
|
<Plus class="h-4 w-4 sm:mr-2" /> <span class="hidden sm:inline">新建任务</span>
|
||||||
</Button>
|
</Button>
|
||||||
|
<Button v-else-if="filterType === TASK_TYPE.REPO" @click="openCreateRepo" class="shrink-0 px-3 h-9 shadow-sm">
|
||||||
|
<GitBranch class="h-4 w-4 sm:mr-2" /> <span class="hidden sm:inline">同步仓库</span>
|
||||||
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- 桌面端类型切换移到后面 -->
|
||||||
|
<Tabs :model-value="filterType" @update:model-value="v => { filterType = String(v); handleTypeChange() }" class="shrink-0 hidden md:block">
|
||||||
|
<TabsList class="h-9 p-1 bg-muted/30 border">
|
||||||
|
<TabsTrigger :value="TASK_TYPE.NORMAL" class="px-4 h-7 text-[13px]">定时任务</TabsTrigger>
|
||||||
|
<TabsTrigger :value="TASK_TYPE.REPO" class="px-4 h-7 text-[13px]">仓库同步</TabsTrigger>
|
||||||
|
</TabsList>
|
||||||
|
</Tabs>
|
||||||
</div>
|
</div>
|
||||||
<!-- 移动端 agent 过滤标签 -->
|
<!-- 移动端 agent 过滤标签 -->
|
||||||
<div v-if="filterAgentId"
|
<div v-if="filterAgentId"
|
||||||
@@ -282,7 +340,9 @@ watch(() => route.query.agent_id, (newVal) => {
|
|||||||
<!-- 表头 -->
|
<!-- 表头 -->
|
||||||
<div
|
<div
|
||||||
class="flex flex-wrap sm:flex-nowrap items-center gap-x-2 gap-y-2 sm:gap-4 px-3 sm:px-4 py-2 sm:py-1.5 border-b bg-muted/20 text-xs sm:text-sm text-muted-foreground font-medium min-w-0 sm:min-w-[1000px]">
|
class="flex flex-wrap sm:flex-nowrap items-center gap-x-2 gap-y-2 sm:gap-4 px-3 sm:px-4 py-2 sm:py-1.5 border-b bg-muted/20 text-xs sm:text-sm text-muted-foreground font-medium min-w-0 sm:min-w-[1000px]">
|
||||||
<span class="w-10 sm:w-12 shrink-0 max-sm:order-1">序号</span>
|
<div class="w-10 sm:w-12 shrink-0 flex items-center gap-2 max-sm:order-1 pl-1">
|
||||||
|
<span class="text-xs sm:text-sm">序号</span>
|
||||||
|
</div>
|
||||||
<span class="w-8 shrink-0 text-center max-sm:order-2">类型</span>
|
<span class="w-8 shrink-0 text-center max-sm:order-2">类型</span>
|
||||||
<span class="flex-1 min-w-0 sm:flex-none sm:w-40 md:w-48 lg:w-56 shrink-0 max-sm:order-3">名称</span>
|
<span class="flex-1 min-w-0 sm:flex-none sm:w-40 md:w-48 lg:w-56 shrink-0 max-sm:order-3">名称</span>
|
||||||
<span class="w-24 sm:w-32 shrink-0 hidden md:block">执行位置</span>
|
<span class="w-24 sm:w-32 shrink-0 hidden md:block">执行位置</span>
|
||||||
@@ -304,8 +364,10 @@ watch(() => route.query.agent_id, (newVal) => {
|
|||||||
</div>
|
</div>
|
||||||
<div v-for="(task, index) in tasks" :key="task.id"
|
<div v-for="(task, index) in tasks" :key="task.id"
|
||||||
class="flex flex-wrap sm:flex-nowrap items-center gap-x-2 gap-y-2 sm:gap-4 px-3 sm:px-4 py-2.5 sm:py-1.5 hover:bg-muted/30 transition-colors">
|
class="flex flex-wrap sm:flex-nowrap items-center gap-x-2 gap-y-2 sm:gap-4 px-3 sm:px-4 py-2.5 sm:py-1.5 hover:bg-muted/30 transition-colors">
|
||||||
<span class="w-10 sm:w-12 shrink-0 text-muted-foreground text-xs sm:text-sm max-sm:order-1">#{{ total -
|
<div class="w-10 sm:w-12 shrink-0 flex items-center gap-2 max-sm:order-1 pl-1">
|
||||||
(currentPage - 1) * pageSize - index }}</span>
|
<span class="text-muted-foreground text-xs sm:text-sm">#{{ total -
|
||||||
|
(currentPage - 1) * pageSize - index }}</span>
|
||||||
|
</div>
|
||||||
<span class="w-8 shrink-0 flex justify-center max-sm:order-2" :title="getTaskTypeTitle(task.type || 'task')">
|
<span class="w-8 shrink-0 flex justify-center max-sm:order-2" :title="getTaskTypeTitle(task.type || 'task')">
|
||||||
<GitBranch v-if="task.type === TASK_TYPE.REPO" class="h-3.5 w-3.5 sm:h-4 sm:w-4 text-primary" />
|
<GitBranch v-if="task.type === TASK_TYPE.REPO" class="h-3.5 w-3.5 sm:h-4 sm:w-4 text-primary" />
|
||||||
<Terminal v-else class="h-3.5 w-3.5 sm:h-4 sm:w-4 text-primary" />
|
<Terminal v-else class="h-3.5 w-3.5 sm:h-4 sm:w-4 text-primary" />
|
||||||
@@ -397,7 +459,29 @@ watch(() => route.query.agent_id, (newVal) => {
|
|||||||
<!-- 仓库同步弹窗 -->
|
<!-- 仓库同步弹窗 -->
|
||||||
<RepoDialog v-model:open="showRepoDialog" :task="editingTask" :is-edit="isEdit" @saved="loadTasks" />
|
<RepoDialog v-model:open="showRepoDialog" :task="editingTask" :is-edit="isEdit" @saved="loadTasks" />
|
||||||
|
|
||||||
<!-- 删除确认 -->
|
<!-- 最新日志全屏查看 -->
|
||||||
|
<LogViewer v-model:open="showLogViewer" :task-name="latestLogTitle"
|
||||||
|
:log-id="selectedLogId" :initial-status="latestLogStatus" />
|
||||||
|
|
||||||
|
<!-- 删除确认 (批量) -->
|
||||||
|
<AlertDialog v-model:open="showBatchDeleteDialog">
|
||||||
|
<AlertDialogContent>
|
||||||
|
<AlertDialogHeader>
|
||||||
|
<AlertDialogTitle>确认批量删除</AlertDialogTitle>
|
||||||
|
<AlertDialogDescription>
|
||||||
|
将会删除当前所有过滤条件下匹配的 <b>{{ total }}</b> 个任务。操作不可撤销。
|
||||||
|
</AlertDialogDescription>
|
||||||
|
</AlertDialogHeader>
|
||||||
|
<AlertDialogFooter>
|
||||||
|
<AlertDialogCancel>取消</AlertDialogCancel>
|
||||||
|
<AlertDialogAction class="bg-destructive text-white hover:bg-destructive/90" @click="batchDeleteTasks">
|
||||||
|
确认删除
|
||||||
|
</AlertDialogAction>
|
||||||
|
</AlertDialogFooter>
|
||||||
|
</AlertDialogContent>
|
||||||
|
</AlertDialog>
|
||||||
|
|
||||||
|
<!-- 删除确认 (单个) -->
|
||||||
<AlertDialog v-model:open="showDeleteDialog">
|
<AlertDialog v-model:open="showDeleteDialog">
|
||||||
<AlertDialogContent>
|
<AlertDialogContent>
|
||||||
<AlertDialogHeader>
|
<AlertDialogHeader>
|
||||||
|
|||||||
Reference in New Issue
Block a user