package constant import ( "os" "path/filepath" "time" ) var ( // ConfigPath 配置文件路径 ConfigPath string // DataDir 数据目录 DataDir string // DefaultDBPath 默认数据库路径 DefaultDBPath string // WebDistDir 前端构建目录 WebDistDir string // ScriptsWorkDir 脚本工作目录 ScriptsWorkDir string ) func init() { rootDir := ResolveAppRootDir() ConfigPath = filepath.Clean(filepath.Join(rootDir, "configs", "config.ini")) DataDir = filepath.Clean(filepath.Join(rootDir, "data")) DefaultDBPath = filepath.Clean(filepath.Join(rootDir, "data", "baihu.db")) WebDistDir = filepath.Clean(filepath.Join(rootDir, "web", "dist")) ScriptsWorkDir = filepath.Clean(filepath.Join(rootDir, "data", "scripts")) } // ResolveAppRootDir 获取应用程序的绝对根目录路径。 func ResolveAppRootDir() string { // 1. 检查当前工作目录(CWD)及其上级目录 if cwd, err := os.Getwd(); err == nil { dir := cwd for { if _, err := os.Stat(filepath.Join(dir, "configs", "config.ini")); err == nil { return dir } if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil { return dir } parent := filepath.Dir(dir) if parent == dir { break } dir = parent } } // 2. 检查当前可执行文件路径及其上级目录 if exe, err := os.Executable(); err == nil { dir := filepath.Dir(exe) for { if _, err := os.Stat(filepath.Join(dir, "configs", "config.ini")); err == nil { return dir } if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil { return dir } parent := filepath.Dir(dir) if parent == dir { break } dir = parent } } // 3. 兜底回退到当前工作目录 if cwd, err := os.Getwd(); err == nil { return cwd } return "." } const ( // DefaultRole 默认用户角色 DefaultRole = "user" // AdminRole 管理员角色 AdminRole = "admin" // CookieName Cookie 名称 CookieName = "BHToken" // DefaultTaskTimeout 默认任务超时时间(分钟) DefaultTaskTimeout = 30 // Settings Section 常量 SectionSite = "site" SectionSystem = "system" SectionScheduler = "scheduler" SectionSecurity = "security" SectionNotify = "notify" // Site Settings Key 常量 KeyTitle = "title" KeySubtitle = "subtitle" KeyIcon = "icon" KeyPageSize = "page_size" KeyCookieDays = "cookie_days" KeyOpenapiToken = "openapi_token" // Security Settings Key 常量 KeySecret = "secret" // System Settings Key 常量 KeyInitialized = "initialized" // KeyLogRetention = "log_retention" // Deprecated // Log Retention Keys KeySystemNoticeDays = "system_notice_days" KeySystemNoticeMaxCount = "system_notice_max_count" KeyPushLogDays = "push_log_days" KeyPushLogMaxCount = "push_log_max_count" KeyLoginLogDays = "login_log_days" KeyLoginLogMaxCount = "login_log_max_count" KeySchedulerLogDays = "scheduler_log_days" KeySchedulerLogMaxCount = "scheduler_log_max_count" // Scheduler Settings Key 常量 KeyWorkerCount = "worker_count" KeyQueueSize = "queue_size" KeyRateInterval = "rate_interval" // Notify Settings Key 常量 KeyNotifyChannels = "channels" KeyNotifyEvents = "events" KeyNotifyToken = "notify_token" KeyNotifyPrefix = "notify_prefix" // Notify Templates Keys KeyNotifyTemplateUserLoginTitle = "notify_template_user_login_title" KeyNotifyTemplateUserLoginText = "notify_template_user_login_text" KeyNotifyTemplateBruteForceLoginTitle = "notify_template_brute_force_login_title" KeyNotifyTemplateBruteForceLoginText = "notify_template_brute_force_login_text" KeyNotifyTemplatePasswordChangedTitle = "notify_template_password_changed_title" KeyNotifyTemplatePasswordChangedText = "notify_template_password_changed_text" KeyNotifyTemplateTaskSuccessTitle = "notify_template_task_success_title" KeyNotifyTemplateTaskSuccessText = "notify_template_task_success_text" KeyNotifyTemplateTaskFailedTitle = "notify_template_task_failed_title" KeyNotifyTemplateTaskFailedText = "notify_template_task_failed_text" KeyNotifyTemplateTaskTimeoutTitle = "notify_template_task_timeout_title" KeyNotifyTemplateTaskTimeoutText = "notify_template_task_timeout_text" // 事件绑定类型 BindingTypeSystem = "system" BindingTypeTask = "task" // 系统事件类型 EventUserLogin = "user_login" EventBruteForceLogin = "brute_force_login" EventPasswordChanged = "password_changed" // 任务事件类型 EventTaskSuccess = "task_success" EventTaskFailed = "task_failed" EventTaskTimeout = "task_timeout" EventTaskRunning = "task_running" EventTaskQueued = "task_queued" // 其他事件类型 EventSystemNotice = "system_notice" EventSchedulerLog = "scheduler_log" EventNotifySent = "notify_sent" EventAppLogAdded = "app_log_added" // WebSocket 消息类型 WSTypeHeartbeat = "heartbeat" WSTypeHeartbeatAck = "heartbeat_ack" WSTypeTasks = "tasks" WSTypeTaskResult = "task_result" WSTypeTaskLog = "task_log" WSTypeExecute = "execute" WSTypeUpdate = "update" WSTypeDisconnect = "disconnect" WSTypeConnected = "connected" WSTypeDisabled = "disabled" WSTypeEnabled = "enabled" WSTypeFetchTasks = "fetch_tasks" WSTypeTaskHeartbeat = "task_heartbeat" WSTypeStop = "stop" // 任务状态 TaskStatusSuccess = "success" TaskStatusFailed = "failed" TaskStatusRunning = "running" TaskStatusPending = "pending" TaskStatusTimeout = "timeout" TaskStatusCancelled = "cancelled" TaskStatusQueued = "queued" // 任务类型 TaskTypeNormal = "task" TaskTypeRepo = "repo" // 任务置顶类型 PinTypeNone = "none" PinTypeTop = "top" // 触发类型 TriggerTypeCron = "cron" TriggerTypeBaihuStartup = "baihu_startup" // Agent 状态 AgentStatusOnline = "online" AgentStatusOffline = "offline" // AppLog 分类 LogCategoryDefault = "default" LogCategorySystemNotice = "system_notice" LogCategoryPushLog = "push_log" LogCategoryLoginLog = "login_log" LogCategorySchedulerLog = "scheduler_log" // AppLog 级别 LogLevelInfo = "info" LogLevelWarning = "warning" LogLevelError = "error" // AppLog 状态 LogStatusUnread = "unread" LogStatusRead = "read" LogStatusSuccess = "success" LogStatusFailed = "failed" // Env Type EnvTypeNormal = "normal" EnvTypeSecret = "secret" // WebSocket 安全常量 // PongWait 收到 pong 的超时时间 PongWait = 60 * time.Second // PingPeriod 发送 ping 的周期 PingPeriod = (PongWait * 9) / 10 // MaxMessageSize 允许的最大消息大小 MaxMessageSize = 1024 * 1024 // 1MB // MaxLogSize 允许的最大日志大小 (保留末尾 10MB) MaxLogSize = 10 * 1024 * 1024 // 10MB // ScriptsDirPlaceholder 脚本目录占位符 ScriptsDirPlaceholder = "$SCRIPTS_DIR$" ) // TablePrefix 表前缀,从配置文件读取 var TablePrefix string // Runtime 数据库配置快照,用于需要单独启动内部子进程(如 reposync)时显式透传数据库连接信息, // 避免主进程启动阶段清理环境变量后,子进程意外回退到默认 sqlite 配置。 var ( RuntimeDBType string RuntimeDBHost string RuntimeDBPort int RuntimeDBUser string RuntimeDBPassword string RuntimeDBName string RuntimeDBPath string RuntimeDBDSN string RuntimeDBTablePrefix string ) // Secret JWT和密码salt密钥,运行中自动从数据库加载 var Secret string // DemoMode 演示模式,从环境变量读取 var DemoMode bool // DefaultIcon 默认站点图标 var DefaultIcon = `` // DefaultSettings 默认系统设置 var DefaultSettings = map[string]map[string]string{ SectionSite: { KeyTitle: "白虎面板", KeySubtitle: "极致轻量、高性能的自动化任务调度平台", KeyIcon: DefaultIcon, KeyPageSize: "10", KeyCookieDays: "7", }, SectionScheduler: { KeyWorkerCount: "4", KeyQueueSize: "100", KeyRateInterval: "200", }, SectionNotify: { KeyNotifyPrefix: "[白虎面板]", // Login KeyNotifyTemplateUserLoginTitle: "用户登录(成功/失败)", KeyNotifyTemplateUserLoginText: "用户 {{username}} 在 IP {{ip}} 登录{{status_label}}\n{{message}}", KeyNotifyTemplateBruteForceLoginTitle: "系统安全警告", KeyNotifyTemplateBruteForceLoginText: "检测到 IP {{ip}} 正在尝试暴力破解用户 {{username}}", KeyNotifyTemplatePasswordChangedTitle: "账户安全通知", KeyNotifyTemplatePasswordChangedText: "用户 {{username}} 刚刚修改了密码", // Task KeyNotifyTemplateTaskSuccessTitle: "任务[{{task_name}}] 成功", KeyNotifyTemplateTaskSuccessText: "任务 #{{task_id}} {{task_name}}\n状态: 成功\n耗时: {{duration}}ms\n执行结果: {{output}}", KeyNotifyTemplateTaskFailedTitle: "任务[{{task_name}}] 失败", KeyNotifyTemplateTaskFailedText: "任务 #{{task_id}} {{task_name}}\n状态: 失败\n执行时间: {{start_time}}\n原因: {{error}}\n最后输出: {{output}}", KeyNotifyTemplateTaskTimeoutTitle: "任务[{{task_name}}] 超时", KeyNotifyTemplateTaskTimeoutText: "任务 #{{task_id}} {{task_name}}\n状态: 超时\n耗时: {{duration}}ms\n最后输出: {{output}}", }, }