mirror of
https://github.com/whyour/qinglong.git
synced 2026-08-11 19:05:20 +08:00
Compare commits
47
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0deebcfc88 | ||
|
|
07fcb09cc6 | ||
|
|
6aefc61be6 | ||
|
|
bf9be821ba | ||
|
|
d42074f76a | ||
|
|
5c798a0e93 | ||
|
|
15d94f469b | ||
|
|
777fd3fb23 | ||
|
|
1f2fd8ac02 | ||
|
|
06aa07329f | ||
|
|
4cf2858ab0 | ||
|
|
4cb9f57479 | ||
|
|
c369514741 | ||
|
|
0e28e1b6c4 | ||
|
|
2ff7a186e7 | ||
|
|
b2b1777c6b | ||
|
|
f355b4e441 | ||
|
|
489454daa0 | ||
|
|
db93ca9aa9 | ||
|
|
4758400df6 | ||
|
|
73f8f3c5fa | ||
|
|
494ccb3c08 | ||
|
|
399728b433 | ||
|
|
52a1de5063 | ||
|
|
18f27a9a69 | ||
|
|
07951964a1 | ||
|
|
a1f888af59 | ||
|
|
f7472b6e74 | ||
|
|
a7baeba755 | ||
|
|
e4f733320d | ||
|
|
55c92dc320 | ||
|
|
50769c43dd | ||
|
|
0587644a6b | ||
|
|
87b934aafe | ||
|
|
7a92e7c6ab | ||
|
|
1d8403c0ec | ||
|
|
ef9e38f167 | ||
|
|
c9bd053fbd | ||
|
|
57939391b9 | ||
|
|
394e96bbf8 | ||
|
|
47c194c1f4 | ||
|
|
7d65d96ebd | ||
|
|
224000b63b | ||
|
|
1c18668bad | ||
|
|
f94582b68d | ||
|
|
eb1c00984c | ||
|
|
1a185f5682 |
+1
-2
@@ -1,6 +1,5 @@
|
|||||||
GRPC_PORT=5500
|
GRPC_PORT=5500
|
||||||
BACK_PORT=5600
|
BACK_PORT=5700
|
||||||
PORT=5700
|
|
||||||
|
|
||||||
LOG_LEVEL='info'
|
LOG_LEVEL='info'
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,4 @@
|
|||||||
|
---
|
||||||
|
name: Bug Fixer
|
||||||
|
description: Fix this issue following our error handling pattern.
|
||||||
|
---
|
||||||
+28
-20
@@ -20,12 +20,14 @@ jobs:
|
|||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
- uses: wearerequired/git-mirror-action@v1
|
- uses: Yikun/hub-mirror-action@master
|
||||||
env:
|
|
||||||
SSH_PRIVATE_KEY: ${{ secrets.GITLAB_SSH_PK }}
|
|
||||||
with:
|
with:
|
||||||
source-repo: https://github.com/whyour/qinglong.git
|
src: github/whyour
|
||||||
destination-repo: git@gitlab.com:whyour/qinglong.git
|
dst: gitlab/whyour
|
||||||
|
dst_key: ${{ secrets.GITLAB_SSH_PK }}
|
||||||
|
dst_token: ${{ secrets.GITLAB_TOKEN }}
|
||||||
|
static_list: "qinglong"
|
||||||
|
force_update: true
|
||||||
|
|
||||||
code_gitee:
|
code_gitee:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
@@ -33,12 +35,14 @@ jobs:
|
|||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
- uses: wearerequired/git-mirror-action@v1
|
- uses: Yikun/hub-mirror-action@master
|
||||||
env:
|
|
||||||
SSH_PRIVATE_KEY: ${{ secrets.GITLAB_SSH_PK }}
|
|
||||||
with:
|
with:
|
||||||
source-repo: https://github.com/whyour/qinglong.git
|
src: github/whyour
|
||||||
destination-repo: git@gitee.com:whyour/qinglong.git
|
dst: gitee/whyour
|
||||||
|
dst_key: ${{ secrets.GITLAB_SSH_PK }}
|
||||||
|
dst_token: ${{ secrets.GITEE_TOKEN }}
|
||||||
|
static_list: "qinglong"
|
||||||
|
force_update: true
|
||||||
|
|
||||||
build-static:
|
build-static:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
@@ -82,12 +86,14 @@ jobs:
|
|||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
- uses: wearerequired/git-mirror-action@v1
|
- uses: Yikun/hub-mirror-action@master
|
||||||
env:
|
|
||||||
SSH_PRIVATE_KEY: ${{ secrets.GITLAB_SSH_PK }}
|
|
||||||
with:
|
with:
|
||||||
source-repo: https://github.com/whyour/qinglong-static.git
|
src: github/whyour
|
||||||
destination-repo: git@gitlab.com:whyour/qinglong-static.git
|
dst: gitlab/whyour
|
||||||
|
dst_key: ${{ secrets.GITLAB_SSH_PK }}
|
||||||
|
dst_token: ${{ secrets.GITLAB_TOKEN }}
|
||||||
|
static_list: "qinglong-static"
|
||||||
|
force_update: true
|
||||||
|
|
||||||
static_gitee:
|
static_gitee:
|
||||||
needs: build-static
|
needs: build-static
|
||||||
@@ -96,12 +102,14 @@ jobs:
|
|||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
- uses: wearerequired/git-mirror-action@v1
|
- uses: Yikun/hub-mirror-action@master
|
||||||
env:
|
|
||||||
SSH_PRIVATE_KEY: ${{ secrets.GITLAB_SSH_PK }}
|
|
||||||
with:
|
with:
|
||||||
source-repo: https://github.com/whyour/qinglong-static.git
|
src: github/whyour
|
||||||
destination-repo: git@gitee.com:whyour/qinglong-static.git
|
dst: gitee/whyour
|
||||||
|
dst_key: ${{ secrets.GITLAB_SSH_PK }}
|
||||||
|
dst_token: ${{ secrets.GITEE_TOKEN }}
|
||||||
|
static_list: "qinglong-static"
|
||||||
|
force_update: true
|
||||||
|
|
||||||
build:
|
build:
|
||||||
needs: build-static
|
needs: build-static
|
||||||
@@ -17,7 +17,7 @@ export default defineConfig({
|
|||||||
publicPath: process.env.NODE_ENV === 'production' ? './' : '/',
|
publicPath: process.env.NODE_ENV === 'production' ? './' : '/',
|
||||||
proxy: {
|
proxy: {
|
||||||
[`${baseUrl}api`]: {
|
[`${baseUrl}api`]: {
|
||||||
target: 'http://127.0.0.1:5600/',
|
target: 'http://127.0.0.1:5700/',
|
||||||
changeOrigin: true,
|
changeOrigin: true,
|
||||||
ws: true,
|
ws: true,
|
||||||
pathRewrite: { [`^${baseUrl}api`]: '/api' },
|
pathRewrite: { [`^${baseUrl}api`]: '/api' },
|
||||||
|
|||||||
@@ -0,0 +1,252 @@
|
|||||||
|
# Multi-User Data Migration Guide
|
||||||
|
|
||||||
|
This document explains how to migrate existing data to the multi-user system.
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
When upgrading to the multi-user version of Qinglong, all existing data (cron tasks, environment variables, subscriptions, and dependencies) will be treated as "legacy data" that is accessible to all users.
|
||||||
|
|
||||||
|
To properly isolate data between users, you need to migrate existing data to specific user accounts.
|
||||||
|
|
||||||
|
## Migration Script
|
||||||
|
|
||||||
|
The `migrate-to-multiuser.js` script helps you assign existing legacy data to specific users.
|
||||||
|
|
||||||
|
### Prerequisites
|
||||||
|
|
||||||
|
- Node.js installed
|
||||||
|
- Sequelize and dotenv packages (already included in the project)
|
||||||
|
- At least one user created in the User Management interface
|
||||||
|
|
||||||
|
### Usage
|
||||||
|
|
||||||
|
#### 1. List All Users
|
||||||
|
|
||||||
|
First, see all available users in your system:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
node migrate-to-multiuser.js --list-users
|
||||||
|
```
|
||||||
|
|
||||||
|
Output example:
|
||||||
|
```
|
||||||
|
Users in the system:
|
||||||
|
ID Username Role Status
|
||||||
|
-- -------- ---- ------
|
||||||
|
1 admin Admin Enabled
|
||||||
|
2 user1 User Enabled
|
||||||
|
3 user2 User Enabled
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 2. Preview Migration (Dry Run)
|
||||||
|
|
||||||
|
Before making changes, preview what will be migrated:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
node migrate-to-multiuser.js --userId=1 --dry-run
|
||||||
|
```
|
||||||
|
|
||||||
|
Or by username:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
node migrate-to-multiuser.js --username=admin --dry-run
|
||||||
|
```
|
||||||
|
|
||||||
|
Output example:
|
||||||
|
```
|
||||||
|
Legacy Data Statistics:
|
||||||
|
Cron tasks: 15
|
||||||
|
Environment variables: 8
|
||||||
|
Subscriptions: 3
|
||||||
|
Dependencies: 5
|
||||||
|
|
||||||
|
DRY RUN: No changes will be made.
|
||||||
|
|
||||||
|
Would assign all legacy data to user ID 1
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 3. Perform Migration
|
||||||
|
|
||||||
|
Once you're ready, run the migration without `--dry-run`:
|
||||||
|
|
||||||
|
**By User ID:**
|
||||||
|
```bash
|
||||||
|
node migrate-to-multiuser.js --userId=1
|
||||||
|
```
|
||||||
|
|
||||||
|
**By Username:**
|
||||||
|
```bash
|
||||||
|
node migrate-to-multiuser.js --username=admin
|
||||||
|
```
|
||||||
|
|
||||||
|
Output example:
|
||||||
|
```
|
||||||
|
Found user 'admin' with ID 1
|
||||||
|
|
||||||
|
Legacy Data Statistics:
|
||||||
|
Cron tasks: 15
|
||||||
|
Environment variables: 8
|
||||||
|
Subscriptions: 3
|
||||||
|
Dependencies: 5
|
||||||
|
|
||||||
|
Migrating data to user ID 1...
|
||||||
|
✓ Migrated 15 cron tasks
|
||||||
|
✓ Migrated 8 environment variables
|
||||||
|
✓ Migrated 3 subscriptions
|
||||||
|
✓ Migrated 5 dependencies
|
||||||
|
|
||||||
|
✓ Migration completed successfully!
|
||||||
|
```
|
||||||
|
|
||||||
|
### Command Line Options
|
||||||
|
|
||||||
|
| Option | Description |
|
||||||
|
|--------|-------------|
|
||||||
|
| `--userId=<id>` | Assign all legacy data to user with this ID |
|
||||||
|
| `--username=<name>` | Assign all legacy data to user with this username |
|
||||||
|
| `--list-users` | List all users in the system |
|
||||||
|
| `--dry-run` | Show what would be changed without making changes |
|
||||||
|
| `--help` | Show help message |
|
||||||
|
|
||||||
|
## Migration Strategy
|
||||||
|
|
||||||
|
### Scenario 1: Single User to Multi-User
|
||||||
|
|
||||||
|
If you're upgrading from single-user to multi-user and want to keep all existing data under one admin account:
|
||||||
|
|
||||||
|
1. Create an admin user in the User Management interface
|
||||||
|
2. Run migration: `node migrate-to-multiuser.js --username=admin`
|
||||||
|
|
||||||
|
### Scenario 2: Distribute Data to Multiple Users
|
||||||
|
|
||||||
|
If you want to distribute existing data to different users:
|
||||||
|
|
||||||
|
1. Create all necessary user accounts first
|
||||||
|
2. Identify which data belongs to which user (you may need to do this manually by checking the database)
|
||||||
|
3. For each user, manually update the `userId` field in the database tables (`Crontabs`, `Envs`, `Subscriptions`, `Dependences`)
|
||||||
|
|
||||||
|
**SQL Example:**
|
||||||
|
```sql
|
||||||
|
-- Assign specific cron tasks to user ID 2
|
||||||
|
UPDATE Crontabs
|
||||||
|
SET userId = 2
|
||||||
|
WHERE name LIKE '%user2%' AND userId IS NULL;
|
||||||
|
|
||||||
|
-- Assign specific environment variables to user ID 2
|
||||||
|
UPDATE Envs
|
||||||
|
SET userId = 2
|
||||||
|
WHERE name LIKE '%USER2%' AND userId IS NULL;
|
||||||
|
```
|
||||||
|
|
||||||
|
### Scenario 3: Keep as Shared Data
|
||||||
|
|
||||||
|
If you want certain data to remain accessible to all users:
|
||||||
|
|
||||||
|
- Simply don't run the migration script
|
||||||
|
- Data with `userId = NULL` remains as "legacy data" accessible to everyone
|
||||||
|
- This is useful for shared cron tasks or environment variables
|
||||||
|
|
||||||
|
## Important Notes
|
||||||
|
|
||||||
|
1. **Backup First**: Always backup your database before running migration scripts
|
||||||
|
```bash
|
||||||
|
cp data/database.sqlite data/database.sqlite.backup
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Test in Dry Run**: Always use `--dry-run` first to see what will change
|
||||||
|
|
||||||
|
3. **One-Time Operation**: The script only migrates data where `userId` is NULL
|
||||||
|
- Already migrated data won't be changed
|
||||||
|
- You can run it multiple times safely
|
||||||
|
|
||||||
|
4. **Transaction Safety**: The migration uses database transactions
|
||||||
|
- If any error occurs, all changes are rolled back
|
||||||
|
- Your data remains safe
|
||||||
|
|
||||||
|
5. **User Must Exist**: The target user must exist before migration
|
||||||
|
- Create users in the User Management interface first
|
||||||
|
- Use `--list-users` to verify users exist
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
### Error: "User not found"
|
||||||
|
|
||||||
|
**Problem:** The specified user doesn't exist in the database.
|
||||||
|
|
||||||
|
**Solution:**
|
||||||
|
1. Run `node migrate-to-multiuser.js --list-users` to see available users
|
||||||
|
2. Create the user in User Management interface if needed
|
||||||
|
3. Use correct user ID or username
|
||||||
|
|
||||||
|
### Error: "Database connection failed"
|
||||||
|
|
||||||
|
**Problem:** Cannot connect to the database.
|
||||||
|
|
||||||
|
**Solution:**
|
||||||
|
1. Check that `data/database.sqlite` exists
|
||||||
|
2. Verify database file permissions
|
||||||
|
3. Check `QL_DATA_DIR` environment variable if using custom path
|
||||||
|
|
||||||
|
### Error: "Migration failed"
|
||||||
|
|
||||||
|
**Problem:** An error occurred during migration.
|
||||||
|
|
||||||
|
**Solution:**
|
||||||
|
1. Check the error message for details
|
||||||
|
2. Verify database is not corrupted
|
||||||
|
3. Restore from backup if needed
|
||||||
|
4. Check database file permissions
|
||||||
|
|
||||||
|
## Manual Migration
|
||||||
|
|
||||||
|
If you prefer to migrate data manually using SQL:
|
||||||
|
|
||||||
|
### Connect to Database
|
||||||
|
```bash
|
||||||
|
sqlite3 data/database.sqlite
|
||||||
|
```
|
||||||
|
|
||||||
|
### Check Legacy Data
|
||||||
|
```sql
|
||||||
|
-- Count legacy cron tasks
|
||||||
|
SELECT COUNT(*) FROM Crontabs WHERE userId IS NULL;
|
||||||
|
|
||||||
|
-- View legacy cron tasks
|
||||||
|
SELECT id, name, command FROM Crontabs WHERE userId IS NULL;
|
||||||
|
```
|
||||||
|
|
||||||
|
### Migrate Data
|
||||||
|
```sql
|
||||||
|
-- Migrate all legacy data to user ID 1
|
||||||
|
UPDATE Crontabs SET userId = 1 WHERE userId IS NULL;
|
||||||
|
UPDATE Envs SET userId = 1 WHERE userId IS NULL;
|
||||||
|
UPDATE Subscriptions SET userId = 1 WHERE userId IS NULL;
|
||||||
|
UPDATE Dependences SET userId = 1 WHERE userId IS NULL;
|
||||||
|
```
|
||||||
|
|
||||||
|
### Verify Migration
|
||||||
|
```sql
|
||||||
|
-- Check if any legacy data remains
|
||||||
|
SELECT
|
||||||
|
(SELECT COUNT(*) FROM Crontabs WHERE userId IS NULL) as legacy_crons,
|
||||||
|
(SELECT COUNT(*) FROM Envs WHERE userId IS NULL) as legacy_envs,
|
||||||
|
(SELECT COUNT(*) FROM Subscriptions WHERE userId IS NULL) as legacy_subs,
|
||||||
|
(SELECT COUNT(*) FROM Dependences WHERE userId IS NULL) as legacy_deps;
|
||||||
|
```
|
||||||
|
|
||||||
|
## Support
|
||||||
|
|
||||||
|
If you encounter issues with data migration:
|
||||||
|
|
||||||
|
1. Check this guide for solutions
|
||||||
|
2. Review the error messages carefully
|
||||||
|
3. Ensure you have a recent backup
|
||||||
|
4. Open an issue on GitHub with:
|
||||||
|
- Error messages
|
||||||
|
- Migration command used
|
||||||
|
- Database statistics (from dry run)
|
||||||
|
|
||||||
|
## Related Documentation
|
||||||
|
|
||||||
|
- [MULTI_USER_GUIDE.md](./MULTI_USER_GUIDE.md) - Complete multi-user feature guide
|
||||||
|
- [README.md](./README.md) - Main project documentation
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
# 多用户管理功能说明 (Multi-User Management Guide)
|
||||||
|
|
||||||
|
## 功能概述 (Overview)
|
||||||
|
|
||||||
|
青龙面板现已支持多用户管理和数据隔离功能。管理员可以创建多个用户账号,每个用户只能看到和操作自己的数据。
|
||||||
|
|
||||||
|
Qinglong now supports multi-user management with data isolation. Administrators can create multiple user accounts, and each user can only see and operate their own data.
|
||||||
|
|
||||||
|
## 用户角色 (User Roles)
|
||||||
|
|
||||||
|
### 管理员 (Admin)
|
||||||
|
- 可以访问所有用户的数据
|
||||||
|
- 可以创建、编辑、删除用户
|
||||||
|
- 可以管理系统设置
|
||||||
|
- Can access all users' data
|
||||||
|
- Can create, edit, and delete users
|
||||||
|
- Can manage system settings
|
||||||
|
|
||||||
|
### 普通用户 (Regular User)
|
||||||
|
- 只能访问自己创建的数据
|
||||||
|
- 可以管理自己的定时任务、环境变量、订阅和依赖
|
||||||
|
- 无法访问其他用户的数据
|
||||||
|
- Can only access their own data
|
||||||
|
- Can manage their own cron jobs, environment variables, subscriptions, and dependencies
|
||||||
|
- Cannot access other users' data
|
||||||
|
|
||||||
|
## API 使用 (API Usage)
|
||||||
|
|
||||||
|
### 用户管理接口 (User Management Endpoints)
|
||||||
|
|
||||||
|
所有用户管理接口需要管理员权限。
|
||||||
|
All user management endpoints require admin privileges.
|
||||||
|
|
||||||
|
#### 获取用户列表 (Get User List)
|
||||||
|
```
|
||||||
|
GET /api/user-management?searchValue=keyword
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 创建用户 (Create User)
|
||||||
|
```
|
||||||
|
POST /api/user-management
|
||||||
|
{
|
||||||
|
"username": "user1",
|
||||||
|
"password": "password123",
|
||||||
|
"role": 1, // 0: admin, 1: user
|
||||||
|
"status": 0 // 0: active, 1: disabled
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 更新用户 (Update User)
|
||||||
|
```
|
||||||
|
PUT /api/user-management
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"username": "user1",
|
||||||
|
"password": "newpassword",
|
||||||
|
"role": 1,
|
||||||
|
"status": 0
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 删除用户 (Delete Users)
|
||||||
|
```
|
||||||
|
DELETE /api/user-management
|
||||||
|
[1, 2, 3] // User IDs to delete
|
||||||
|
```
|
||||||
|
|
||||||
|
## 数据隔离 (Data Isolation)
|
||||||
|
|
||||||
|
### 定时任务 (Cron Jobs)
|
||||||
|
- 每个用户创建的定时任务会自动关联到该用户
|
||||||
|
- 用户只能查看、编辑、运行、删除自己的定时任务
|
||||||
|
- 管理员可以查看所有用户的定时任务
|
||||||
|
|
||||||
|
### 环境变量 (Environment Variables)
|
||||||
|
- 每个用户的环境变量相互隔离
|
||||||
|
- 用户只能查看和修改自己的环境变量
|
||||||
|
- 管理员可以查看所有环境变量
|
||||||
|
|
||||||
|
### 订阅和依赖 (Subscriptions and Dependencies)
|
||||||
|
- 用户数据完全隔离
|
||||||
|
- Only accessible by the owning user and admins
|
||||||
|
|
||||||
|
## 密码安全 (Password Security)
|
||||||
|
|
||||||
|
- 所有密码使用 bcrypt 加密存储
|
||||||
|
- 密码长度最少为 6 位
|
||||||
|
- 建议使用强密码
|
||||||
|
- All passwords are hashed with bcrypt
|
||||||
|
- Minimum password length is 6 characters
|
||||||
|
- Strong passwords are recommended
|
||||||
|
|
||||||
|
## 数据迁移 (Data Migration)
|
||||||
|
|
||||||
|
### 迁移工具 (Migration Tool)
|
||||||
|
|
||||||
|
项目提供了数据迁移脚本,可以将现有数据分配给特定用户。
|
||||||
|
|
||||||
|
A migration script is provided to assign existing data to specific users.
|
||||||
|
|
||||||
|
#### 使用方法 (Usage)
|
||||||
|
|
||||||
|
1. **列出所有用户 (List all users)**
|
||||||
|
```bash
|
||||||
|
node migrate-to-multiuser.js --list-users
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **预览迁移(不实际执行)(Dry run)**
|
||||||
|
```bash
|
||||||
|
node migrate-to-multiuser.js --userId=1 --dry-run
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **将数据迁移到指定用户ID (Migrate to user ID)**
|
||||||
|
```bash
|
||||||
|
node migrate-to-multiuser.js --userId=1
|
||||||
|
```
|
||||||
|
|
||||||
|
4. **将数据迁移到指定用户名 (Migrate to username)**
|
||||||
|
```bash
|
||||||
|
node migrate-to-multiuser.js --username=admin
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 注意事项 (Important Notes)
|
||||||
|
|
||||||
|
- 迁移脚本只会处理 `userId` 为空的数据(遗留数据)
|
||||||
|
- 已分配给用户的数据不会被修改
|
||||||
|
- 建议先使用 `--dry-run` 预览变更
|
||||||
|
- 迁移过程中如果出错会自动回滚
|
||||||
|
|
||||||
|
- The script only migrates data where `userId` is NULL (legacy data)
|
||||||
|
- Data already assigned to users will not be changed
|
||||||
|
- It's recommended to use `--dry-run` first to preview changes
|
||||||
|
- Changes are automatically rolled back if an error occurs
|
||||||
|
|
||||||
|
## 向后兼容 (Backward Compatibility)
|
||||||
|
|
||||||
|
- 原有的单用户系统管理员账号继续有效
|
||||||
|
- 已存在的数据可以被所有用户访问(遗留数据)
|
||||||
|
- 新创建的数据会自动关联到创建者
|
||||||
|
- The original system admin account remains valid
|
||||||
|
- Existing data is accessible by all users (legacy data)
|
||||||
|
- Newly created data is automatically associated with the creator
|
||||||
|
|
||||||
|
## 注意事项 (Notes)
|
||||||
|
|
||||||
|
1. **首次使用**:首次使用多用户功能时,建议先创建一个管理员账号作为备份
|
||||||
|
2. **密码管理**:请妥善保管用户密码,忘记密码需要管理员重置
|
||||||
|
3. **数据迁移**:使用提供的 `migrate-to-multiuser.js` 脚本将现有数据分配给特定用户
|
||||||
|
4. **权限控制**:删除用户不会删除该用户的数据,数据会变为遗留数据
|
||||||
|
|
||||||
|
1. **First Use**: When first using multi-user functionality, it's recommended to create an admin account as a backup
|
||||||
|
2. **Password Management**: Please keep user passwords safe; forgotten passwords need admin reset
|
||||||
|
3. **Data Migration**: Use the provided `migrate-to-multiuser.js` script to assign existing data to specific users
|
||||||
|
4. **Permission Control**: Deleting a user doesn't delete their data; the data becomes legacy data
|
||||||
+2
-2
@@ -18,9 +18,9 @@ Timed task management platform supporting Python3, JavaScript, Shell, Typescript
|
|||||||
[docker-image-size-image]: https://img.shields.io/docker/image-size/whyour/qinglong?style=flat
|
[docker-image-size-image]: https://img.shields.io/docker/image-size/whyour/qinglong?style=flat
|
||||||
[docker-image-size-url]: https://hub.docker.com/r/whyour/qinglong
|
[docker-image-size-url]: https://hub.docker.com/r/whyour/qinglong
|
||||||
|
|
||||||
[Demo](http://demo.ninesix.cc:4433/) / [Issues](https://github.com/whyour/qinglong/issues) / [Telegram Channel](https://t.me/jiao_long) / [Buy Me a Coffee](https://www.buymeacoffee.com/qinglong)
|
[Demo](http://demo.qinglong.online:4433/) / [Issues](https://github.com/whyour/qinglong/issues) / [Telegram Channel](https://t.me/jiao_long) / [Buy Me a Coffee](https://www.buymeacoffee.com/qinglong)
|
||||||
|
|
||||||
[演示](http://demo.ninesix.cc:4433/) / [反馈](https://github.com/whyour/qinglong/issues) / [Telegram 频道](https://t.me/jiao_long) / [打赏开发者](https://user-images.githubusercontent.com/22700758/244744295-29cd0cd1-c8bb-4ea1-adf6-29bd390ad4dd.jpg)
|
[演示](http://demo.qinglong.online:4433/) / [反馈](https://github.com/whyour/qinglong/issues) / [Telegram 频道](https://t.me/jiao_long) / [打赏开发者](https://user-images.githubusercontent.com/22700758/244744295-29cd0cd1-c8bb-4ea1-adf6-29bd390ad4dd.jpg)
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||

|

|
||||||
|
|||||||
@@ -20,9 +20,9 @@ Timed task management platform supporting Python3, JavaScript, Shell, Typescript
|
|||||||
[docker-image-size-image]: https://img.shields.io/docker/image-size/whyour/qinglong?style=flat
|
[docker-image-size-image]: https://img.shields.io/docker/image-size/whyour/qinglong?style=flat
|
||||||
[docker-image-size-url]: https://hub.docker.com/r/whyour/qinglong
|
[docker-image-size-url]: https://hub.docker.com/r/whyour/qinglong
|
||||||
|
|
||||||
[Demo](http://demo.ninesix.cc:4433/) / [Issues](https://github.com/whyour/qinglong/issues) / [Telegram Channel](https://t.me/jiao_long) / [Buy Me a Coffee](https://www.buymeacoffee.com/qinglong)
|
[Demo](http://demo.qinglong.online:4433/) / [Issues](https://github.com/whyour/qinglong/issues) / [Telegram Channel](https://t.me/jiao_long) / [Buy Me a Coffee](https://www.buymeacoffee.com/qinglong)
|
||||||
|
|
||||||
[演示](http://demo.ninesix.cc:4433/) / [反馈](https://github.com/whyour/qinglong/issues) / [Telegram 频道](https://t.me/jiao_long) / [打赏开发者](https://user-images.githubusercontent.com/22700758/244744295-29cd0cd1-c8bb-4ea1-adf6-29bd390ad4dd.jpg)
|
[演示](http://demo.qinglong.online:4433/) / [反馈](https://github.com/whyour/qinglong/issues) / [Telegram 频道](https://t.me/jiao_long) / [打赏开发者](https://user-images.githubusercontent.com/22700758/244744295-29cd0cd1-c8bb-4ea1-adf6-29bd390ad4dd.jpg)
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||

|

|
||||||
|
|||||||
+35
-28
@@ -145,7 +145,10 @@ export default (app: Router) => {
|
|||||||
const logger: Logger = Container.get('logger');
|
const logger: Logger = Container.get('logger');
|
||||||
try {
|
try {
|
||||||
const cronService = Container.get(CronService);
|
const cronService = Container.get(CronService);
|
||||||
const data = await cronService.crontabs(req.query as any);
|
const data = await cronService.crontabs({
|
||||||
|
...req.query as any,
|
||||||
|
userId: req.user?.userId
|
||||||
|
});
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
logger.error('🔥 error: %o', e);
|
logger.error('🔥 error: %o', e);
|
||||||
@@ -177,7 +180,10 @@ export default (app: Router) => {
|
|||||||
const logger: Logger = Container.get('logger');
|
const logger: Logger = Container.get('logger');
|
||||||
try {
|
try {
|
||||||
const cronService = Container.get(CronService);
|
const cronService = Container.get(CronService);
|
||||||
const data = await cronService.create(req.body);
|
const data = await cronService.create({
|
||||||
|
...req.body,
|
||||||
|
userId: req.user?.userId
|
||||||
|
});
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return next(e);
|
return next(e);
|
||||||
@@ -194,10 +200,10 @@ export default (app: Router) => {
|
|||||||
const logger: Logger = Container.get('logger');
|
const logger: Logger = Container.get('logger');
|
||||||
try {
|
try {
|
||||||
const cronService = Container.get(CronService);
|
const cronService = Container.get(CronService);
|
||||||
const data = await cronService.run(req.body);
|
const data = await cronService.run(req.body, req.user?.userId);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e: any) {
|
||||||
return next(e);
|
return res.send({ code: 400, message: e.message });
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -211,10 +217,10 @@ export default (app: Router) => {
|
|||||||
const logger: Logger = Container.get('logger');
|
const logger: Logger = Container.get('logger');
|
||||||
try {
|
try {
|
||||||
const cronService = Container.get(CronService);
|
const cronService = Container.get(CronService);
|
||||||
const data = await cronService.stop(req.body);
|
const data = await cronService.stop(req.body, req.user?.userId);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e: any) {
|
||||||
return next(e);
|
return res.send({ code: 400, message: e.message });
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -234,10 +240,11 @@ export default (app: Router) => {
|
|||||||
const data = await cronService.removeLabels(
|
const data = await cronService.removeLabels(
|
||||||
req.body.ids,
|
req.body.ids,
|
||||||
req.body.labels,
|
req.body.labels,
|
||||||
|
req.user?.userId,
|
||||||
);
|
);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e: any) {
|
||||||
return next(e);
|
return res.send({ code: 400, message: e.message });
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -254,10 +261,10 @@ export default (app: Router) => {
|
|||||||
const logger: Logger = Container.get('logger');
|
const logger: Logger = Container.get('logger');
|
||||||
try {
|
try {
|
||||||
const cronService = Container.get(CronService);
|
const cronService = Container.get(CronService);
|
||||||
const data = await cronService.addLabels(req.body.ids, req.body.labels);
|
const data = await cronService.addLabels(req.body.ids, req.body.labels, req.user?.userId);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e: any) {
|
||||||
return next(e);
|
return res.send({ code: 400, message: e.message });
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -271,10 +278,10 @@ export default (app: Router) => {
|
|||||||
const logger: Logger = Container.get('logger');
|
const logger: Logger = Container.get('logger');
|
||||||
try {
|
try {
|
||||||
const cronService = Container.get(CronService);
|
const cronService = Container.get(CronService);
|
||||||
const data = await cronService.disabled(req.body);
|
const data = await cronService.disabled(req.body, req.user?.userId);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e: any) {
|
||||||
return next(e);
|
return res.send({ code: 400, message: e.message });
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -288,10 +295,10 @@ export default (app: Router) => {
|
|||||||
const logger: Logger = Container.get('logger');
|
const logger: Logger = Container.get('logger');
|
||||||
try {
|
try {
|
||||||
const cronService = Container.get(CronService);
|
const cronService = Container.get(CronService);
|
||||||
const data = await cronService.enabled(req.body);
|
const data = await cronService.enabled(req.body, req.user?.userId);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e: any) {
|
||||||
return next(e);
|
return res.send({ code: 400, message: e.message });
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -344,10 +351,10 @@ export default (app: Router) => {
|
|||||||
const logger: Logger = Container.get('logger');
|
const logger: Logger = Container.get('logger');
|
||||||
try {
|
try {
|
||||||
const cronService = Container.get(CronService);
|
const cronService = Container.get(CronService);
|
||||||
const data = await cronService.remove(req.body);
|
const data = await cronService.remove(req.body, req.user?.userId);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e: any) {
|
||||||
return next(e);
|
return res.send({ code: 400, message: e.message });
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -361,10 +368,10 @@ export default (app: Router) => {
|
|||||||
const logger: Logger = Container.get('logger');
|
const logger: Logger = Container.get('logger');
|
||||||
try {
|
try {
|
||||||
const cronService = Container.get(CronService);
|
const cronService = Container.get(CronService);
|
||||||
const data = await cronService.pin(req.body);
|
const data = await cronService.pin(req.body, req.user?.userId);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e: any) {
|
||||||
return next(e);
|
return res.send({ code: 400, message: e.message });
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -378,10 +385,10 @@ export default (app: Router) => {
|
|||||||
const logger: Logger = Container.get('logger');
|
const logger: Logger = Container.get('logger');
|
||||||
try {
|
try {
|
||||||
const cronService = Container.get(CronService);
|
const cronService = Container.get(CronService);
|
||||||
const data = await cronService.unPin(req.body);
|
const data = await cronService.unPin(req.body, req.user?.userId);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e: any) {
|
||||||
return next(e);
|
return res.send({ code: 400, message: e.message });
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|||||||
+35
-24
@@ -8,17 +8,28 @@ const route = Router();
|
|||||||
export default (app: Router) => {
|
export default (app: Router) => {
|
||||||
app.use('/dependencies', route);
|
app.use('/dependencies', route);
|
||||||
|
|
||||||
route.get('/', async (req: Request, res: Response, next: NextFunction) => {
|
route.get(
|
||||||
const logger: Logger = Container.get('logger');
|
'/',
|
||||||
try {
|
celebrate({
|
||||||
const dependenceService = Container.get(DependenceService);
|
query:
|
||||||
const data = await dependenceService.dependencies(req.query as any);
|
Joi.object({
|
||||||
return res.send({ code: 200, data });
|
searchValue: Joi.string().optional().allow(''),
|
||||||
} catch (e) {
|
type: Joi.string().optional().allow(''),
|
||||||
logger.error('🔥 error: %o', e);
|
status: Joi.string().optional().allow(''),
|
||||||
return next(e);
|
}),
|
||||||
}
|
}),
|
||||||
});
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
|
const logger: Logger = Container.get('logger');
|
||||||
|
try {
|
||||||
|
const dependenceService = Container.get(DependenceService);
|
||||||
|
const data = await dependenceService.dependencies(req.query as any, [], {}, req.user?.userId);
|
||||||
|
return res.send({ code: 200, data });
|
||||||
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
|
return next(e);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
route.post(
|
route.post(
|
||||||
'/',
|
'/',
|
||||||
@@ -34,7 +45,7 @@ export default (app: Router) => {
|
|||||||
async (req: Request, res: Response, next: NextFunction) => {
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const dependenceService = Container.get(DependenceService);
|
const dependenceService = Container.get(DependenceService);
|
||||||
const data = await dependenceService.create(req.body);
|
const data = await dependenceService.create(req.body, req.user?.userId);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return next(e);
|
return next(e);
|
||||||
@@ -71,10 +82,10 @@ export default (app: Router) => {
|
|||||||
async (req: Request, res: Response, next: NextFunction) => {
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const dependenceService = Container.get(DependenceService);
|
const dependenceService = Container.get(DependenceService);
|
||||||
const data = await dependenceService.remove(req.body);
|
const data = await dependenceService.remove(req.body, false, req.user?.userId);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e: any) {
|
||||||
return next(e);
|
return res.send({ code: 400, message: e.message });
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -87,10 +98,10 @@ export default (app: Router) => {
|
|||||||
async (req: Request, res: Response, next: NextFunction) => {
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const dependenceService = Container.get(DependenceService);
|
const dependenceService = Container.get(DependenceService);
|
||||||
const data = await dependenceService.remove(req.body, true);
|
const data = await dependenceService.remove(req.body, true, req.user?.userId);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e: any) {
|
||||||
return next(e);
|
return res.send({ code: 400, message: e.message });
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -121,10 +132,10 @@ export default (app: Router) => {
|
|||||||
async (req: Request, res: Response, next: NextFunction) => {
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const dependenceService = Container.get(DependenceService);
|
const dependenceService = Container.get(DependenceService);
|
||||||
const data = await dependenceService.reInstall(req.body);
|
const data = await dependenceService.reInstall(req.body, req.user?.userId);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e: any) {
|
||||||
return next(e);
|
return res.send({ code: 400, message: e.message });
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -137,10 +148,10 @@ export default (app: Router) => {
|
|||||||
async (req: Request, res: Response, next: NextFunction) => {
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const dependenceService = Container.get(DependenceService);
|
const dependenceService = Container.get(DependenceService);
|
||||||
await dependenceService.cancel(req.body);
|
await dependenceService.cancel(req.body, req.user?.userId);
|
||||||
return res.send({ code: 200 });
|
return res.send({ code: 200 });
|
||||||
} catch (e) {
|
} catch (e: any) {
|
||||||
return next(e);
|
return res.send({ code: 400, message: e.message });
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|||||||
+55
-21
@@ -1,12 +1,12 @@
|
|||||||
import { Router, Request, Response, NextFunction } from 'express';
|
import { Joi, celebrate } from 'celebrate';
|
||||||
import { Container } from 'typedi';
|
import { NextFunction, Request, Response, Router } from 'express';
|
||||||
import EnvService from '../services/env';
|
|
||||||
import { Logger } from 'winston';
|
|
||||||
import { celebrate, Joi } from 'celebrate';
|
|
||||||
import multer from 'multer';
|
|
||||||
import config from '../config';
|
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
|
import multer from 'multer';
|
||||||
|
import { Container } from 'typedi';
|
||||||
|
import { Logger } from 'winston';
|
||||||
|
import config from '../config';
|
||||||
import { safeJSONParse } from '../config/util';
|
import { safeJSONParse } from '../config/util';
|
||||||
|
import EnvService from '../services/env';
|
||||||
const route = Router();
|
const route = Router();
|
||||||
|
|
||||||
const storage = multer.diskStorage({
|
const storage = multer.diskStorage({
|
||||||
@@ -26,7 +26,7 @@ export default (app: Router) => {
|
|||||||
const logger: Logger = Container.get('logger');
|
const logger: Logger = Container.get('logger');
|
||||||
try {
|
try {
|
||||||
const envService = Container.get(EnvService);
|
const envService = Container.get(EnvService);
|
||||||
const data = await envService.envs(req.query.searchValue as string);
|
const data = await envService.envs(req.query.searchValue as string, {}, req.user?.userId);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
logger.error('🔥 error: %o', e);
|
logger.error('🔥 error: %o', e);
|
||||||
@@ -54,7 +54,7 @@ export default (app: Router) => {
|
|||||||
if (!req.body?.length) {
|
if (!req.body?.length) {
|
||||||
return res.send({ code: 400, message: '参数不正确' });
|
return res.send({ code: 400, message: '参数不正确' });
|
||||||
}
|
}
|
||||||
const data = await envService.create(req.body);
|
const data = await envService.create(req.body, req.user?.userId);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return next(e);
|
return next(e);
|
||||||
@@ -93,10 +93,10 @@ export default (app: Router) => {
|
|||||||
const logger: Logger = Container.get('logger');
|
const logger: Logger = Container.get('logger');
|
||||||
try {
|
try {
|
||||||
const envService = Container.get(EnvService);
|
const envService = Container.get(EnvService);
|
||||||
const data = await envService.remove(req.body);
|
const data = await envService.remove(req.body, req.user?.userId);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e: any) {
|
||||||
return next(e);
|
return res.send({ code: 400, message: e.message });
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -132,10 +132,10 @@ export default (app: Router) => {
|
|||||||
const logger: Logger = Container.get('logger');
|
const logger: Logger = Container.get('logger');
|
||||||
try {
|
try {
|
||||||
const envService = Container.get(EnvService);
|
const envService = Container.get(EnvService);
|
||||||
const data = await envService.disabled(req.body);
|
const data = await envService.disabled(req.body, req.user?.userId);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e: any) {
|
||||||
return next(e);
|
return res.send({ code: 400, message: e.message });
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -149,10 +149,10 @@ export default (app: Router) => {
|
|||||||
const logger: Logger = Container.get('logger');
|
const logger: Logger = Container.get('logger');
|
||||||
try {
|
try {
|
||||||
const envService = Container.get(EnvService);
|
const envService = Container.get(EnvService);
|
||||||
const data = await envService.enabled(req.body);
|
const data = await envService.enabled(req.body, req.user?.userId);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e: any) {
|
||||||
return next(e);
|
return res.send({ code: 400, message: e.message });
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -169,10 +169,10 @@ export default (app: Router) => {
|
|||||||
const logger: Logger = Container.get('logger');
|
const logger: Logger = Container.get('logger');
|
||||||
try {
|
try {
|
||||||
const envService = Container.get(EnvService);
|
const envService = Container.get(EnvService);
|
||||||
const data = await envService.updateNames(req.body);
|
const data = await envService.updateNames(req.body, req.user?.userId);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e: any) {
|
||||||
return next(e);
|
return res.send({ code: 400, message: e.message });
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -196,6 +196,40 @@ export default (app: Router) => {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
route.put(
|
||||||
|
'/pin',
|
||||||
|
celebrate({
|
||||||
|
body: Joi.array().items(Joi.number().required()),
|
||||||
|
}),
|
||||||
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
|
const logger: Logger = Container.get('logger');
|
||||||
|
try {
|
||||||
|
const envService = Container.get(EnvService);
|
||||||
|
const data = await envService.pin(req.body);
|
||||||
|
return res.send({ code: 200, data });
|
||||||
|
} catch (e) {
|
||||||
|
return next(e);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
route.put(
|
||||||
|
'/unpin',
|
||||||
|
celebrate({
|
||||||
|
body: Joi.array().items(Joi.number().required()),
|
||||||
|
}),
|
||||||
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
|
const logger: Logger = Container.get('logger');
|
||||||
|
try {
|
||||||
|
const envService = Container.get(EnvService);
|
||||||
|
const data = await envService.unPin(req.body);
|
||||||
|
return res.send({ code: 200, data });
|
||||||
|
} catch (e) {
|
||||||
|
return next(e);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
route.post(
|
route.post(
|
||||||
'/upload',
|
'/upload',
|
||||||
upload.single('env'),
|
upload.single('env'),
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import system from './system';
|
|||||||
import subscription from './subscription';
|
import subscription from './subscription';
|
||||||
import update from './update';
|
import update from './update';
|
||||||
import health from './health';
|
import health from './health';
|
||||||
|
import userManagement from './userManagement';
|
||||||
|
|
||||||
export default () => {
|
export default () => {
|
||||||
const app = Router();
|
const app = Router();
|
||||||
@@ -26,6 +27,7 @@ export default () => {
|
|||||||
subscription(app);
|
subscription(app);
|
||||||
update(app);
|
update(app);
|
||||||
health(app);
|
health(app);
|
||||||
|
userManagement(app);
|
||||||
|
|
||||||
return app;
|
return app;
|
||||||
};
|
};
|
||||||
|
|||||||
+151
@@ -8,8 +8,12 @@ import {
|
|||||||
readDirs,
|
readDirs,
|
||||||
removeAnsi,
|
removeAnsi,
|
||||||
rmPath,
|
rmPath,
|
||||||
|
IFile,
|
||||||
} from '../config/util';
|
} from '../config/util';
|
||||||
import LogService from '../services/log';
|
import LogService from '../services/log';
|
||||||
|
import CronService from '../services/cron';
|
||||||
|
import { UserRole } from '../data/user';
|
||||||
|
import { Crontab } from '../data/cron';
|
||||||
const route = Router();
|
const route = Router();
|
||||||
const blacklist = ['.tmp'];
|
const blacklist = ['.tmp'];
|
||||||
|
|
||||||
@@ -20,6 +24,39 @@ export default (app: Router) => {
|
|||||||
const logger: Logger = Container.get('logger');
|
const logger: Logger = Container.get('logger');
|
||||||
try {
|
try {
|
||||||
const result = await readDirs(config.logPath, config.logPath, blacklist);
|
const result = await readDirs(config.logPath, config.logPath, blacklist);
|
||||||
|
|
||||||
|
// Filter logs based on user permissions
|
||||||
|
if (req.user?.role !== UserRole.admin && req.user?.userId) {
|
||||||
|
const cronService = Container.get(CronService);
|
||||||
|
const { data: userCrons } = await cronService.crontabs({
|
||||||
|
searchValue: '',
|
||||||
|
page: '0',
|
||||||
|
size: '0',
|
||||||
|
sorter: '',
|
||||||
|
filters: '',
|
||||||
|
queryString: '',
|
||||||
|
userId: req.user.userId,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Build a set of log paths that the user has access to
|
||||||
|
const allowedLogPaths = new Set(
|
||||||
|
userCrons
|
||||||
|
.filter((cron: Crontab) => cron.log_name && cron.log_name !== '/dev/null')
|
||||||
|
.map((cron: Crontab) => cron.log_name)
|
||||||
|
);
|
||||||
|
|
||||||
|
// Filter the result to only include logs the user owns
|
||||||
|
const filteredResult = (result as IFile[]).filter((item: IFile) =>
|
||||||
|
item.type === 'directory' && (allowedLogPaths.has(item.title) || allowedLogPaths.has(`${item.title}/`))
|
||||||
|
);
|
||||||
|
|
||||||
|
res.send({
|
||||||
|
code: 200,
|
||||||
|
data: filteredResult,
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
res.send({
|
res.send({
|
||||||
code: 200,
|
code: 200,
|
||||||
data: result,
|
data: result,
|
||||||
@@ -45,6 +82,35 @@ export default (app: Router) => {
|
|||||||
message: '暂无权限',
|
message: '暂无权限',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Check if user has permission to view this log
|
||||||
|
if (req.user?.role !== UserRole.admin && req.user?.userId) {
|
||||||
|
const cronService = Container.get(CronService);
|
||||||
|
const { data: userCrons } = await cronService.crontabs({
|
||||||
|
searchValue: '',
|
||||||
|
page: '0',
|
||||||
|
size: '0',
|
||||||
|
sorter: '',
|
||||||
|
filters: '',
|
||||||
|
queryString: '',
|
||||||
|
userId: req.user.userId,
|
||||||
|
});
|
||||||
|
|
||||||
|
const logPath = (req.query.path as string) || '';
|
||||||
|
const hasAccess = userCrons.some((cron: Crontab) =>
|
||||||
|
cron.log_name &&
|
||||||
|
cron.log_name !== '/dev/null' &&
|
||||||
|
(logPath.startsWith(cron.log_name) || cron.log_name.startsWith(logPath))
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!hasAccess) {
|
||||||
|
return res.send({
|
||||||
|
code: 403,
|
||||||
|
message: '暂无权限',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const content = await getFileContentByName(finalPath);
|
const content = await getFileContentByName(finalPath);
|
||||||
res.send({ code: 200, data: removeAnsi(content) });
|
res.send({ code: 200, data: removeAnsi(content) });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -68,6 +134,35 @@ export default (app: Router) => {
|
|||||||
message: '暂无权限',
|
message: '暂无权限',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Check if user has permission to view this log
|
||||||
|
if (req.user?.role !== UserRole.admin && req.user?.userId) {
|
||||||
|
const cronService = Container.get(CronService);
|
||||||
|
const { data: userCrons } = await cronService.crontabs({
|
||||||
|
searchValue: '',
|
||||||
|
page: '0',
|
||||||
|
size: '0',
|
||||||
|
sorter: '',
|
||||||
|
filters: '',
|
||||||
|
queryString: '',
|
||||||
|
userId: req.user.userId,
|
||||||
|
});
|
||||||
|
|
||||||
|
const logPath = (req.query.path as string) || '';
|
||||||
|
const hasAccess = userCrons.some((cron: Crontab) =>
|
||||||
|
cron.log_name &&
|
||||||
|
cron.log_name !== '/dev/null' &&
|
||||||
|
(logPath.startsWith(cron.log_name) || cron.log_name.startsWith(logPath))
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!hasAccess) {
|
||||||
|
return res.send({
|
||||||
|
code: 403,
|
||||||
|
message: '暂无权限',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const content = await getFileContentByName(finalPath);
|
const content = await getFileContentByName(finalPath);
|
||||||
res.send({ code: 200, data: content });
|
res.send({ code: 200, data: content });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -99,6 +194,34 @@ export default (app: Router) => {
|
|||||||
message: '暂无权限',
|
message: '暂无权限',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Check if user has permission to delete this log
|
||||||
|
if (req.user?.role !== UserRole.admin && req.user?.userId) {
|
||||||
|
const cronService = Container.get(CronService);
|
||||||
|
const { data: userCrons } = await cronService.crontabs({
|
||||||
|
searchValue: '',
|
||||||
|
page: '0',
|
||||||
|
size: '0',
|
||||||
|
sorter: '',
|
||||||
|
filters: '',
|
||||||
|
queryString: '',
|
||||||
|
userId: req.user.userId,
|
||||||
|
});
|
||||||
|
|
||||||
|
const hasAccess = userCrons.some((cron: Crontab) =>
|
||||||
|
cron.log_name &&
|
||||||
|
cron.log_name !== '/dev/null' &&
|
||||||
|
(path.startsWith(cron.log_name) || cron.log_name.startsWith(path))
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!hasAccess) {
|
||||||
|
return res.send({
|
||||||
|
code: 403,
|
||||||
|
message: '暂无权限',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
await rmPath(finalPath);
|
await rmPath(finalPath);
|
||||||
res.send({ code: 200 });
|
res.send({ code: 200 });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -129,6 +252,34 @@ export default (app: Router) => {
|
|||||||
message: '暂无权限',
|
message: '暂无权限',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Check if user has permission to download this log
|
||||||
|
if (req.user?.role !== UserRole.admin && req.user?.userId) {
|
||||||
|
const cronService = Container.get(CronService);
|
||||||
|
const { data: userCrons } = await cronService.crontabs({
|
||||||
|
searchValue: '',
|
||||||
|
page: '0',
|
||||||
|
size: '0',
|
||||||
|
sorter: '',
|
||||||
|
filters: '',
|
||||||
|
queryString: '',
|
||||||
|
userId: req.user.userId,
|
||||||
|
});
|
||||||
|
|
||||||
|
const hasAccess = userCrons.some((cron: Crontab) =>
|
||||||
|
cron.log_name &&
|
||||||
|
cron.log_name !== '/dev/null' &&
|
||||||
|
(path.startsWith(cron.log_name) || cron.log_name.startsWith(path))
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!hasAccess) {
|
||||||
|
return res.send({
|
||||||
|
code: 403,
|
||||||
|
message: '暂无权限',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return res.download(filePath, filename, (err) => {
|
return res.download(filePath, filename, (err) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
return next(err);
|
return next(err);
|
||||||
|
|||||||
+90
-46
@@ -24,55 +24,68 @@ const upload = multer({ storage: storage });
|
|||||||
export default (app: Router) => {
|
export default (app: Router) => {
|
||||||
app.use('/scripts', route);
|
app.use('/scripts', route);
|
||||||
|
|
||||||
route.get('/', async (req: Request, res: Response, next: NextFunction) => {
|
route.get(
|
||||||
const logger: Logger = Container.get('logger');
|
'/',
|
||||||
try {
|
celebrate({
|
||||||
let result: IFile[] = [];
|
query: Joi.object({
|
||||||
const blacklist = [
|
path: Joi.string().optional().allow(''),
|
||||||
'node_modules',
|
}),
|
||||||
'.git',
|
}),
|
||||||
'.pnpm',
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
'pnpm-lock.yaml',
|
const logger: Logger = Container.get('logger');
|
||||||
'yarn.lock',
|
try {
|
||||||
'package-lock.json',
|
let result: IFile[] = [];
|
||||||
];
|
const blacklist = [
|
||||||
if (req.query.path) {
|
'node_modules',
|
||||||
result = await readDir(
|
'.git',
|
||||||
req.query.path as string,
|
'.pnpm',
|
||||||
config.scriptPath,
|
'pnpm-lock.yaml',
|
||||||
blacklist,
|
'yarn.lock',
|
||||||
);
|
'package-lock.json',
|
||||||
} else {
|
];
|
||||||
result = await readDirs(
|
if (req.query.path) {
|
||||||
config.scriptPath,
|
result = await readDir(
|
||||||
config.scriptPath,
|
req.query.path as string,
|
||||||
blacklist,
|
config.scriptPath,
|
||||||
(a, b) => {
|
blacklist,
|
||||||
if (a.type === b.type) {
|
);
|
||||||
return a.title.localeCompare(b.title);
|
} else {
|
||||||
} else {
|
result = await readDirs(
|
||||||
return a.type === 'directory' ? -1 : 1;
|
config.scriptPath,
|
||||||
}
|
config.scriptPath,
|
||||||
},
|
blacklist,
|
||||||
);
|
(a, b) => {
|
||||||
|
if (a.type === b.type) {
|
||||||
|
return a.title.localeCompare(b.title);
|
||||||
|
} else {
|
||||||
|
return a.type === 'directory' ? -1 : 1;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
res.send({
|
||||||
|
code: 200,
|
||||||
|
data: result,
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
logger.error('🔥 error: %o', e);
|
||||||
|
return next(e);
|
||||||
}
|
}
|
||||||
res.send({
|
});
|
||||||
code: 200,
|
|
||||||
data: result,
|
|
||||||
});
|
|
||||||
} catch (e) {
|
|
||||||
logger.error('🔥 error: %o', e);
|
|
||||||
return next(e);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
route.get(
|
route.get(
|
||||||
'/detail',
|
'/detail',
|
||||||
|
celebrate({
|
||||||
|
query: Joi.object({
|
||||||
|
path: Joi.string().optional().allow(''),
|
||||||
|
file: Joi.string().required(),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const scriptService = Container.get(ScriptService);
|
const scriptService = Container.get(ScriptService);
|
||||||
const content = await scriptService.getFile(
|
const content = await scriptService.getFile(
|
||||||
req.query.path as string,
|
req.query?.path as string || '',
|
||||||
req.query.file as string,
|
req.query.file as string,
|
||||||
);
|
);
|
||||||
res.send({ code: 200, data: content });
|
res.send({ code: 200, data: content });
|
||||||
@@ -84,11 +97,19 @@ export default (app: Router) => {
|
|||||||
|
|
||||||
route.get(
|
route.get(
|
||||||
'/:file',
|
'/:file',
|
||||||
|
celebrate({
|
||||||
|
params: Joi.object({
|
||||||
|
file: Joi.string().required(),
|
||||||
|
}),
|
||||||
|
query: Joi.object({
|
||||||
|
path: Joi.string().optional().allow(''),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const scriptService = Container.get(ScriptService);
|
const scriptService = Container.get(ScriptService);
|
||||||
const content = await scriptService.getFile(
|
const content = await scriptService.getFile(
|
||||||
req.query.path as string,
|
req.query?.path as string || '',
|
||||||
req.params.file,
|
req.params.file,
|
||||||
);
|
);
|
||||||
res.send({ code: 200, data: content });
|
res.send({ code: 200, data: content });
|
||||||
@@ -101,6 +122,15 @@ export default (app: Router) => {
|
|||||||
route.post(
|
route.post(
|
||||||
'/',
|
'/',
|
||||||
upload.single('file'),
|
upload.single('file'),
|
||||||
|
celebrate({
|
||||||
|
body: Joi.object({
|
||||||
|
filename: Joi.string().required(),
|
||||||
|
path: Joi.string().optional().allow(''),
|
||||||
|
content: Joi.string().optional().allow(''),
|
||||||
|
originFilename: Joi.string().optional().allow(''),
|
||||||
|
directory: Joi.string().optional().allow(''),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
let { filename, path, content, originFilename, directory } =
|
let { filename, path, content, originFilename, directory } =
|
||||||
@@ -201,7 +231,7 @@ export default (app: Router) => {
|
|||||||
celebrate({
|
celebrate({
|
||||||
body: Joi.object({
|
body: Joi.object({
|
||||||
filename: Joi.string().required(),
|
filename: Joi.string().required(),
|
||||||
path: Joi.string().allow(''),
|
path: Joi.string().optional().allow(''),
|
||||||
type: Joi.string().optional(),
|
type: Joi.string().optional(),
|
||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
@@ -211,6 +241,9 @@ export default (app: Router) => {
|
|||||||
filename: string;
|
filename: string;
|
||||||
path: string;
|
path: string;
|
||||||
};
|
};
|
||||||
|
if (!path) {
|
||||||
|
path = '';
|
||||||
|
}
|
||||||
const scriptService = Container.get(ScriptService);
|
const scriptService = Container.get(ScriptService);
|
||||||
const filePath = scriptService.checkFilePath(path, filename);
|
const filePath = scriptService.checkFilePath(path, filename);
|
||||||
if (!filePath) {
|
if (!filePath) {
|
||||||
@@ -232,7 +265,7 @@ export default (app: Router) => {
|
|||||||
celebrate({
|
celebrate({
|
||||||
body: Joi.object({
|
body: Joi.object({
|
||||||
filename: Joi.string().required(),
|
filename: Joi.string().required(),
|
||||||
path: Joi.string().allow(''),
|
path: Joi.string().optional().allow(''),
|
||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
@@ -241,6 +274,9 @@ export default (app: Router) => {
|
|||||||
filename: string;
|
filename: string;
|
||||||
path: string;
|
path: string;
|
||||||
};
|
};
|
||||||
|
if (!path) {
|
||||||
|
path = '';
|
||||||
|
}
|
||||||
const scriptService = Container.get(ScriptService);
|
const scriptService = Container.get(ScriptService);
|
||||||
const filePath = scriptService.checkFilePath(path, filename);
|
const filePath = scriptService.checkFilePath(path, filename);
|
||||||
if (!filePath) {
|
if (!filePath) {
|
||||||
@@ -273,6 +309,9 @@ export default (app: Router) => {
|
|||||||
const logger: Logger = Container.get('logger');
|
const logger: Logger = Container.get('logger');
|
||||||
try {
|
try {
|
||||||
let { filename, content, path } = req.body;
|
let { filename, content, path } = req.body;
|
||||||
|
if (!path) {
|
||||||
|
path = '';
|
||||||
|
}
|
||||||
const { name, ext } = parse(filename);
|
const { name, ext } = parse(filename);
|
||||||
const filePath = join(config.scriptPath, path, `${name}.swap${ext}`);
|
const filePath = join(config.scriptPath, path, `${name}.swap${ext}`);
|
||||||
await writeFileWithLock(filePath, content || '');
|
await writeFileWithLock(filePath, content || '');
|
||||||
@@ -298,6 +337,9 @@ export default (app: Router) => {
|
|||||||
async (req: Request, res: Response, next: NextFunction) => {
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
let { filename, path, pid } = req.body;
|
let { filename, path, pid } = req.body;
|
||||||
|
if (!path) {
|
||||||
|
path = '';
|
||||||
|
}
|
||||||
const { name, ext } = parse(filename);
|
const { name, ext } = parse(filename);
|
||||||
const filePath = join(config.scriptPath, path, `${name}.swap${ext}`);
|
const filePath = join(config.scriptPath, path, `${name}.swap${ext}`);
|
||||||
const logPath = join(config.logPath, path, `${name}.swap`);
|
const logPath = join(config.logPath, path, `${name}.swap`);
|
||||||
@@ -325,12 +367,14 @@ export default (app: Router) => {
|
|||||||
}),
|
}),
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
let { filename, path, type, newFilename } = req.body as {
|
let { filename, path, newFilename } = req.body as {
|
||||||
filename: string;
|
filename: string;
|
||||||
path: string;
|
path: string;
|
||||||
type: string;
|
|
||||||
newFilename: string;
|
newFilename: string;
|
||||||
};
|
};
|
||||||
|
if (!path) {
|
||||||
|
path = '';
|
||||||
|
}
|
||||||
const filePath = join(config.scriptPath, path, filename);
|
const filePath = join(config.scriptPath, path, filename);
|
||||||
const newPath = join(config.scriptPath, path, newFilename);
|
const newPath = join(config.scriptPath, path, newFilename);
|
||||||
await fs.rename(filePath, newPath);
|
await fs.rename(filePath, newPath);
|
||||||
|
|||||||
+20
-16
@@ -16,6 +16,7 @@ export default (app: Router) => {
|
|||||||
const data = await subscriptionService.list(
|
const data = await subscriptionService.list(
|
||||||
req.query.searchValue as string,
|
req.query.searchValue as string,
|
||||||
req.query.ids as string,
|
req.query.ids as string,
|
||||||
|
req.user?.userId,
|
||||||
);
|
);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -63,7 +64,10 @@ export default (app: Router) => {
|
|||||||
cron_parser.parseExpression(req.body.schedule).hasNext()
|
cron_parser.parseExpression(req.body.schedule).hasNext()
|
||||||
) {
|
) {
|
||||||
const subscriptionService = Container.get(SubscriptionService);
|
const subscriptionService = Container.get(SubscriptionService);
|
||||||
const data = await subscriptionService.create(req.body);
|
const data = await subscriptionService.create({
|
||||||
|
...req.body,
|
||||||
|
userId: req.user?.userId,
|
||||||
|
});
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} else {
|
} else {
|
||||||
return res.send({ code: 400, message: 'param schedule error' });
|
return res.send({ code: 400, message: 'param schedule error' });
|
||||||
@@ -83,10 +87,10 @@ export default (app: Router) => {
|
|||||||
const logger: Logger = Container.get('logger');
|
const logger: Logger = Container.get('logger');
|
||||||
try {
|
try {
|
||||||
const subscriptionService = Container.get(SubscriptionService);
|
const subscriptionService = Container.get(SubscriptionService);
|
||||||
const data = await subscriptionService.run(req.body);
|
const data = await subscriptionService.run(req.body, req.user?.userId);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e: any) {
|
||||||
return next(e);
|
return res.send({ code: 400, message: e.message });
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -100,10 +104,10 @@ export default (app: Router) => {
|
|||||||
const logger: Logger = Container.get('logger');
|
const logger: Logger = Container.get('logger');
|
||||||
try {
|
try {
|
||||||
const subscriptionService = Container.get(SubscriptionService);
|
const subscriptionService = Container.get(SubscriptionService);
|
||||||
const data = await subscriptionService.stop(req.body);
|
const data = await subscriptionService.stop(req.body, req.user?.userId);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e: any) {
|
||||||
return next(e);
|
return res.send({ code: 400, message: e.message });
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -117,10 +121,10 @@ export default (app: Router) => {
|
|||||||
const logger: Logger = Container.get('logger');
|
const logger: Logger = Container.get('logger');
|
||||||
try {
|
try {
|
||||||
const subscriptionService = Container.get(SubscriptionService);
|
const subscriptionService = Container.get(SubscriptionService);
|
||||||
const data = await subscriptionService.disabled(req.body);
|
const data = await subscriptionService.disabled(req.body, req.user?.userId);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e: any) {
|
||||||
return next(e);
|
return res.send({ code: 400, message: e.message });
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -134,10 +138,10 @@ export default (app: Router) => {
|
|||||||
const logger: Logger = Container.get('logger');
|
const logger: Logger = Container.get('logger');
|
||||||
try {
|
try {
|
||||||
const subscriptionService = Container.get(SubscriptionService);
|
const subscriptionService = Container.get(SubscriptionService);
|
||||||
const data = await subscriptionService.enabled(req.body);
|
const data = await subscriptionService.enabled(req.body, req.user?.userId);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e: any) {
|
||||||
return next(e);
|
return res.send({ code: 400, message: e.message });
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -220,10 +224,10 @@ export default (app: Router) => {
|
|||||||
const logger: Logger = Container.get('logger');
|
const logger: Logger = Container.get('logger');
|
||||||
try {
|
try {
|
||||||
const subscriptionService = Container.get(SubscriptionService);
|
const subscriptionService = Container.get(SubscriptionService);
|
||||||
const data = await subscriptionService.remove(req.body, req.query);
|
const data = await subscriptionService.remove(req.body, req.query, req.user?.userId);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e: any) {
|
||||||
return next(e);
|
return res.send({ code: 400, message: e.message });
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|||||||
+46
-5
@@ -14,6 +14,7 @@ import {
|
|||||||
} from '../config/util';
|
} from '../config/util';
|
||||||
import dayjs from 'dayjs';
|
import dayjs from 'dayjs';
|
||||||
import multer from 'multer';
|
import multer from 'multer';
|
||||||
|
import { UserRole } from '../data/user';
|
||||||
|
|
||||||
const route = Router();
|
const route = Router();
|
||||||
const storage = multer.diskStorage({
|
const storage = multer.diskStorage({
|
||||||
@@ -273,19 +274,20 @@ export default (app: Router) => {
|
|||||||
{
|
{
|
||||||
onStart: async (cp, startTime) => {
|
onStart: async (cp, startTime) => {
|
||||||
res.setHeader('QL-Task-Pid', `${cp.pid}`);
|
res.setHeader('QL-Task-Pid', `${cp.pid}`);
|
||||||
|
res.setHeader('QL-Task-Log', `${logPath}`);
|
||||||
},
|
},
|
||||||
onEnd: async (cp, endTime, diff) => {
|
onEnd: async (cp, endTime, diff) => {
|
||||||
res.end();
|
res.end();
|
||||||
},
|
},
|
||||||
onError: async (message: string) => {
|
onError: async (message: string) => {
|
||||||
res.write(`\n${message}`);
|
res.write(message);
|
||||||
const absolutePath = await handleLogPath(logPath);
|
const absolutePath = await handleLogPath(logPath);
|
||||||
await fs.appendFile(absolutePath, `\n${message}`);
|
await fs.appendFile(absolutePath, message);
|
||||||
},
|
},
|
||||||
onLog: async (message: string) => {
|
onLog: async (message: string) => {
|
||||||
res.write(`\n${message}`);
|
res.write(message);
|
||||||
const absolutePath = await handleLogPath(logPath);
|
const absolutePath = await handleLogPath(logPath);
|
||||||
await fs.appendFile(absolutePath, `\n${message}`);
|
await fs.appendFile(absolutePath, message);
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -316,10 +318,15 @@ export default (app: Router) => {
|
|||||||
|
|
||||||
route.put(
|
route.put(
|
||||||
'/data/export',
|
'/data/export',
|
||||||
|
celebrate({
|
||||||
|
body: Joi.object({
|
||||||
|
type: Joi.array().items(Joi.string()).optional(),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const systemService = Container.get(SystemService);
|
const systemService = Container.get(SystemService);
|
||||||
await systemService.exportData(res);
|
await systemService.exportData(res, req.body.type);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
@@ -351,6 +358,14 @@ export default (app: Router) => {
|
|||||||
}),
|
}),
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
|
// Only admin can view system logs
|
||||||
|
if (req.user?.role !== UserRole.admin) {
|
||||||
|
return res.send({
|
||||||
|
code: 403,
|
||||||
|
message: '暂无权限',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const systemService = Container.get(SystemService);
|
const systemService = Container.get(SystemService);
|
||||||
await systemService.getSystemLog(
|
await systemService.getSystemLog(
|
||||||
res,
|
res,
|
||||||
@@ -369,6 +384,14 @@ export default (app: Router) => {
|
|||||||
'/log',
|
'/log',
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
|
// Only admin can delete system logs
|
||||||
|
if (req.user?.role !== UserRole.admin) {
|
||||||
|
return res.send({
|
||||||
|
code: 403,
|
||||||
|
message: '暂无权限',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const systemService = Container.get(SystemService);
|
const systemService = Container.get(SystemService);
|
||||||
await systemService.deleteSystemLog();
|
await systemService.deleteSystemLog();
|
||||||
res.send({ code: 200 });
|
res.send({ code: 200 });
|
||||||
@@ -416,4 +439,22 @@ export default (app: Router) => {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
route.put(
|
||||||
|
'/config/dependence-clean',
|
||||||
|
celebrate({
|
||||||
|
body: Joi.object({
|
||||||
|
type: Joi.string().allow(''),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
|
try {
|
||||||
|
const systemService = Container.get(SystemService);
|
||||||
|
const result = await systemService.cleanDependence(req.body.type);
|
||||||
|
res.send(result);
|
||||||
|
} catch (e) {
|
||||||
|
return next(e);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import { v4 as uuidV4 } from 'uuid';
|
|||||||
import rateLimit from 'express-rate-limit';
|
import rateLimit from 'express-rate-limit';
|
||||||
import config from '../config';
|
import config from '../config';
|
||||||
import { isDemoEnv } from '../config/util';
|
import { isDemoEnv } from '../config/util';
|
||||||
|
import { UserRole } from '../data/user';
|
||||||
const route = Router();
|
const route = Router();
|
||||||
|
|
||||||
const storage = multer.diskStorage({
|
const storage = multer.diskStorage({
|
||||||
@@ -97,6 +98,7 @@ export default (app: Router) => {
|
|||||||
username: authInfo.username,
|
username: authInfo.username,
|
||||||
avatar: authInfo.avatar,
|
avatar: authInfo.avatar,
|
||||||
twoFactorActivated: authInfo.twoFactorActivated,
|
twoFactorActivated: authInfo.twoFactorActivated,
|
||||||
|
role: req.user?.role,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -178,6 +180,14 @@ export default (app: Router) => {
|
|||||||
async (req: Request, res: Response, next: NextFunction) => {
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
const logger: Logger = Container.get('logger');
|
const logger: Logger = Container.get('logger');
|
||||||
try {
|
try {
|
||||||
|
// Only admin can view login logs
|
||||||
|
if (req.user?.role !== UserRole.admin) {
|
||||||
|
return res.send({
|
||||||
|
code: 403,
|
||||||
|
message: '暂无权限',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const userService = Container.get(UserService);
|
const userService = Container.get(UserService);
|
||||||
const data = await userService.getLoginLog();
|
const data = await userService.getLoginLog();
|
||||||
res.send({ code: 200, data });
|
res.send({ code: 200, data });
|
||||||
|
|||||||
@@ -0,0 +1,114 @@
|
|||||||
|
import { Router, Request, Response, NextFunction } from 'express';
|
||||||
|
import { Container } from 'typedi';
|
||||||
|
import { celebrate, Joi } from 'celebrate';
|
||||||
|
import UserManagementService from '../services/userManagement';
|
||||||
|
import { UserRole } from '../data/user';
|
||||||
|
|
||||||
|
const route = Router();
|
||||||
|
|
||||||
|
// Middleware to check if user is admin
|
||||||
|
const requireAdmin = (req: Request, res: Response, next: NextFunction) => {
|
||||||
|
if (req.user && req.user.role === UserRole.admin) {
|
||||||
|
return next();
|
||||||
|
}
|
||||||
|
return res.status(403).send({ code: 403, message: '需要管理员权限' });
|
||||||
|
};
|
||||||
|
|
||||||
|
export default (app: Router) => {
|
||||||
|
app.use('/user-management', route);
|
||||||
|
|
||||||
|
// List all users (admin only)
|
||||||
|
route.get(
|
||||||
|
'/',
|
||||||
|
requireAdmin,
|
||||||
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
|
try {
|
||||||
|
const userManagementService = Container.get(UserManagementService);
|
||||||
|
const data = await userManagementService.list(req.query.searchValue as string);
|
||||||
|
res.send({ code: 200, data });
|
||||||
|
} catch (e) {
|
||||||
|
return next(e);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
// Get a specific user (admin only)
|
||||||
|
route.get(
|
||||||
|
'/:id',
|
||||||
|
requireAdmin,
|
||||||
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
|
try {
|
||||||
|
const userManagementService = Container.get(UserManagementService);
|
||||||
|
const data = await userManagementService.get(Number(req.params.id));
|
||||||
|
res.send({ code: 200, data });
|
||||||
|
} catch (e) {
|
||||||
|
return next(e);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
// Create a new user (admin only)
|
||||||
|
route.post(
|
||||||
|
'/',
|
||||||
|
requireAdmin,
|
||||||
|
celebrate({
|
||||||
|
body: Joi.object({
|
||||||
|
username: Joi.string().required(),
|
||||||
|
password: Joi.string().required(),
|
||||||
|
role: Joi.number().valid(UserRole.admin, UserRole.user).default(UserRole.user),
|
||||||
|
status: Joi.number().optional(),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
|
try {
|
||||||
|
const userManagementService = Container.get(UserManagementService);
|
||||||
|
const data = await userManagementService.create(req.body);
|
||||||
|
res.send({ code: 200, data, message: '创建用户成功' });
|
||||||
|
} catch (e: any) {
|
||||||
|
return res.send({ code: 400, message: e.message });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
// Update a user (admin only)
|
||||||
|
route.put(
|
||||||
|
'/',
|
||||||
|
requireAdmin,
|
||||||
|
celebrate({
|
||||||
|
body: Joi.object({
|
||||||
|
id: Joi.number().required(),
|
||||||
|
username: Joi.string().required(),
|
||||||
|
password: Joi.string().required(),
|
||||||
|
role: Joi.number().valid(UserRole.admin, UserRole.user),
|
||||||
|
status: Joi.number().optional(),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
|
try {
|
||||||
|
const userManagementService = Container.get(UserManagementService);
|
||||||
|
const data = await userManagementService.update(req.body);
|
||||||
|
res.send({ code: 200, data, message: '更新用户成功' });
|
||||||
|
} catch (e: any) {
|
||||||
|
return res.send({ code: 400, message: e.message });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
// Delete users (admin only)
|
||||||
|
route.delete(
|
||||||
|
'/',
|
||||||
|
requireAdmin,
|
||||||
|
celebrate({
|
||||||
|
body: Joi.array().items(Joi.number()).required(),
|
||||||
|
}),
|
||||||
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
|
try {
|
||||||
|
const userManagementService = Container.get(UserManagementService);
|
||||||
|
const count = await userManagementService.delete(req.body);
|
||||||
|
res.send({ code: 200, data: count, message: '删除用户成功' });
|
||||||
|
} catch (e) {
|
||||||
|
return next(e);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
};
|
||||||
+179
-33
@@ -1,4 +1,5 @@
|
|||||||
import 'reflect-metadata';
|
import 'reflect-metadata';
|
||||||
|
import cluster, { type Worker } from 'cluster';
|
||||||
import compression from 'compression';
|
import compression from 'compression';
|
||||||
import cors from 'cors';
|
import cors from 'cors';
|
||||||
import express from 'express';
|
import express from 'express';
|
||||||
@@ -10,76 +11,142 @@ import { monitoringMiddleware } from './middlewares/monitoring';
|
|||||||
import { type GrpcServerService } from './services/grpc';
|
import { type GrpcServerService } from './services/grpc';
|
||||||
import { type HttpServerService } from './services/http';
|
import { type HttpServerService } from './services/http';
|
||||||
|
|
||||||
|
interface WorkerMetadata {
|
||||||
|
id: number;
|
||||||
|
pid: number;
|
||||||
|
serviceType: string;
|
||||||
|
startTime: Date;
|
||||||
|
}
|
||||||
|
|
||||||
class Application {
|
class Application {
|
||||||
private app: express.Application;
|
private app: express.Application;
|
||||||
private httpServerService?: HttpServerService;
|
private httpServerService?: HttpServerService;
|
||||||
private grpcServerService?: GrpcServerService;
|
private grpcServerService?: GrpcServerService;
|
||||||
private isShuttingDown = false;
|
private isShuttingDown = false;
|
||||||
|
private workerMetadataMap = new Map<number, WorkerMetadata>();
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
this.app = express();
|
this.app = express();
|
||||||
|
// 创建一个全局中间件,删除查询参数中的t
|
||||||
|
this.app.use((req: express.Request, res: express.Response, next: express.NextFunction) => {
|
||||||
|
if (req.query.t) {
|
||||||
|
delete req.query.t;
|
||||||
|
}
|
||||||
|
next();
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async start() {
|
async start() {
|
||||||
try {
|
try {
|
||||||
await this.initializeDatabase();
|
if (cluster.isPrimary) {
|
||||||
await this.initServer();
|
await this.initializeDatabase();
|
||||||
this.setupMiddlewares();
|
}
|
||||||
await this.initializeServices();
|
if (cluster.isPrimary) {
|
||||||
this.setupGracefulShutdown();
|
this.startMasterProcess();
|
||||||
|
} else {
|
||||||
process.send?.('ready');
|
await this.startWorkerProcess();
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
Logger.error('Failed to start application:', error);
|
Logger.error('Failed to start application:', error);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async initServer() {
|
private startMasterProcess() {
|
||||||
const { HttpServerService } = await import('./services/http');
|
this.forkWorker('http');
|
||||||
const { GrpcServerService } = await import('./services/grpc');
|
this.forkWorker('grpc');
|
||||||
this.httpServerService = Container.get(HttpServerService);
|
|
||||||
this.grpcServerService = Container.get(GrpcServerService);
|
cluster.on('exit', (worker, code, signal) => {
|
||||||
|
const metadata = this.workerMetadataMap.get(worker.id);
|
||||||
|
if (metadata) {
|
||||||
|
if (!this.isShuttingDown) {
|
||||||
|
Logger.error(
|
||||||
|
`${metadata.serviceType} worker ${worker.process.pid} died (${signal || code
|
||||||
|
}). Restarting...`,
|
||||||
|
);
|
||||||
|
const newWorker = this.forkWorker(metadata.serviceType);
|
||||||
|
Logger.info(
|
||||||
|
`Restarted ${metadata.serviceType} worker (New PID: ${newWorker.process.pid})`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.workerMetadataMap.delete(worker.id);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
this.setupMasterShutdown();
|
||||||
|
}
|
||||||
|
|
||||||
|
private forkWorker(serviceType: string): Worker {
|
||||||
|
const worker = cluster.fork({ SERVICE_TYPE: serviceType });
|
||||||
|
|
||||||
|
this.workerMetadataMap.set(worker.id, {
|
||||||
|
id: worker.id,
|
||||||
|
pid: worker.process.pid!,
|
||||||
|
serviceType,
|
||||||
|
startTime: new Date(),
|
||||||
|
});
|
||||||
|
|
||||||
|
return worker;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async initializeDatabase() {
|
private async initializeDatabase() {
|
||||||
await require('./loaders/db').default();
|
const dbLoader = await import('./loaders/db');
|
||||||
|
await dbLoader.default();
|
||||||
}
|
}
|
||||||
|
|
||||||
private setupMiddlewares() {
|
private setupMiddlewares() {
|
||||||
this.app.use(helmet());
|
this.app.use(helmet({
|
||||||
|
contentSecurityPolicy: false,
|
||||||
|
}));
|
||||||
this.app.use(cors(config.cors));
|
this.app.use(cors(config.cors));
|
||||||
this.app.use(compression());
|
this.app.use(compression());
|
||||||
this.app.use(monitoringMiddleware);
|
this.app.use(monitoringMiddleware);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async initializeServices() {
|
private setupMasterShutdown() {
|
||||||
await this.grpcServerService?.initialize();
|
|
||||||
|
|
||||||
await require('./loaders/app').default({ app: this.app });
|
|
||||||
|
|
||||||
const server = await this.httpServerService?.initialize(
|
|
||||||
this.app,
|
|
||||||
config.port,
|
|
||||||
);
|
|
||||||
|
|
||||||
await require('./loaders/server').default({ server });
|
|
||||||
}
|
|
||||||
|
|
||||||
private setupGracefulShutdown() {
|
|
||||||
const shutdown = async () => {
|
const shutdown = async () => {
|
||||||
if (this.isShuttingDown) return;
|
if (this.isShuttingDown) return;
|
||||||
this.isShuttingDown = true;
|
this.isShuttingDown = true;
|
||||||
|
|
||||||
Logger.info('Shutting down services...');
|
const workers = Object.values(cluster.workers || {});
|
||||||
|
const workerPromises: Promise<void>[] = [];
|
||||||
|
|
||||||
|
workers.forEach((worker) => {
|
||||||
|
if (worker) {
|
||||||
|
const exitPromise = new Promise<void>((resolve) => {
|
||||||
|
worker.once('exit', () => {
|
||||||
|
Logger.info(`Worker ${worker.process.pid} exited`);
|
||||||
|
resolve();
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
worker.send('shutdown');
|
||||||
|
} catch (error) {
|
||||||
|
Logger.warn(
|
||||||
|
`Failed to send shutdown to worker ${worker.process.pid}:`,
|
||||||
|
error,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
workerPromises.push(exitPromise);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await Promise.all([
|
await Promise.race([
|
||||||
this.grpcServerService?.shutdown(),
|
Promise.all(workerPromises),
|
||||||
this.httpServerService?.shutdown(),
|
new Promise<void>((resolve) => {
|
||||||
|
setTimeout(() => {
|
||||||
|
Logger.warn('Worker shutdown timeout reached');
|
||||||
|
resolve();
|
||||||
|
}, 10000);
|
||||||
|
}),
|
||||||
]);
|
]);
|
||||||
process.exit(0);
|
process.exit(0);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
Logger.error('Error during shutdown:', error);
|
Logger.error('Error during worker shutdown:', error);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -87,6 +154,85 @@ class Application {
|
|||||||
process.on('SIGTERM', shutdown);
|
process.on('SIGTERM', shutdown);
|
||||||
process.on('SIGINT', shutdown);
|
process.on('SIGINT', shutdown);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async startWorkerProcess() {
|
||||||
|
const serviceType = process.env.SERVICE_TYPE;
|
||||||
|
if (!serviceType || !['http', 'grpc'].includes(serviceType)) {
|
||||||
|
Logger.error('Invalid SERVICE_TYPE:', serviceType);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
Logger.info(`✌️ ${serviceType} worker started (PID: ${process.pid})`);
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (serviceType === 'http') {
|
||||||
|
await this.startHttpService();
|
||||||
|
} else {
|
||||||
|
await this.startGrpcService();
|
||||||
|
}
|
||||||
|
|
||||||
|
process.send?.('ready');
|
||||||
|
} catch (error) {
|
||||||
|
Logger.error(`${serviceType} worker failed:`, error);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async startHttpService() {
|
||||||
|
this.setupMiddlewares();
|
||||||
|
|
||||||
|
const { HttpServerService } = await import('./services/http');
|
||||||
|
this.httpServerService = Container.get(HttpServerService);
|
||||||
|
|
||||||
|
const appLoader = await import('./loaders/app');
|
||||||
|
await appLoader.default({ app: this.app });
|
||||||
|
|
||||||
|
const server = await this.httpServerService.initialize(
|
||||||
|
this.app,
|
||||||
|
config.port,
|
||||||
|
);
|
||||||
|
|
||||||
|
const serverLoader = await import('./loaders/server');
|
||||||
|
await (serverLoader.default as any)({ server });
|
||||||
|
this.setupWorkerShutdown('http');
|
||||||
|
}
|
||||||
|
|
||||||
|
private async startGrpcService() {
|
||||||
|
const { GrpcServerService } = await import('./services/grpc');
|
||||||
|
this.grpcServerService = Container.get(GrpcServerService);
|
||||||
|
|
||||||
|
await this.grpcServerService.initialize();
|
||||||
|
this.setupWorkerShutdown('grpc');
|
||||||
|
}
|
||||||
|
|
||||||
|
private setupWorkerShutdown(serviceType: string) {
|
||||||
|
process.on('message', (msg) => {
|
||||||
|
if (msg === 'shutdown') {
|
||||||
|
this.gracefulShutdown(serviceType);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const shutdown = () => this.gracefulShutdown(serviceType);
|
||||||
|
process.on('SIGTERM', shutdown);
|
||||||
|
process.on('SIGINT', shutdown);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async gracefulShutdown(serviceType: string) {
|
||||||
|
if (this.isShuttingDown) return;
|
||||||
|
this.isShuttingDown = true;
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (serviceType === 'http') {
|
||||||
|
await this.httpServerService?.shutdown();
|
||||||
|
} else {
|
||||||
|
await this.grpcServerService?.shutdown();
|
||||||
|
}
|
||||||
|
process.exit(0);
|
||||||
|
} catch (error) {
|
||||||
|
Logger.error(`[${serviceType}] Error during shutdown:`, error);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const app = new Application();
|
const app = new Application();
|
||||||
|
|||||||
@@ -25,3 +25,27 @@ export const SAMPLE_FILES = [
|
|||||||
];
|
];
|
||||||
|
|
||||||
export const PYTHON_INSTALL_DIR = process.env.PYTHON_HOME;
|
export const PYTHON_INSTALL_DIR = process.env.PYTHON_HOME;
|
||||||
|
|
||||||
|
export const NotificationModeStringMap = {
|
||||||
|
0: 'gotify',
|
||||||
|
1: 'goCqHttpBot',
|
||||||
|
2: 'serverChan',
|
||||||
|
3: 'pushDeer',
|
||||||
|
4: 'bark',
|
||||||
|
5: 'chat',
|
||||||
|
6: 'telegramBot',
|
||||||
|
7: 'dingtalkBot',
|
||||||
|
8: 'weWorkBot',
|
||||||
|
9: 'weWorkApp',
|
||||||
|
10: 'aibotk',
|
||||||
|
11: 'iGot',
|
||||||
|
12: 'pushPlus',
|
||||||
|
13: 'wePlusBot',
|
||||||
|
14: 'email',
|
||||||
|
15: 'pushMe',
|
||||||
|
16: 'feishu',
|
||||||
|
17: 'webhook',
|
||||||
|
18: 'chronocat',
|
||||||
|
19: 'ntfy',
|
||||||
|
20: 'wxPusherBot',
|
||||||
|
} as const;
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ interface Config {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const config: Config = {
|
const config: Config = {
|
||||||
port: parseInt(process.env.BACK_PORT || '5600', 10),
|
port: parseInt(process.env.BACK_PORT || '5700', 10),
|
||||||
grpcPort: parseInt(process.env.GRPC_PORT || '5500', 10),
|
grpcPort: parseInt(process.env.GRPC_PORT || '5500', 10),
|
||||||
nodeEnv: process.env.NODE_ENV || 'development',
|
nodeEnv: process.env.NODE_ENV || 'development',
|
||||||
isDevelopment: process.env.NODE_ENV === 'development',
|
isDevelopment: process.env.NODE_ENV === 'development',
|
||||||
@@ -41,7 +41,7 @@ const config: Config = {
|
|||||||
prefix: '/api',
|
prefix: '/api',
|
||||||
},
|
},
|
||||||
jwt: {
|
jwt: {
|
||||||
secret: process.env.JWT_SECRET || createRandomString(16, 32),
|
secret: process.env.JWT_SECRET || 'whyour-secret',
|
||||||
expiresIn: process.env.JWT_EXPIRES_IN,
|
expiresIn: process.env.JWT_EXPIRES_IN,
|
||||||
},
|
},
|
||||||
cors: {
|
cors: {
|
||||||
@@ -86,6 +86,7 @@ const dbPath = path.join(dataPath, 'db/');
|
|||||||
const uploadPath = path.join(dataPath, 'upload/');
|
const uploadPath = path.join(dataPath, 'upload/');
|
||||||
const sshdPath = path.join(dataPath, 'ssh.d/');
|
const sshdPath = path.join(dataPath, 'ssh.d/');
|
||||||
const systemLogPath = path.join(dataPath, 'syslog/');
|
const systemLogPath = path.join(dataPath, 'syslog/');
|
||||||
|
const dependenceCachePath = path.join(dataPath, 'dep_cache/');
|
||||||
|
|
||||||
const envFile = path.join(preloadPath, 'env.sh');
|
const envFile = path.join(preloadPath, 'env.sh');
|
||||||
const jsEnvFile = path.join(preloadPath, 'env.js');
|
const jsEnvFile = path.join(preloadPath, 'env.js');
|
||||||
@@ -174,4 +175,5 @@ export default {
|
|||||||
sqliteFile,
|
sqliteFile,
|
||||||
sshdPath,
|
sshdPath,
|
||||||
systemLogPath,
|
systemLogPath,
|
||||||
|
dependenceCachePath,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -514,6 +514,27 @@ export async function setSystemTimezone(timezone: string): Promise<boolean> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function getGetCommand(type: DependenceTypes, name: string): string {
|
||||||
|
const baseCommands = {
|
||||||
|
[DependenceTypes.nodejs]: `pnpm ls -g | grep "${name}" | head -1`,
|
||||||
|
[DependenceTypes.python3]: `
|
||||||
|
python3 -c "exec('''
|
||||||
|
name='${name}'
|
||||||
|
try:
|
||||||
|
from importlib.metadata import version
|
||||||
|
print(version(name))
|
||||||
|
except:
|
||||||
|
import importlib.util as u
|
||||||
|
import importlib.metadata as m
|
||||||
|
spec=u.find_spec(name)
|
||||||
|
print(name if spec else '')
|
||||||
|
''')"`,
|
||||||
|
[DependenceTypes.linux]: `apk info -es ${name}`,
|
||||||
|
};
|
||||||
|
|
||||||
|
return baseCommands[type];
|
||||||
|
}
|
||||||
|
|
||||||
export function getInstallCommand(type: DependenceTypes, name: string): string {
|
export function getInstallCommand(type: DependenceTypes, name: string): string {
|
||||||
const baseCommands = {
|
const baseCommands = {
|
||||||
[DependenceTypes.nodejs]: 'pnpm add -g',
|
[DependenceTypes.nodejs]: 'pnpm add -g',
|
||||||
|
|||||||
+7
-1
@@ -21,6 +21,8 @@ export class Crontab {
|
|||||||
extra_schedules?: Array<{ schedule: string }>;
|
extra_schedules?: Array<{ schedule: string }>;
|
||||||
task_before?: string;
|
task_before?: string;
|
||||||
task_after?: string;
|
task_after?: string;
|
||||||
|
log_name?: string;
|
||||||
|
userId?: number;
|
||||||
|
|
||||||
constructor(options: Crontab) {
|
constructor(options: Crontab) {
|
||||||
this.name = options.name;
|
this.name = options.name;
|
||||||
@@ -45,6 +47,8 @@ export class Crontab {
|
|||||||
this.extra_schedules = options.extra_schedules;
|
this.extra_schedules = options.extra_schedules;
|
||||||
this.task_before = options.task_before;
|
this.task_before = options.task_before;
|
||||||
this.task_after = options.task_after;
|
this.task_after = options.task_after;
|
||||||
|
this.log_name = options.log_name;
|
||||||
|
this.userId = options.userId;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -55,7 +59,7 @@ export enum CrontabStatus {
|
|||||||
'disabled',
|
'disabled',
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CronInstance extends Model<Crontab, Crontab>, Crontab { }
|
export interface CronInstance extends Model<Crontab, Crontab>, Crontab {}
|
||||||
export const CrontabModel = sequelize.define<CronInstance>('Crontab', {
|
export const CrontabModel = sequelize.define<CronInstance>('Crontab', {
|
||||||
name: {
|
name: {
|
||||||
unique: 'compositeIndex',
|
unique: 'compositeIndex',
|
||||||
@@ -84,4 +88,6 @@ export const CrontabModel = sequelize.define<CronInstance>('Crontab', {
|
|||||||
extra_schedules: DataTypes.JSON,
|
extra_schedules: DataTypes.JSON,
|
||||||
task_before: DataTypes.STRING,
|
task_before: DataTypes.STRING,
|
||||||
task_after: DataTypes.STRING,
|
task_after: DataTypes.STRING,
|
||||||
|
log_name: DataTypes.STRING,
|
||||||
|
userId: { type: DataTypes.NUMBER, allowNull: true },
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ export class Dependence {
|
|||||||
name: string;
|
name: string;
|
||||||
log?: string[];
|
log?: string[];
|
||||||
remark?: string;
|
remark?: string;
|
||||||
|
userId?: number;
|
||||||
|
|
||||||
constructor(options: Dependence) {
|
constructor(options: Dependence) {
|
||||||
this.id = options.id;
|
this.id = options.id;
|
||||||
@@ -21,6 +22,7 @@ export class Dependence {
|
|||||||
this.name = options.name.trim();
|
this.name = options.name.trim();
|
||||||
this.log = options.log || [];
|
this.log = options.log || [];
|
||||||
this.remark = options.remark || '';
|
this.remark = options.remark || '';
|
||||||
|
this.userId = options.userId;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -41,12 +43,6 @@ export enum DependenceTypes {
|
|||||||
'linux',
|
'linux',
|
||||||
}
|
}
|
||||||
|
|
||||||
export enum GetDependenceCommandTypes {
|
|
||||||
'pnpm ls -g ',
|
|
||||||
'pip3 show --disable-pip-version-check',
|
|
||||||
'apk info -es',
|
|
||||||
}
|
|
||||||
|
|
||||||
export enum versionDependenceCommandTypes {
|
export enum versionDependenceCommandTypes {
|
||||||
'@',
|
'@',
|
||||||
'==',
|
'==',
|
||||||
@@ -65,5 +61,6 @@ export const DependenceModel = sequelize.define<DependenceInstance>(
|
|||||||
status: DataTypes.NUMBER,
|
status: DataTypes.NUMBER,
|
||||||
log: DataTypes.JSON,
|
log: DataTypes.JSON,
|
||||||
remark: DataTypes.STRING,
|
remark: DataTypes.STRING,
|
||||||
|
userId: { type: DataTypes.NUMBER, allowNull: true },
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|||||||
+7
-1
@@ -1,5 +1,5 @@
|
|||||||
|
import { DataTypes, Model } from 'sequelize';
|
||||||
import { sequelize } from '.';
|
import { sequelize } from '.';
|
||||||
import { DataTypes, Model, ModelDefined } from 'sequelize';
|
|
||||||
|
|
||||||
export class Env {
|
export class Env {
|
||||||
value?: string;
|
value?: string;
|
||||||
@@ -9,6 +9,8 @@ export class Env {
|
|||||||
position?: number;
|
position?: number;
|
||||||
name?: string;
|
name?: string;
|
||||||
remarks?: string;
|
remarks?: string;
|
||||||
|
userId?: number;
|
||||||
|
isPinned?: 1 | 0;
|
||||||
|
|
||||||
constructor(options: Env) {
|
constructor(options: Env) {
|
||||||
this.value = options.value;
|
this.value = options.value;
|
||||||
@@ -21,6 +23,8 @@ export class Env {
|
|||||||
this.position = options.position;
|
this.position = options.position;
|
||||||
this.name = options.name;
|
this.name = options.name;
|
||||||
this.remarks = options.remarks || '';
|
this.remarks = options.remarks || '';
|
||||||
|
this.userId = options.userId;
|
||||||
|
this.isPinned = options.isPinned || 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -42,4 +46,6 @@ export const EnvModel = sequelize.define<EnvInstance>('Env', {
|
|||||||
position: DataTypes.NUMBER,
|
position: DataTypes.NUMBER,
|
||||||
name: { type: DataTypes.STRING, unique: 'compositeIndex' },
|
name: { type: DataTypes.STRING, unique: 'compositeIndex' },
|
||||||
remarks: DataTypes.STRING,
|
remarks: DataTypes.STRING,
|
||||||
|
userId: { type: DataTypes.NUMBER, allowNull: true },
|
||||||
|
isPinned: DataTypes.NUMBER,
|
||||||
});
|
});
|
||||||
|
|||||||
+4
-2
@@ -1,5 +1,3 @@
|
|||||||
import { IncomingHttpHeaders } from 'http';
|
|
||||||
|
|
||||||
export enum NotificationMode {
|
export enum NotificationMode {
|
||||||
'gotify' = 'gotify',
|
'gotify' = 'gotify',
|
||||||
'goCqHttpBot' = 'goCqHttpBot',
|
'goCqHttpBot' = 'goCqHttpBot',
|
||||||
@@ -150,6 +148,10 @@ export class NtfyNotification extends NotificationBaseInfo {
|
|||||||
public ntfyUrl = '';
|
public ntfyUrl = '';
|
||||||
public ntfyTopic = '';
|
public ntfyTopic = '';
|
||||||
public ntfyPriority = '';
|
public ntfyPriority = '';
|
||||||
|
public ntfyToken = '';
|
||||||
|
public ntfyUsername = '';
|
||||||
|
public ntfyPassword = '';
|
||||||
|
public ntfyActions = '';
|
||||||
}
|
}
|
||||||
|
|
||||||
export class WxPusherBotNotification extends NotificationBaseInfo {
|
export class WxPusherBotNotification extends NotificationBaseInfo {
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ export class Subscription {
|
|||||||
proxy?: string;
|
proxy?: string;
|
||||||
autoAddCron?: 1 | 0;
|
autoAddCron?: 1 | 0;
|
||||||
autoDelCron?: 1 | 0;
|
autoDelCron?: 1 | 0;
|
||||||
|
userId?: number;
|
||||||
|
|
||||||
constructor(options: Subscription) {
|
constructor(options: Subscription) {
|
||||||
this.id = options.id;
|
this.id = options.id;
|
||||||
@@ -60,6 +61,7 @@ export class Subscription {
|
|||||||
this.proxy = options.proxy;
|
this.proxy = options.proxy;
|
||||||
this.autoAddCron = options.autoAddCron ? 1 : 0;
|
this.autoAddCron = options.autoAddCron ? 1 : 0;
|
||||||
this.autoDelCron = options.autoDelCron ? 1 : 0;
|
this.autoDelCron = options.autoDelCron ? 1 : 0;
|
||||||
|
this.userId = options.userId;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -111,5 +113,6 @@ export const SubscriptionModel = sequelize.define<SubscriptionInstance>(
|
|||||||
proxy: { type: DataTypes.STRING, allowNull: true },
|
proxy: { type: DataTypes.STRING, allowNull: true },
|
||||||
autoAddCron: { type: DataTypes.NUMBER, allowNull: true },
|
autoAddCron: { type: DataTypes.NUMBER, allowNull: true },
|
||||||
autoDelCron: { type: DataTypes.NUMBER, allowNull: true },
|
autoDelCron: { type: DataTypes.NUMBER, allowNull: true },
|
||||||
|
userId: { type: DataTypes.NUMBER, allowNull: true },
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -0,0 +1,56 @@
|
|||||||
|
import { sequelize } from '.';
|
||||||
|
import { DataTypes, Model } from 'sequelize';
|
||||||
|
|
||||||
|
export class User {
|
||||||
|
id?: number;
|
||||||
|
username: string;
|
||||||
|
password: string;
|
||||||
|
role: UserRole;
|
||||||
|
status: UserStatus;
|
||||||
|
createdAt?: Date;
|
||||||
|
updatedAt?: Date;
|
||||||
|
|
||||||
|
constructor(options: User) {
|
||||||
|
this.id = options.id;
|
||||||
|
this.username = options.username;
|
||||||
|
this.password = options.password;
|
||||||
|
this.role = options.role || UserRole.user;
|
||||||
|
this.status =
|
||||||
|
typeof options.status === 'number' && UserStatus[options.status]
|
||||||
|
? options.status
|
||||||
|
: UserStatus.active;
|
||||||
|
this.createdAt = options.createdAt;
|
||||||
|
this.updatedAt = options.updatedAt;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum UserRole {
|
||||||
|
'admin' = 0,
|
||||||
|
'user' = 1,
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum UserStatus {
|
||||||
|
'active' = 0,
|
||||||
|
'disabled' = 1,
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UserInstance extends Model<User, User>, User {}
|
||||||
|
export const UserModel = sequelize.define<UserInstance>('User', {
|
||||||
|
username: {
|
||||||
|
type: DataTypes.STRING,
|
||||||
|
unique: true,
|
||||||
|
allowNull: false,
|
||||||
|
},
|
||||||
|
password: {
|
||||||
|
type: DataTypes.STRING,
|
||||||
|
allowNull: false,
|
||||||
|
},
|
||||||
|
role: {
|
||||||
|
type: DataTypes.NUMBER,
|
||||||
|
defaultValue: UserRole.user,
|
||||||
|
},
|
||||||
|
status: {
|
||||||
|
type: DataTypes.NUMBER,
|
||||||
|
defaultValue: UserStatus.active,
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -6,6 +6,7 @@ import { AppModel } from '../data/open';
|
|||||||
import { SystemModel } from '../data/system';
|
import { SystemModel } from '../data/system';
|
||||||
import { SubscriptionModel } from '../data/subscription';
|
import { SubscriptionModel } from '../data/subscription';
|
||||||
import { CrontabViewModel } from '../data/cronView';
|
import { CrontabViewModel } from '../data/cronView';
|
||||||
|
import { UserModel } from '../data/user';
|
||||||
import { sequelize } from '../data';
|
import { sequelize } from '../data';
|
||||||
|
|
||||||
export default async () => {
|
export default async () => {
|
||||||
@@ -17,6 +18,7 @@ export default async () => {
|
|||||||
await EnvModel.sync();
|
await EnvModel.sync();
|
||||||
await SubscriptionModel.sync();
|
await SubscriptionModel.sync();
|
||||||
await CrontabViewModel.sync();
|
await CrontabViewModel.sync();
|
||||||
|
await UserModel.sync();
|
||||||
|
|
||||||
// 初始化新增字段
|
// 初始化新增字段
|
||||||
try {
|
try {
|
||||||
@@ -56,6 +58,28 @@ export default async () => {
|
|||||||
try {
|
try {
|
||||||
await sequelize.query('alter table Crontabs add column task_after TEXT');
|
await sequelize.query('alter table Crontabs add column task_after TEXT');
|
||||||
} catch (error) {}
|
} catch (error) {}
|
||||||
|
try {
|
||||||
|
await sequelize.query(
|
||||||
|
'alter table Crontabs add column log_name VARCHAR(255)',
|
||||||
|
);
|
||||||
|
} catch (error) {}
|
||||||
|
try {
|
||||||
|
await sequelize.query('alter table Envs add column isPinned NUMBER');
|
||||||
|
} catch (error) {}
|
||||||
|
|
||||||
|
// Multi-user support: Add userId columns
|
||||||
|
try {
|
||||||
|
await sequelize.query('alter table Crontabs add column userId NUMBER');
|
||||||
|
} catch (error) {}
|
||||||
|
try {
|
||||||
|
await sequelize.query('alter table Envs add column userId NUMBER');
|
||||||
|
} catch (error) {}
|
||||||
|
try {
|
||||||
|
await sequelize.query('alter table Subscriptions add column userId NUMBER');
|
||||||
|
} catch (error) {}
|
||||||
|
try {
|
||||||
|
await sequelize.query('alter table Dependences add column userId NUMBER');
|
||||||
|
} catch (error) {}
|
||||||
|
|
||||||
Logger.info('✌️ DB loaded');
|
Logger.info('✌️ DB loaded');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ async function linkToNodeModule(src: string, dst?: string) {
|
|||||||
if (!stats) {
|
if (!stats) {
|
||||||
await fs.symlink(source, target, 'dir');
|
await fs.symlink(source, target, 'dir');
|
||||||
}
|
}
|
||||||
} catch (error) {}
|
} catch (error) { }
|
||||||
}
|
}
|
||||||
|
|
||||||
async function linkCommand() {
|
async function linkCommand() {
|
||||||
@@ -36,6 +36,12 @@ async function linkCommand() {
|
|||||||
const source = path.join(config.rootPath, 'shell', link.src);
|
const source = path.join(config.rootPath, 'shell', link.src);
|
||||||
const target = path.join(commandDir, link.dest);
|
const target = path.join(commandDir, link.dest);
|
||||||
const tmpTarget = path.join(commandDir, link.tmp);
|
const tmpTarget = path.join(commandDir, link.tmp);
|
||||||
|
try {
|
||||||
|
const stats = await fs.lstat(tmpTarget);
|
||||||
|
if (stats) {
|
||||||
|
await fs.unlink(tmpTarget);
|
||||||
|
}
|
||||||
|
} catch (error) { }
|
||||||
await fs.symlink(source, tmpTarget);
|
await fs.symlink(source, tmpTarget);
|
||||||
await fs.rename(tmpTarget, target);
|
await fs.rename(tmpTarget, target);
|
||||||
}
|
}
|
||||||
@@ -52,6 +58,6 @@ export default async (src: string = 'deps') => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
watcher
|
watcher
|
||||||
.on('add', (path) => linkToNodeModule(src))
|
.on('add', () => linkToNodeModule(src))
|
||||||
.on('change', (path) => linkToNodeModule(src));
|
.on('change', () => linkToNodeModule(src));
|
||||||
};
|
};
|
||||||
|
|||||||
+37
-5
@@ -9,6 +9,7 @@ import rewrite from 'express-urlrewrite';
|
|||||||
import { errors } from 'celebrate';
|
import { errors } from 'celebrate';
|
||||||
import { serveEnv } from '../config/serverEnv';
|
import { serveEnv } from '../config/serverEnv';
|
||||||
import { IKeyvStore, shareStore } from '../shared/store';
|
import { IKeyvStore, shareStore } from '../shared/store';
|
||||||
|
import path from 'path';
|
||||||
|
|
||||||
export default ({ app }: { app: Application }) => {
|
export default ({ app }: { app: Application }) => {
|
||||||
app.set('trust proxy', 'loopback');
|
app.set('trust proxy', 'loopback');
|
||||||
@@ -19,12 +20,15 @@ export default ({ app }: { app: Application }) => {
|
|||||||
app.use(bodyParser.json({ limit: '50mb' }));
|
app.use(bodyParser.json({ limit: '50mb' }));
|
||||||
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
|
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
|
||||||
|
|
||||||
|
const frontendPath = path.join(config.rootPath, 'static/dist');
|
||||||
|
app.use(express.static(frontendPath));
|
||||||
|
|
||||||
app.use(
|
app.use(
|
||||||
expressjwt({
|
expressjwt({
|
||||||
secret: config.jwt.secret,
|
secret: config.jwt.secret,
|
||||||
algorithms: ['HS384'],
|
algorithms: ['HS384'],
|
||||||
}).unless({
|
}).unless({
|
||||||
path: [...config.apiWhiteList, /^\/open\//],
|
path: [...config.apiWhiteList, /^\/(?!api\/).*/],
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -38,7 +42,23 @@ export default ({ app }: { app: Application }) => {
|
|||||||
return next();
|
return next();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Extract userId and role from JWT
|
||||||
|
app.use((req: Request, res, next) => {
|
||||||
|
if (req.auth) {
|
||||||
|
const payload = req.auth as any;
|
||||||
|
req.user = {
|
||||||
|
userId: payload.userId,
|
||||||
|
role: payload.role,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return next();
|
||||||
|
});
|
||||||
|
|
||||||
app.use(async (req: Request, res, next) => {
|
app.use(async (req: Request, res, next) => {
|
||||||
|
if (!['/open/', '/api/'].some((x) => req.path.startsWith(x))) {
|
||||||
|
return next();
|
||||||
|
}
|
||||||
|
|
||||||
const headerToken = getToken(req);
|
const headerToken = getToken(req);
|
||||||
if (req.path.startsWith('/open/')) {
|
if (req.path.startsWith('/open/')) {
|
||||||
const apps = await shareStore.getApps();
|
const apps = await shareStore.getApps();
|
||||||
@@ -68,6 +88,13 @@ export default ({ app }: { app: Application }) => {
|
|||||||
return next();
|
return next();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// If JWT has been successfully verified by expressjwt middleware, allow the request
|
||||||
|
// This handles regular users whose tokens are not stored in authInfo
|
||||||
|
if (req.auth) {
|
||||||
|
return next();
|
||||||
|
}
|
||||||
|
|
||||||
|
// For system admin, also check against stored token
|
||||||
const authInfo = await shareStore.getAuthInfo();
|
const authInfo = await shareStore.getAuthInfo();
|
||||||
if (authInfo && headerToken) {
|
if (authInfo && headerToken) {
|
||||||
const { token = '', tokens = {} } = authInfo;
|
const { token = '', tokens = {} } = authInfo;
|
||||||
@@ -110,10 +137,15 @@ export default ({ app }: { app: Application }) => {
|
|||||||
app.use(rewrite('/open/*', '/api/$1'));
|
app.use(rewrite('/open/*', '/api/$1'));
|
||||||
app.use(config.api.prefix, routes());
|
app.use(config.api.prefix, routes());
|
||||||
|
|
||||||
app.use((req, res, next) => {
|
app.get('*', (_, res, next) => {
|
||||||
const err: any = new Error('Not Found');
|
const indexPath = path.join(frontendPath, 'index.html');
|
||||||
err['status'] = 404;
|
res.sendFile(indexPath, (err) => {
|
||||||
next(err);
|
if (err) {
|
||||||
|
const err: any = new Error('Not Found');
|
||||||
|
err['status'] = 404;
|
||||||
|
next(err);
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
app.use(errors());
|
app.use(errors());
|
||||||
|
|||||||
@@ -89,7 +89,8 @@ export default async () => {
|
|||||||
setTimeout(async () => {
|
setTimeout(async () => {
|
||||||
await dependenceService.installDependenceOneByOne(docs);
|
await dependenceService.installDependenceOneByOne(docs);
|
||||||
|
|
||||||
require('./bootAfter').default();
|
const bootAfterLoader = await import('./bootAfter');
|
||||||
|
bootAfterLoader.default();
|
||||||
}, 5000);
|
}, 5000);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -116,7 +116,9 @@ export default async () => {
|
|||||||
`Neither content nor source specified for ${item.target}`,
|
`Neither content nor source specified for ${item.target}`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
const content = item.content || (await fs.readFile(item.source!));
|
const content =
|
||||||
|
item.content ||
|
||||||
|
(await fs.readFile(item.source!, { encoding: 'utf-8' }));
|
||||||
await writeFileWithLock(item.target, content);
|
await writeFileWithLock(item.target, content);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+36
-14
@@ -4,6 +4,8 @@ import { Container } from 'typedi';
|
|||||||
import SockService from '../services/sock';
|
import SockService from '../services/sock';
|
||||||
import { getPlatform } from '../config/util';
|
import { getPlatform } from '../config/util';
|
||||||
import { shareStore } from '../shared/store';
|
import { shareStore } from '../shared/store';
|
||||||
|
import jwt from 'jsonwebtoken';
|
||||||
|
import config from '../config';
|
||||||
|
|
||||||
export default async ({ server }: { server: Server }) => {
|
export default async ({ server }: { server: Server }) => {
|
||||||
const echo = sockJs.createServer({ prefix: '/api/ws', log: () => {} });
|
const echo = sockJs.createServer({ prefix: '/api/ws', log: () => {} });
|
||||||
@@ -14,26 +16,46 @@ export default async ({ server }: { server: Server }) => {
|
|||||||
conn.close('404');
|
conn.close('404');
|
||||||
}
|
}
|
||||||
|
|
||||||
const authInfo = await shareStore.getAuthInfo();
|
|
||||||
const platform = getPlatform(conn.headers['user-agent'] || '') || 'desktop';
|
const platform = getPlatform(conn.headers['user-agent'] || '') || 'desktop';
|
||||||
const headerToken = conn.url.replace(`${conn.pathname}?token=`, '');
|
const headerToken = conn.url.replace(`${conn.pathname}?token=`, '');
|
||||||
if (authInfo) {
|
|
||||||
const { token = '', tokens = {} } = authInfo;
|
let isAuthenticated = false;
|
||||||
if (headerToken === token || tokens[platform] === headerToken) {
|
|
||||||
sockService.addClient(conn);
|
|
||||||
|
|
||||||
conn.on('data', (message) => {
|
// First try to verify JWT token (for regular users)
|
||||||
conn.write(message);
|
if (headerToken) {
|
||||||
});
|
try {
|
||||||
|
jwt.verify(headerToken, config.jwt.secret, { algorithms: ['HS384'] });
|
||||||
conn.on('close', function () {
|
isAuthenticated = true;
|
||||||
sockService.removeClient(conn);
|
} catch (error) {
|
||||||
});
|
// JWT verification failed, will try authInfo check next
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Also check against stored token for system admin
|
||||||
|
if (!isAuthenticated) {
|
||||||
|
const authInfo = await shareStore.getAuthInfo();
|
||||||
|
if (authInfo) {
|
||||||
|
const { token = '', tokens = {} } = authInfo;
|
||||||
|
if (headerToken === token || tokens[platform] === headerToken) {
|
||||||
|
isAuthenticated = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isAuthenticated) {
|
||||||
|
sockService.addClient(conn);
|
||||||
|
|
||||||
|
conn.on('data', (message) => {
|
||||||
|
conn.write(message);
|
||||||
|
});
|
||||||
|
|
||||||
|
conn.on('close', function () {
|
||||||
|
sockService.removeClient(conn);
|
||||||
|
});
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
conn.close('404');
|
conn.close('404');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
+123
-8
@@ -53,14 +53,7 @@ message Response {
|
|||||||
optional string message = 2;
|
optional string message = 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
message SystemNotifyRequest {
|
message ExtraScheduleItem { string schedule = 1; }
|
||||||
string title = 1;
|
|
||||||
string content = 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
message ExtraScheduleItem {
|
|
||||||
string schedule = 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
message CronItem {
|
message CronItem {
|
||||||
optional int32 id = 1;
|
optional int32 id = 1;
|
||||||
@@ -124,6 +117,128 @@ message CronDetailResponse {
|
|||||||
optional string message = 3;
|
optional string message = 3;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
enum NotificationMode {
|
||||||
|
gotify = 0;
|
||||||
|
goCqHttpBot = 1;
|
||||||
|
serverChan = 2;
|
||||||
|
pushDeer = 3;
|
||||||
|
bark = 4;
|
||||||
|
chat = 5;
|
||||||
|
telegramBot = 6;
|
||||||
|
dingtalkBot = 7;
|
||||||
|
weWorkBot = 8;
|
||||||
|
weWorkApp = 9;
|
||||||
|
aibotk = 10;
|
||||||
|
iGot = 11;
|
||||||
|
pushPlus = 12;
|
||||||
|
wePlusBot = 13;
|
||||||
|
email = 14;
|
||||||
|
pushMe = 15;
|
||||||
|
feishu = 16;
|
||||||
|
webhook = 17;
|
||||||
|
chronocat = 18;
|
||||||
|
ntfy = 19;
|
||||||
|
wxPusherBot = 20;
|
||||||
|
}
|
||||||
|
|
||||||
|
message NotificationInfo {
|
||||||
|
NotificationMode type = 1;
|
||||||
|
|
||||||
|
optional string gotifyUrl = 2;
|
||||||
|
optional string gotifyToken = 3;
|
||||||
|
optional int32 gotifyPriority = 4;
|
||||||
|
|
||||||
|
optional string goCqHttpBotUrl = 5;
|
||||||
|
optional string goCqHttpBotToken = 6;
|
||||||
|
optional string goCqHttpBotQq = 7;
|
||||||
|
|
||||||
|
optional string serverChanKey = 8;
|
||||||
|
|
||||||
|
optional string pushDeerKey = 9;
|
||||||
|
optional string pushDeerUrl = 10;
|
||||||
|
|
||||||
|
optional string synologyChatUrl = 11;
|
||||||
|
|
||||||
|
optional string barkPush = 12;
|
||||||
|
optional string barkIcon = 13;
|
||||||
|
optional string barkSound = 14;
|
||||||
|
optional string barkGroup = 15;
|
||||||
|
optional string barkLevel = 16;
|
||||||
|
optional string barkUrl = 17;
|
||||||
|
optional string barkArchive = 18;
|
||||||
|
|
||||||
|
optional string telegramBotToken = 19;
|
||||||
|
optional string telegramBotUserId = 20;
|
||||||
|
optional string telegramBotProxyHost = 21;
|
||||||
|
optional string telegramBotProxyPort = 22;
|
||||||
|
optional string telegramBotProxyAuth = 23;
|
||||||
|
optional string telegramBotApiHost = 24;
|
||||||
|
|
||||||
|
optional string dingtalkBotToken = 25;
|
||||||
|
optional string dingtalkBotSecret = 26;
|
||||||
|
|
||||||
|
optional string weWorkBotKey = 27;
|
||||||
|
optional string weWorkOrigin = 28;
|
||||||
|
|
||||||
|
optional string weWorkAppKey = 29;
|
||||||
|
|
||||||
|
optional string aibotkKey = 30;
|
||||||
|
optional string aibotkType = 31;
|
||||||
|
optional string aibotkName = 32;
|
||||||
|
|
||||||
|
optional string iGotPushKey = 33;
|
||||||
|
|
||||||
|
optional string pushPlusToken = 34;
|
||||||
|
optional string pushPlusUser = 35;
|
||||||
|
optional string pushPlusTemplate = 36;
|
||||||
|
optional string pushplusChannel = 37;
|
||||||
|
optional string pushplusWebhook = 38;
|
||||||
|
optional string pushplusCallbackUrl = 39;
|
||||||
|
optional string pushplusTo = 40;
|
||||||
|
|
||||||
|
optional string wePlusBotToken = 41;
|
||||||
|
optional string wePlusBotReceiver = 42;
|
||||||
|
optional string wePlusBotVersion = 43;
|
||||||
|
|
||||||
|
optional string emailService = 44;
|
||||||
|
optional string emailUser = 45;
|
||||||
|
optional string emailPass = 46;
|
||||||
|
optional string emailTo = 47;
|
||||||
|
|
||||||
|
optional string pushMeKey = 48;
|
||||||
|
optional string pushMeUrl = 49;
|
||||||
|
|
||||||
|
optional string chronocatURL = 50;
|
||||||
|
optional string chronocatQQ = 51;
|
||||||
|
optional string chronocatToken = 52;
|
||||||
|
|
||||||
|
optional string webhookHeaders = 53;
|
||||||
|
optional string webhookBody = 54;
|
||||||
|
optional string webhookUrl = 55;
|
||||||
|
optional string webhookMethod = 56;
|
||||||
|
optional string webhookContentType = 57;
|
||||||
|
|
||||||
|
optional string larkKey = 58;
|
||||||
|
|
||||||
|
optional string ntfyUrl = 59;
|
||||||
|
optional string ntfyTopic = 60;
|
||||||
|
optional string ntfyPriority = 61;
|
||||||
|
optional string ntfyToken = 62;
|
||||||
|
optional string ntfyUsername = 63;
|
||||||
|
optional string ntfyPassword = 64;
|
||||||
|
optional string ntfyActions = 65;
|
||||||
|
|
||||||
|
optional string wxPusherBotAppToken = 66;
|
||||||
|
optional string wxPusherBotTopicIds = 67;
|
||||||
|
optional string wxPusherBotUids = 68;
|
||||||
|
}
|
||||||
|
|
||||||
|
message SystemNotifyRequest {
|
||||||
|
string title = 1;
|
||||||
|
string content = 2;
|
||||||
|
optional NotificationInfo notificationInfo = 3;
|
||||||
|
}
|
||||||
|
|
||||||
service Api {
|
service Api {
|
||||||
rpc GetEnvs(GetEnvsRequest) returns (EnvsResponse) {}
|
rpc GetEnvs(GetEnvsRequest) returns (EnvsResponse) {}
|
||||||
rpc CreateEnv(CreateEnvRequest) returns (EnvsResponse) {}
|
rpc CreateEnv(CreateEnvRequest) returns (EnvsResponse) {}
|
||||||
|
|||||||
+1531
-81
File diff suppressed because it is too large
Load Diff
@@ -16,7 +16,7 @@ const addCron = (
|
|||||||
}
|
}
|
||||||
|
|
||||||
Logger.info(
|
Logger.info(
|
||||||
'[schedule][创建定时任务], 任务ID: %s, 名称: %s, cron: %s, 执行命令: %s',
|
'[schedule][创建定时任务] 任务ID: %s, 名称: %s, cron: %s, 执行命令: %s',
|
||||||
id,
|
id,
|
||||||
name,
|
name,
|
||||||
schedule,
|
schedule,
|
||||||
@@ -26,7 +26,7 @@ const addCron = (
|
|||||||
if (extra_schedules?.length) {
|
if (extra_schedules?.length) {
|
||||||
extra_schedules.forEach((x) => {
|
extra_schedules.forEach((x) => {
|
||||||
Logger.info(
|
Logger.info(
|
||||||
'[schedule][创建定时任务], 任务ID: %s, 名称: %s, cron: %s, 执行命令: %s',
|
'[schedule][创建定时任务] 任务ID: %s, 名称: %s, cron: %s, 执行命令: %s',
|
||||||
id,
|
id,
|
||||||
name,
|
name,
|
||||||
x.schedule,
|
x.schedule,
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ import {
|
|||||||
DeleteCronsRequest,
|
DeleteCronsRequest,
|
||||||
CronResponse,
|
CronResponse,
|
||||||
} from '../protos/api';
|
} from '../protos/api';
|
||||||
|
import { NotificationInfo } from '../data/notify';
|
||||||
|
|
||||||
Container.set('logger', LoggerInstance);
|
Container.set('logger', LoggerInstance);
|
||||||
|
|
||||||
@@ -227,7 +228,11 @@ export const systemNotify = async (
|
|||||||
) => {
|
) => {
|
||||||
try {
|
try {
|
||||||
const systemService = Container.get(SystemService);
|
const systemService = Container.get(SystemService);
|
||||||
const data = await systemService.notify(call.request);
|
const data = await systemService.notify({
|
||||||
|
title: call.request.title,
|
||||||
|
content: call.request.content,
|
||||||
|
notificationInfo: call.request.notificationInfo as unknown as NotificationInfo,
|
||||||
|
});
|
||||||
callback(null, data);
|
callback(null, data);
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
callback(e);
|
callback(e);
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ const delCron = (
|
|||||||
for (const id of call.request.ids) {
|
for (const id of call.request.ids) {
|
||||||
if (scheduleStacks.has(id)) {
|
if (scheduleStacks.has(id)) {
|
||||||
Logger.info(
|
Logger.info(
|
||||||
'[schedule][取消定时任务], 任务ID: %s',
|
'[schedule][取消定时任务] 任务ID: %s',
|
||||||
id,
|
id,
|
||||||
);
|
);
|
||||||
scheduleStacks.get(id)?.forEach(x => x.cancel());
|
scheduleStacks.get(id)?.forEach(x => x.cancel());
|
||||||
|
|||||||
+99
-30
@@ -27,7 +27,31 @@ import { ScheduleType } from '../interface/schedule';
|
|||||||
|
|
||||||
@Service()
|
@Service()
|
||||||
export default class CronService {
|
export default class CronService {
|
||||||
constructor(@Inject('logger') private logger: winston.Logger) {}
|
constructor(@Inject('logger') private logger: winston.Logger) { }
|
||||||
|
|
||||||
|
private addUserIdFilter(query: any, userId?: number) {
|
||||||
|
if (userId !== undefined) {
|
||||||
|
query.userId = userId;
|
||||||
|
}
|
||||||
|
return query;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async checkOwnership(ids: number[], userId?: number): Promise<void> {
|
||||||
|
if (userId === undefined) {
|
||||||
|
// Admin can access all crons
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const crons = await CrontabModel.findAll({
|
||||||
|
where: { id: ids },
|
||||||
|
attributes: ['id', 'userId'],
|
||||||
|
});
|
||||||
|
const unauthorized = crons.filter(
|
||||||
|
(cron) => cron.userId !== undefined && cron.userId !== userId
|
||||||
|
);
|
||||||
|
if (unauthorized.length > 0) {
|
||||||
|
throw new Error('无权限操作该定时任务');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private isNodeCron(cron: Crontab) {
|
private isNodeCron(cron: Crontab) {
|
||||||
const { schedule, extra_schedules } = cron;
|
const { schedule, extra_schedules } = cron;
|
||||||
@@ -49,9 +73,27 @@ export default class CronService {
|
|||||||
return this.isOnceSchedule(schedule) || this.isBootSchedule(schedule);
|
return this.isOnceSchedule(schedule) || this.isBootSchedule(schedule);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async getLogName(cron: Crontab) {
|
||||||
|
const { log_name, command, id } = cron;
|
||||||
|
if (log_name === '/dev/null') {
|
||||||
|
return log_name;
|
||||||
|
}
|
||||||
|
let uniqPath = await getUniqPath(command, `${id}`);
|
||||||
|
if (log_name) {
|
||||||
|
const normalizedLogName = log_name.startsWith('/') ? log_name : path.join(config.logPath, log_name);
|
||||||
|
if (normalizedLogName.startsWith(config.logPath)) {
|
||||||
|
uniqPath = log_name;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const logDirPath = path.resolve(config.logPath, `${uniqPath}`);
|
||||||
|
await fs.mkdir(logDirPath, { recursive: true });
|
||||||
|
return uniqPath;
|
||||||
|
}
|
||||||
|
|
||||||
public async create(payload: Crontab): Promise<Crontab> {
|
public async create(payload: Crontab): Promise<Crontab> {
|
||||||
const tab = new Crontab(payload);
|
const tab = new Crontab(payload);
|
||||||
tab.saved = false;
|
tab.saved = false;
|
||||||
|
tab.log_name = await this.getLogName(tab);
|
||||||
const doc = await this.insert(tab);
|
const doc = await this.insert(tab);
|
||||||
|
|
||||||
if (isDemoEnv()) {
|
if (isDemoEnv()) {
|
||||||
@@ -82,6 +124,7 @@ export default class CronService {
|
|||||||
const doc = await this.getDb({ id: payload.id });
|
const doc = await this.getDb({ id: payload.id });
|
||||||
const tab = new Crontab({ ...doc, ...payload });
|
const tab = new Crontab({ ...doc, ...payload });
|
||||||
tab.saved = false;
|
tab.saved = false;
|
||||||
|
tab.log_name = await this.getLogName(tab);
|
||||||
const newDoc = await this.updateDb(tab);
|
const newDoc = await this.updateDb(tab);
|
||||||
|
|
||||||
if (doc.isDisabled === 1 || isDemoEnv()) {
|
if (doc.isDisabled === 1 || isDemoEnv()) {
|
||||||
@@ -142,7 +185,7 @@ export default class CronService {
|
|||||||
let cron;
|
let cron;
|
||||||
try {
|
try {
|
||||||
cron = await this.getDb({ id });
|
cron = await this.getDb({ id });
|
||||||
} catch (err) {}
|
} catch (err) { }
|
||||||
if (!cron) {
|
if (!cron) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -156,21 +199,26 @@ export default class CronService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async remove(ids: number[]) {
|
public async remove(ids: number[], userId?: number) {
|
||||||
|
await this.checkOwnership(ids, userId);
|
||||||
await CrontabModel.destroy({ where: { id: ids } });
|
await CrontabModel.destroy({ where: { id: ids } });
|
||||||
await cronClient.delCron(ids.map(String));
|
await cronClient.delCron(ids.map(String));
|
||||||
await this.setCrontab();
|
await this.setCrontab();
|
||||||
}
|
}
|
||||||
|
|
||||||
public async pin(ids: number[]) {
|
public async pin(ids: number[], userId?: number) {
|
||||||
|
await this.checkOwnership(ids, userId);
|
||||||
await CrontabModel.update({ isPinned: 1 }, { where: { id: ids } });
|
await CrontabModel.update({ isPinned: 1 }, { where: { id: ids } });
|
||||||
}
|
}
|
||||||
|
|
||||||
public async unPin(ids: number[]) {
|
public async unPin(ids: number[], userId?: number) {
|
||||||
|
await this.checkOwnership(ids, userId);
|
||||||
await CrontabModel.update({ isPinned: 0 }, { where: { id: ids } });
|
await CrontabModel.update({ isPinned: 0 }, { where: { id: ids } });
|
||||||
}
|
}
|
||||||
|
|
||||||
public async addLabels(ids: string[], labels: string[]) {
|
public async addLabels(ids: string[], labels: string[], userId?: number) {
|
||||||
|
const numIds = ids.map(Number);
|
||||||
|
await this.checkOwnership(numIds, userId);
|
||||||
const docs = await CrontabModel.findAll({ where: { id: ids } });
|
const docs = await CrontabModel.findAll({ where: { id: ids } });
|
||||||
for (const doc of docs) {
|
for (const doc of docs) {
|
||||||
await CrontabModel.update(
|
await CrontabModel.update(
|
||||||
@@ -182,7 +230,9 @@ export default class CronService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async removeLabels(ids: string[], labels: string[]) {
|
public async removeLabels(ids: string[], labels: string[], userId?: number) {
|
||||||
|
const numIds = ids.map(Number);
|
||||||
|
await this.checkOwnership(numIds, userId);
|
||||||
const docs = await CrontabModel.findAll({ where: { id: ids } });
|
const docs = await CrontabModel.findAll({ where: { id: ids } });
|
||||||
for (const doc of docs) {
|
for (const doc of docs) {
|
||||||
await CrontabModel.update(
|
await CrontabModel.update(
|
||||||
@@ -215,14 +265,24 @@ export default class CronService {
|
|||||||
operate2 = Op.and;
|
operate2 = Op.and;
|
||||||
break;
|
break;
|
||||||
case 'In':
|
case 'In':
|
||||||
q[Op.or] = [
|
if (
|
||||||
{
|
property === 'status' &&
|
||||||
[property]: Array.isArray(value) ? value : [value],
|
!value.includes(CrontabStatus.disabled)
|
||||||
},
|
) {
|
||||||
property === 'status' && value.includes(2)
|
q[Op.and] = [
|
||||||
? { isDisabled: 1 }
|
{ [property]: Array.isArray(value) ? value : [value] },
|
||||||
: {},
|
{ isDisabled: 0 },
|
||||||
];
|
];
|
||||||
|
} else {
|
||||||
|
q[Op.or] = [
|
||||||
|
{
|
||||||
|
[property]: Array.isArray(value) ? value : [value],
|
||||||
|
},
|
||||||
|
property === 'status' && value.includes(CrontabStatus.disabled)
|
||||||
|
? { isDisabled: 1 }
|
||||||
|
: {},
|
||||||
|
];
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
case 'Nin':
|
case 'Nin':
|
||||||
q[Op.and] = [
|
q[Op.and] = [
|
||||||
@@ -367,6 +427,7 @@ export default class CronService {
|
|||||||
sorter: string;
|
sorter: string;
|
||||||
filters: string;
|
filters: string;
|
||||||
queryString: string;
|
queryString: string;
|
||||||
|
userId?: number;
|
||||||
}): Promise<{ data: Crontab[]; total: number }> {
|
}): Promise<{ data: Crontab[]; total: number }> {
|
||||||
const searchText = params?.searchValue;
|
const searchText = params?.searchValue;
|
||||||
const page = Number(params?.page || '0');
|
const page = Number(params?.page || '0');
|
||||||
@@ -387,6 +448,7 @@ export default class CronService {
|
|||||||
this.formatSearchText(query, searchText);
|
this.formatSearchText(query, searchText);
|
||||||
this.formatFilterQuery(query, filterQuery);
|
this.formatFilterQuery(query, filterQuery);
|
||||||
this.formatViewSort(order, viewQuery);
|
this.formatViewSort(order, viewQuery);
|
||||||
|
this.addUserIdFilter(query, params?.userId);
|
||||||
|
|
||||||
if (sorterQuery) {
|
if (sorterQuery) {
|
||||||
const { field, type } = sorterQuery;
|
const { field, type } = sorterQuery;
|
||||||
@@ -419,7 +481,8 @@ export default class CronService {
|
|||||||
return doc.get({ plain: true });
|
return doc.get({ plain: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
public async run(ids: number[]) {
|
public async run(ids: number[], userId?: number) {
|
||||||
|
await this.checkOwnership(ids, userId);
|
||||||
await CrontabModel.update(
|
await CrontabModel.update(
|
||||||
{ status: CrontabStatus.queued },
|
{ status: CrontabStatus.queued },
|
||||||
{ where: { id: ids } },
|
{ where: { id: ids } },
|
||||||
@@ -429,7 +492,8 @@ export default class CronService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public async stop(ids: number[]) {
|
public async stop(ids: number[], userId?: number) {
|
||||||
|
await this.checkOwnership(ids, userId);
|
||||||
const docs = await CrontabModel.findAll({ where: { id: ids } });
|
const docs = await CrontabModel.findAll({ where: { id: ids } });
|
||||||
for (const doc of docs) {
|
for (const doc of docs) {
|
||||||
if (doc.pid) {
|
if (doc.pid) {
|
||||||
@@ -466,13 +530,12 @@ export default class CronService {
|
|||||||
`[panel][开始执行任务] 参数: ${JSON.stringify(params)}`,
|
`[panel][开始执行任务] 参数: ${JSON.stringify(params)}`,
|
||||||
);
|
);
|
||||||
|
|
||||||
let { id, command, log_path } = cron;
|
let { id, command, log_name } = cron;
|
||||||
const uniqPath = await getUniqPath(command, `${id}`);
|
|
||||||
|
const uniqPath = log_name === '/dev/null' ? (await getUniqPath(command, `${id}`)) : log_name;
|
||||||
const logTime = dayjs().format('YYYY-MM-DD-HH-mm-ss-SSS');
|
const logTime = dayjs().format('YYYY-MM-DD-HH-mm-ss-SSS');
|
||||||
const logDirPath = path.resolve(config.logPath, `${uniqPath}`);
|
const logDirPath = path.resolve(config.logPath, `${uniqPath}`);
|
||||||
if (log_path?.split('/')?.every((x) => x !== uniqPath)) {
|
await fs.mkdir(logDirPath, { recursive: true });
|
||||||
await fs.mkdir(logDirPath, { recursive: true });
|
|
||||||
}
|
|
||||||
const logPath = `${uniqPath}/${logTime}.log`;
|
const logPath = `${uniqPath}/${logTime}.log`;
|
||||||
const absolutePath = path.resolve(config.logPath, `${logPath}`);
|
const absolutePath = path.resolve(config.logPath, `${logPath}`);
|
||||||
const cp = spawn(
|
const cp = spawn(
|
||||||
@@ -523,13 +586,15 @@ export default class CronService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public async disabled(ids: number[]) {
|
public async disabled(ids: number[], userId?: number) {
|
||||||
|
await this.checkOwnership(ids, userId);
|
||||||
await CrontabModel.update({ isDisabled: 1 }, { where: { id: ids } });
|
await CrontabModel.update({ isDisabled: 1 }, { where: { id: ids } });
|
||||||
await cronClient.delCron(ids.map(String));
|
await cronClient.delCron(ids.map(String));
|
||||||
await this.setCrontab();
|
await this.setCrontab();
|
||||||
}
|
}
|
||||||
|
|
||||||
public async enabled(ids: number[]) {
|
public async enabled(ids: number[], userId?: number) {
|
||||||
|
await this.checkOwnership(ids, userId);
|
||||||
await CrontabModel.update({ isDisabled: 0 }, { where: { id: ids } });
|
await CrontabModel.update({ isDisabled: 0 }, { where: { id: ids } });
|
||||||
const docs = await CrontabModel.findAll({ where: { id: ids } });
|
const docs = await CrontabModel.findAll({ where: { id: ids } });
|
||||||
const sixCron = docs
|
const sixCron = docs
|
||||||
@@ -554,13 +619,18 @@ export default class CronService {
|
|||||||
if (!doc) {
|
if (!doc) {
|
||||||
return '';
|
return '';
|
||||||
}
|
}
|
||||||
|
if (doc.log_name === '/dev/null') {
|
||||||
|
return '日志设置为忽略';
|
||||||
|
}
|
||||||
const absolutePath = path.resolve(config.logPath, `${doc.log_path}`);
|
const absolutePath = path.resolve(config.logPath, `${doc.log_path}`);
|
||||||
const logFileExist = doc.log_path && (await fileExist(absolutePath));
|
const logFileExist = doc.log_path && (await fileExist(absolutePath));
|
||||||
if (logFileExist) {
|
if (logFileExist) {
|
||||||
return await getFileContentByName(`${absolutePath}`);
|
return await getFileContentByName(`${absolutePath}`);
|
||||||
} else {
|
} else {
|
||||||
return '任务未运行';
|
return typeof doc.status === 'number' &&
|
||||||
|
[CrontabStatus.queued, CrontabStatus.running].includes(doc.status)
|
||||||
|
? '运行中...'
|
||||||
|
: '日志不存在...';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -580,7 +650,7 @@ export default class CronService {
|
|||||||
files.map(async (x) => ({
|
files.map(async (x) => ({
|
||||||
filename: x,
|
filename: x,
|
||||||
directory: relativeDir.replace(config.logPath, ''),
|
directory: relativeDir.replace(config.logPath, ''),
|
||||||
time: (await fs.lstat(`${dir}/${x}`)).mtime.getTime(),
|
time: (await fs.lstat(`${dir}/${x}`)).birthtimeMs,
|
||||||
})),
|
})),
|
||||||
)
|
)
|
||||||
).sort((a, b) => b.time - a.time);
|
).sort((a, b) => b.time - a.time);
|
||||||
@@ -594,9 +664,7 @@ export default class CronService {
|
|||||||
if (!command.startsWith(TASK_PREFIX) && !command.startsWith(QL_PREFIX)) {
|
if (!command.startsWith(TASK_PREFIX) && !command.startsWith(QL_PREFIX)) {
|
||||||
command = `${TASK_PREFIX}${tab.command}`;
|
command = `${TASK_PREFIX}${tab.command}`;
|
||||||
}
|
}
|
||||||
let commandVariable = `real_time=${Boolean(realTime)} no_tee=true ID=${
|
let commandVariable = `real_time=${Boolean(realTime)} log_name=${tab.log_name} no_tee=true ID=${tab.id} `;
|
||||||
tab.id
|
|
||||||
} `;
|
|
||||||
if (tab.task_before) {
|
if (tab.task_before) {
|
||||||
commandVariable += `task_before='${tab.task_before
|
commandVariable += `task_before='${tab.task_before
|
||||||
.replace(/'/g, "'\\''")
|
.replace(/'/g, "'\\''")
|
||||||
@@ -694,6 +762,7 @@ export default class CronService {
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
if (isDemoEnv()) {
|
if (isDemoEnv()) {
|
||||||
|
await writeFileWithLock(config.crontabFile, '');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
await cronClient.addCron(regularCrons);
|
await cronClient.addCron(regularCrons);
|
||||||
|
|||||||
+51
-32
@@ -6,7 +6,6 @@ import {
|
|||||||
DependenceStatus,
|
DependenceStatus,
|
||||||
DependenceTypes,
|
DependenceTypes,
|
||||||
DependenceModel,
|
DependenceModel,
|
||||||
GetDependenceCommandTypes,
|
|
||||||
versionDependenceCommandTypes,
|
versionDependenceCommandTypes,
|
||||||
} from '../data/dependence';
|
} from '../data/dependence';
|
||||||
import { spawn } from 'cross-spawn';
|
import { spawn } from 'cross-spawn';
|
||||||
@@ -19,6 +18,7 @@ import {
|
|||||||
promiseExecSuccess,
|
promiseExecSuccess,
|
||||||
getInstallCommand,
|
getInstallCommand,
|
||||||
getUninstallCommand,
|
getUninstallCommand,
|
||||||
|
getGetCommand,
|
||||||
} from '../config/util';
|
} from '../config/util';
|
||||||
import dayjs from 'dayjs';
|
import dayjs from 'dayjs';
|
||||||
import taskLimit from '../shared/pLimit';
|
import taskLimit from '../shared/pLimit';
|
||||||
@@ -28,11 +28,35 @@ export default class DependenceService {
|
|||||||
constructor(
|
constructor(
|
||||||
@Inject('logger') private logger: winston.Logger,
|
@Inject('logger') private logger: winston.Logger,
|
||||||
private sockService: SockService,
|
private sockService: SockService,
|
||||||
) {}
|
) { }
|
||||||
|
|
||||||
public async create(payloads: Dependence[]): Promise<Dependence[]> {
|
private addUserIdFilter(query: any, userId?: number) {
|
||||||
|
if (userId !== undefined) {
|
||||||
|
query.userId = userId;
|
||||||
|
}
|
||||||
|
return query;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async checkOwnership(ids: number[], userId?: number): Promise<void> {
|
||||||
|
if (userId === undefined) {
|
||||||
|
// Admin can access all dependencies
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const dependencies = await DependenceModel.findAll({
|
||||||
|
where: { id: ids },
|
||||||
|
attributes: ['id', 'userId'],
|
||||||
|
});
|
||||||
|
const unauthorized = dependencies.filter(
|
||||||
|
(dep) => dep.userId !== undefined && dep.userId !== userId
|
||||||
|
);
|
||||||
|
if (unauthorized.length > 0) {
|
||||||
|
throw new Error('无权限操作该依赖');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async create(payloads: Dependence[], userId?: number): Promise<Dependence[]> {
|
||||||
const tabs = payloads.map((x) => {
|
const tabs = payloads.map((x) => {
|
||||||
const tab = new Dependence({ ...x, status: DependenceStatus.queued });
|
const tab = new Dependence({ ...x, status: DependenceStatus.queued, userId });
|
||||||
return tab;
|
return tab;
|
||||||
});
|
});
|
||||||
const docs = await this.insert(tabs);
|
const docs = await this.insert(tabs);
|
||||||
@@ -65,7 +89,8 @@ export default class DependenceService {
|
|||||||
return await this.getDb({ id: payload.id });
|
return await this.getDb({ id: payload.id });
|
||||||
}
|
}
|
||||||
|
|
||||||
public async remove(ids: number[], force = false): Promise<Dependence[]> {
|
public async remove(ids: number[], force = false, userId?: number): Promise<Dependence[]> {
|
||||||
|
await this.checkOwnership(ids, userId);
|
||||||
const docs = await DependenceModel.findAll({ where: { id: ids } });
|
const docs = await DependenceModel.findAll({ where: { id: ids } });
|
||||||
for (const doc of docs) {
|
for (const doc of docs) {
|
||||||
taskLimit.removeQueuedDependency(doc);
|
taskLimit.removeQueuedDependency(doc);
|
||||||
@@ -98,34 +123,34 @@ export default class DependenceService {
|
|||||||
searchValue,
|
searchValue,
|
||||||
type,
|
type,
|
||||||
status,
|
status,
|
||||||
}: { searchValue: string; type: string; status: string },
|
}: {
|
||||||
|
searchValue: string;
|
||||||
|
type: keyof typeof DependenceTypes;
|
||||||
|
status: string;
|
||||||
|
},
|
||||||
sort: any = [],
|
sort: any = [],
|
||||||
query: any = {},
|
query: any = {},
|
||||||
|
userId?: number,
|
||||||
): Promise<Dependence[]> {
|
): Promise<Dependence[]> {
|
||||||
let condition = {
|
let condition = query;
|
||||||
...query,
|
this.addUserIdFilter(condition, userId);
|
||||||
type: DependenceTypes[type as any],
|
if (DependenceTypes[type]) {
|
||||||
};
|
condition.type = DependenceTypes[type];
|
||||||
|
}
|
||||||
if (status) {
|
if (status) {
|
||||||
condition.status = status.split(',').map(Number);
|
condition.status = status.split(',').map(Number);
|
||||||
}
|
}
|
||||||
if (searchValue) {
|
if (searchValue) {
|
||||||
const encodeText = encodeURI(searchValue);
|
const encodeText = encodeURI(searchValue);
|
||||||
const reg = {
|
condition.name = {
|
||||||
[Op.or]: [
|
[Op.or]: [
|
||||||
{ [Op.like]: `%${searchValue}%` },
|
{ [Op.like]: `%${searchValue}%` },
|
||||||
{ [Op.like]: `%${encodeText}%` },
|
{ [Op.like]: `%${encodeText}%` },
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
|
|
||||||
condition = {
|
|
||||||
...condition,
|
|
||||||
name: reg,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const result = await this.find(condition, sort);
|
return await this.find(condition, sort);
|
||||||
return result as any;
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
@@ -143,7 +168,8 @@ export default class DependenceService {
|
|||||||
return taskLimit.waitDependencyQueueDone();
|
return taskLimit.waitDependencyQueueDone();
|
||||||
}
|
}
|
||||||
|
|
||||||
public async reInstall(ids: number[]): Promise<Dependence[]> {
|
public async reInstall(ids: number[], userId?: number): Promise<Dependence[]> {
|
||||||
|
await this.checkOwnership(ids, userId);
|
||||||
await DependenceModel.update(
|
await DependenceModel.update(
|
||||||
{ status: DependenceStatus.queued, log: [] },
|
{ status: DependenceStatus.queued, log: [] },
|
||||||
{ where: { id: ids } },
|
{ where: { id: ids } },
|
||||||
@@ -157,17 +183,16 @@ export default class DependenceService {
|
|||||||
return docs;
|
return docs;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async cancel(ids: number[]) {
|
public async cancel(ids: number[], userId?: number) {
|
||||||
|
await this.checkOwnership(ids, userId);
|
||||||
const docs = await DependenceModel.findAll({ where: { id: ids } });
|
const docs = await DependenceModel.findAll({ where: { id: ids } });
|
||||||
for (const doc of docs) {
|
for (const doc of docs) {
|
||||||
taskLimit.removeQueuedDependency(doc);
|
taskLimit.removeQueuedDependency(doc);
|
||||||
const depInstallCommand = getInstallCommand(doc.type, doc.name);
|
const depInstallCommand = getInstallCommand(doc.type, doc.name);
|
||||||
const depUnInstallCommand = getUninstallCommand(doc.type, doc.name);
|
const depUnInstallCommand = getUninstallCommand(doc.type, doc.name);
|
||||||
const installCmd = `${depInstallCommand} ${doc.name.trim()}`;
|
|
||||||
const unInstallCmd = `${depUnInstallCommand} ${doc.name.trim()}`;
|
|
||||||
const pids = await Promise.all([
|
const pids = await Promise.all([
|
||||||
getPid(installCmd),
|
getPid(depInstallCommand),
|
||||||
getPid(unInstallCmd),
|
getPid(depUnInstallCommand),
|
||||||
]);
|
]);
|
||||||
for (const pid of pids) {
|
for (const pid of pids) {
|
||||||
pid && (await killTask(pid));
|
pid && (await killTask(pid));
|
||||||
@@ -252,7 +277,7 @@ export default class DependenceService {
|
|||||||
|
|
||||||
// 判断是否已经安装过依赖
|
// 判断是否已经安装过依赖
|
||||||
if (isInstall && !force) {
|
if (isInstall && !force) {
|
||||||
const getCommandPrefix = GetDependenceCommandTypes[dependency.type];
|
const getCommand = getGetCommand(dependency.type, depName);
|
||||||
const depVersionStr = versionDependenceCommandTypes[dependency.type];
|
const depVersionStr = versionDependenceCommandTypes[dependency.type];
|
||||||
let depVersion = '';
|
let depVersion = '';
|
||||||
if (depName.includes(depVersionStr)) {
|
if (depName.includes(depVersionStr)) {
|
||||||
@@ -269,13 +294,7 @@ export default class DependenceService {
|
|||||||
const isLinuxDependence = dependency.type === DependenceTypes.linux;
|
const isLinuxDependence = dependency.type === DependenceTypes.linux;
|
||||||
const isPythonDependence =
|
const isPythonDependence =
|
||||||
dependency.type === DependenceTypes.python3;
|
dependency.type === DependenceTypes.python3;
|
||||||
const depInfo = (
|
const depInfo = (await promiseExecSuccess(getCommand))
|
||||||
await promiseExecSuccess(
|
|
||||||
isNodeDependence
|
|
||||||
? `${getCommandPrefix} | grep "${depName}" | head -1`
|
|
||||||
: `${getCommandPrefix} ${depName}`,
|
|
||||||
)
|
|
||||||
)
|
|
||||||
.replace(/\s{2,}/, ' ')
|
.replace(/\s{2,}/, ' ')
|
||||||
.replace(/\s+$/, '');
|
.replace(/\s+$/, '');
|
||||||
|
|
||||||
|
|||||||
+49
-12
@@ -1,7 +1,8 @@
|
|||||||
import { Service, Inject } from 'typedi';
|
import groupBy from 'lodash/groupBy';
|
||||||
|
import { FindOptions, Op } from 'sequelize';
|
||||||
|
import { Inject, Service } from 'typedi';
|
||||||
import winston from 'winston';
|
import winston from 'winston';
|
||||||
import config from '../config';
|
import config from '../config';
|
||||||
import * as fs from 'fs/promises';
|
|
||||||
import {
|
import {
|
||||||
Env,
|
Env,
|
||||||
EnvModel,
|
EnvModel,
|
||||||
@@ -11,16 +12,38 @@ import {
|
|||||||
minPosition,
|
minPosition,
|
||||||
stepPosition,
|
stepPosition,
|
||||||
} from '../data/env';
|
} from '../data/env';
|
||||||
import groupBy from 'lodash/groupBy';
|
|
||||||
import { FindOptions, Op } from 'sequelize';
|
|
||||||
import { writeFileWithLock } from '../shared/utils';
|
import { writeFileWithLock } from '../shared/utils';
|
||||||
|
|
||||||
@Service()
|
@Service()
|
||||||
export default class EnvService {
|
export default class EnvService {
|
||||||
constructor(@Inject('logger') private logger: winston.Logger) {}
|
constructor(@Inject('logger') private logger: winston.Logger) {}
|
||||||
|
|
||||||
public async create(payloads: Env[]): Promise<Env[]> {
|
private addUserIdFilter(query: any, userId?: number) {
|
||||||
const envs = await this.envs();
|
if (userId !== undefined) {
|
||||||
|
query.userId = userId;
|
||||||
|
}
|
||||||
|
return query;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async checkOwnership(ids: number[], userId?: number): Promise<void> {
|
||||||
|
if (userId === undefined) {
|
||||||
|
// Admin can access all envs
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const envs = await EnvModel.findAll({
|
||||||
|
where: { id: ids },
|
||||||
|
attributes: ['id', 'userId'],
|
||||||
|
});
|
||||||
|
const unauthorized = envs.filter(
|
||||||
|
(env) => env.userId !== undefined && env.userId !== userId
|
||||||
|
);
|
||||||
|
if (unauthorized.length > 0) {
|
||||||
|
throw new Error('无权限操作该环境变量');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async create(payloads: Env[], userId?: number): Promise<Env[]> {
|
||||||
|
const envs = await this.envs('', {}, userId);
|
||||||
let position = initPosition;
|
let position = initPosition;
|
||||||
if (
|
if (
|
||||||
envs &&
|
envs &&
|
||||||
@@ -31,7 +54,7 @@ export default class EnvService {
|
|||||||
}
|
}
|
||||||
const tabs = payloads.map((x) => {
|
const tabs = payloads.map((x) => {
|
||||||
position = position - stepPosition;
|
position = position - stepPosition;
|
||||||
const tab = new Env({ ...x, position });
|
const tab = new Env({ ...x, position, userId });
|
||||||
return tab;
|
return tab;
|
||||||
});
|
});
|
||||||
const docs = await this.insert(tabs);
|
const docs = await this.insert(tabs);
|
||||||
@@ -62,7 +85,8 @@ export default class EnvService {
|
|||||||
return await this.getDb({ id: payload.id });
|
return await this.getDb({ id: payload.id });
|
||||||
}
|
}
|
||||||
|
|
||||||
public async remove(ids: number[]) {
|
public async remove(ids: number[], userId?: number) {
|
||||||
|
await this.checkOwnership(ids, userId);
|
||||||
await EnvModel.destroy({ where: { id: ids } });
|
await EnvModel.destroy({ where: { id: ids } });
|
||||||
await this.set_envs();
|
await this.set_envs();
|
||||||
}
|
}
|
||||||
@@ -119,8 +143,9 @@ export default class EnvService {
|
|||||||
return parseFloat(position.toPrecision(16));
|
return parseFloat(position.toPrecision(16));
|
||||||
}
|
}
|
||||||
|
|
||||||
public async envs(searchText: string = '', query: any = {}): Promise<Env[]> {
|
public async envs(searchText: string = '', query: any = {}, userId?: number): Promise<Env[]> {
|
||||||
let condition = { ...query };
|
let condition = { ...query };
|
||||||
|
this.addUserIdFilter(condition, userId);
|
||||||
if (searchText) {
|
if (searchText) {
|
||||||
const encodeText = encodeURI(searchText);
|
const encodeText = encodeURI(searchText);
|
||||||
const reg = {
|
const reg = {
|
||||||
@@ -147,6 +172,7 @@ export default class EnvService {
|
|||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const result = await this.find(condition, [
|
const result = await this.find(condition, [
|
||||||
|
['isPinned', 'DESC'],
|
||||||
['position', 'DESC'],
|
['position', 'DESC'],
|
||||||
['createdAt', 'ASC'],
|
['createdAt', 'ASC'],
|
||||||
]);
|
]);
|
||||||
@@ -172,7 +198,8 @@ export default class EnvService {
|
|||||||
return doc.get({ plain: true });
|
return doc.get({ plain: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
public async disabled(ids: number[]) {
|
public async disabled(ids: number[], userId?: number) {
|
||||||
|
await this.checkOwnership(ids, userId);
|
||||||
await EnvModel.update(
|
await EnvModel.update(
|
||||||
{ status: EnvStatus.disabled },
|
{ status: EnvStatus.disabled },
|
||||||
{ where: { id: ids } },
|
{ where: { id: ids } },
|
||||||
@@ -180,16 +207,26 @@ export default class EnvService {
|
|||||||
await this.set_envs();
|
await this.set_envs();
|
||||||
}
|
}
|
||||||
|
|
||||||
public async enabled(ids: number[]) {
|
public async enabled(ids: number[], userId?: number) {
|
||||||
|
await this.checkOwnership(ids, userId);
|
||||||
await EnvModel.update({ status: EnvStatus.normal }, { where: { id: ids } });
|
await EnvModel.update({ status: EnvStatus.normal }, { where: { id: ids } });
|
||||||
await this.set_envs();
|
await this.set_envs();
|
||||||
}
|
}
|
||||||
|
|
||||||
public async updateNames({ ids, name }: { ids: number[]; name: string }) {
|
public async updateNames({ ids, name }: { ids: number[]; name: string }, userId?: number) {
|
||||||
|
await this.checkOwnership(ids, userId);
|
||||||
await EnvModel.update({ name }, { where: { id: ids } });
|
await EnvModel.update({ name }, { where: { id: ids } });
|
||||||
await this.set_envs();
|
await this.set_envs();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async pin(ids: number[]) {
|
||||||
|
await EnvModel.update({ isPinned: 1 }, { where: { id: ids } });
|
||||||
|
}
|
||||||
|
|
||||||
|
public async unPin(ids: number[]) {
|
||||||
|
await EnvModel.update({ isPinned: 0 }, { where: { id: ids } });
|
||||||
|
}
|
||||||
|
|
||||||
public async set_envs() {
|
public async set_envs() {
|
||||||
const envs = await this.envs('', {
|
const envs = await this.envs('', {
|
||||||
name: { [Op.not]: null },
|
name: { [Op.not]: null },
|
||||||
|
|||||||
+36
-5
@@ -49,12 +49,21 @@ export default class NotificationService {
|
|||||||
public async notify(
|
public async notify(
|
||||||
title: string,
|
title: string,
|
||||||
content: string,
|
content: string,
|
||||||
|
notificationInfo?: NotificationInfo,
|
||||||
): Promise<boolean | undefined> {
|
): Promise<boolean | undefined> {
|
||||||
const { type, ...rest } = await this.userService.getNotificationMode();
|
let { type, ...rest } = await this.userService.getNotificationMode();
|
||||||
|
if (notificationInfo?.type) {
|
||||||
|
type = notificationInfo?.type;
|
||||||
|
}
|
||||||
if (type) {
|
if (type) {
|
||||||
this.title = title;
|
this.title = title;
|
||||||
this.content = content;
|
this.content = content;
|
||||||
this.params = rest;
|
let params = rest;
|
||||||
|
if (notificationInfo) {
|
||||||
|
const { type: _, ...others } = notificationInfo;
|
||||||
|
params = { ...rest, ...others };
|
||||||
|
}
|
||||||
|
this.params = params;
|
||||||
const notificationModeAction = this.modeMap.get(type);
|
const notificationModeAction = this.modeMap.get(type);
|
||||||
try {
|
try {
|
||||||
return await notificationModeAction?.call(this);
|
return await notificationModeAction?.call(this);
|
||||||
@@ -623,20 +632,42 @@ export default class NotificationService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private async ntfy() {
|
private async ntfy() {
|
||||||
const { ntfyUrl, ntfyTopic, ntfyPriority } = this.params;
|
const {
|
||||||
|
ntfyUrl,
|
||||||
|
ntfyTopic,
|
||||||
|
ntfyPriority,
|
||||||
|
ntfyToken,
|
||||||
|
ntfyUsername,
|
||||||
|
ntfyPassword,
|
||||||
|
ntfyActions,
|
||||||
|
} = this.params;
|
||||||
// 编码函数
|
// 编码函数
|
||||||
const encodeRfc2047 = (text: string, charset: string = 'UTF-8'): string => {
|
const encodeRfc2047 = (text: string, charset: string = 'UTF-8'): string => {
|
||||||
const encodedText = Buffer.from(text).toString('base64');
|
const encodedText = Buffer.from(text).toString('base64');
|
||||||
return `=?${charset}?B?${encodedText}?=`;
|
return `=?${charset}?B?${encodedText}?=`;
|
||||||
};
|
};
|
||||||
try {
|
try {
|
||||||
const encodedTitle = encodeRfc2047(this.title);
|
const headers: Record<string, string> = {
|
||||||
|
Title: encodeRfc2047(this.title),
|
||||||
|
Priority: `${ntfyPriority || '3'}`,
|
||||||
|
Icon: 'https://qn.whyour.cn/logo.png',
|
||||||
|
};
|
||||||
|
if (ntfyToken) {
|
||||||
|
headers['Authorization'] = `Bearer ${ntfyToken}`;
|
||||||
|
} else if (ntfyUsername && ntfyPassword) {
|
||||||
|
headers['Authorization'] = `Basic ${Buffer.from(
|
||||||
|
`${ntfyUsername}:${ntfyPassword}`,
|
||||||
|
).toString('base64')}`;
|
||||||
|
}
|
||||||
|
if (ntfyActions) {
|
||||||
|
headers['Actions'] = encodeRfc2047(ntfyActions);
|
||||||
|
}
|
||||||
const res = await httpClient.request(
|
const res = await httpClient.request(
|
||||||
`${ntfyUrl || 'https://ntfy.sh'}/${ntfyTopic}`,
|
`${ntfyUrl || 'https://ntfy.sh'}/${ntfyTopic}`,
|
||||||
{
|
{
|
||||||
...this.gotOption,
|
...this.gotOption,
|
||||||
body: `${this.content}`,
|
body: `${this.content}`,
|
||||||
headers: { Title: encodedTitle, Priority: `${ntfyPriority || '3'}` },
|
headers: headers,
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -139,7 +139,7 @@ export default class ScheduleService {
|
|||||||
) {
|
) {
|
||||||
const _id = this.formatId(id);
|
const _id = this.formatId(id);
|
||||||
this.logger.info(
|
this.logger.info(
|
||||||
'[panel][创建cron任务], 任务ID: %s, cron: %s, 任务名: %s, 执行命令: %s',
|
'[panel][创建cron任务] 任务ID: %s, cron: %s, 任务名: %s, 执行命令: %s',
|
||||||
_id,
|
_id,
|
||||||
schedule,
|
schedule,
|
||||||
name,
|
name,
|
||||||
@@ -172,7 +172,7 @@ export default class ScheduleService {
|
|||||||
|
|
||||||
async cancelCronTask({ id = 0, name }: ScheduleTaskType) {
|
async cancelCronTask({ id = 0, name }: ScheduleTaskType) {
|
||||||
const _id = this.formatId(id);
|
const _id = this.formatId(id);
|
||||||
this.logger.info('[panel][取消定时任务], 任务名: %s', name);
|
this.logger.info('[panel][取消定时任务] 任务名: %s', name);
|
||||||
if (this.scheduleStacks.has(_id)) {
|
if (this.scheduleStacks.has(_id)) {
|
||||||
this.scheduleStacks.get(_id)?.cancel();
|
this.scheduleStacks.get(_id)?.cancel();
|
||||||
this.scheduleStacks.delete(_id);
|
this.scheduleStacks.delete(_id);
|
||||||
@@ -187,7 +187,7 @@ export default class ScheduleService {
|
|||||||
) {
|
) {
|
||||||
const _id = this.formatId(id);
|
const _id = this.formatId(id);
|
||||||
this.logger.info(
|
this.logger.info(
|
||||||
'[panel][创建interval任务], 任务ID: %s, 任务名: %s, 执行命令: %s',
|
'[panel][创建interval任务] 任务ID: %s, 任务名: %s, 执行命令: %s',
|
||||||
_id,
|
_id,
|
||||||
name,
|
name,
|
||||||
command,
|
command,
|
||||||
@@ -232,7 +232,7 @@ export default class ScheduleService {
|
|||||||
async cancelIntervalTask({ id = 0, name }: ScheduleTaskType) {
|
async cancelIntervalTask({ id = 0, name }: ScheduleTaskType) {
|
||||||
const _id = this.formatId(id);
|
const _id = this.formatId(id);
|
||||||
this.logger.info(
|
this.logger.info(
|
||||||
'[panel][取消interval任务], 任务ID: %s, 任务名: %s',
|
'[panel][取消interval任务] 任务ID: %s, 任务名: %s',
|
||||||
_id,
|
_id,
|
||||||
name,
|
name,
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -26,12 +26,13 @@ export default class SshKeyService {
|
|||||||
if (_exist) {
|
if (_exist) {
|
||||||
config = await fs.readFile(this.sshConfigFilePath, { encoding: 'utf-8' });
|
config = await fs.readFile(this.sshConfigFilePath, { encoding: 'utf-8' });
|
||||||
} else {
|
} else {
|
||||||
await writeFileWithLock(this.sshConfigFilePath, '');
|
await writeFileWithLock(this.sshConfigFilePath, '', { mode: '600' });
|
||||||
}
|
}
|
||||||
if (!config.includes(this.sshConfigHeader)) {
|
if (!config.includes(this.sshConfigHeader)) {
|
||||||
await writeFileWithLock(
|
await writeFileWithLock(
|
||||||
this.sshConfigFilePath,
|
this.sshConfigFilePath,
|
||||||
`${this.sshConfigHeader}\n\n${config}`,
|
`${this.sshConfigHeader}\n\n${config}`,
|
||||||
|
{ mode: '600' },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -45,7 +46,6 @@ export default class SshKeyService {
|
|||||||
path.join(this.sshPath, alias),
|
path.join(this.sshPath, alias),
|
||||||
`${key}${os.EOL}`,
|
`${key}${os.EOL}`,
|
||||||
{
|
{
|
||||||
encoding: 'utf8',
|
|
||||||
mode: '400',
|
mode: '400',
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -81,6 +81,10 @@ export default class SshKeyService {
|
|||||||
await writeFileWithLock(
|
await writeFileWithLock(
|
||||||
`${path.join(this.sshPath, `${alias}.config`)}`,
|
`${path.join(this.sshPath, `${alias}.config`)}`,
|
||||||
config,
|
config,
|
||||||
|
{
|
||||||
|
encoding: 'utf8',
|
||||||
|
mode: '600',
|
||||||
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -42,11 +42,37 @@ export default class SubscriptionService {
|
|||||||
private crontabService: CrontabService,
|
private crontabService: CrontabService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
|
private addUserIdFilter(query: any, userId?: number) {
|
||||||
|
if (userId !== undefined) {
|
||||||
|
query.userId = userId;
|
||||||
|
}
|
||||||
|
return query;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async checkOwnership(ids: number[], userId?: number): Promise<void> {
|
||||||
|
if (userId === undefined) {
|
||||||
|
// Admin can access all subscriptions
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const subscriptions = await SubscriptionModel.findAll({
|
||||||
|
where: { id: ids },
|
||||||
|
attributes: ['id', 'userId'],
|
||||||
|
});
|
||||||
|
const unauthorized = subscriptions.filter(
|
||||||
|
(sub) => sub.userId !== undefined && sub.userId !== userId
|
||||||
|
);
|
||||||
|
if (unauthorized.length > 0) {
|
||||||
|
throw new Error('无权限操作该订阅');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public async list(
|
public async list(
|
||||||
searchText?: string,
|
searchText?: string,
|
||||||
ids?: string,
|
ids?: string,
|
||||||
|
userId?: number,
|
||||||
): Promise<SubscriptionInstance[]> {
|
): Promise<SubscriptionInstance[]> {
|
||||||
let query = {};
|
let query: any = {};
|
||||||
|
this.addUserIdFilter(query, userId);
|
||||||
const subIds = JSON.parse(ids || '[]');
|
const subIds = JSON.parse(ids || '[]');
|
||||||
if (searchText) {
|
if (searchText) {
|
||||||
const reg = {
|
const reg = {
|
||||||
@@ -262,7 +288,8 @@ export default class SubscriptionService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async remove(ids: number[], query: { force?: boolean }) {
|
public async remove(ids: number[], query: { force?: boolean }, userId?: number) {
|
||||||
|
await this.checkOwnership(ids, userId);
|
||||||
const docs = await SubscriptionModel.findAll({ where: { id: ids } });
|
const docs = await SubscriptionModel.findAll({ where: { id: ids } });
|
||||||
for (const doc of docs) {
|
for (const doc of docs) {
|
||||||
await this.handleTask(doc.get({ plain: true }), false);
|
await this.handleTask(doc.get({ plain: true }), false);
|
||||||
@@ -273,7 +300,7 @@ export default class SubscriptionService {
|
|||||||
if (query?.force === true) {
|
if (query?.force === true) {
|
||||||
const crons = await CrontabModel.findAll({ where: { sub_id: ids } });
|
const crons = await CrontabModel.findAll({ where: { sub_id: ids } });
|
||||||
if (crons?.length) {
|
if (crons?.length) {
|
||||||
await this.crontabService.remove(crons.map((x) => x.id!));
|
await this.crontabService.remove(crons.map((x) => x.id!), userId);
|
||||||
}
|
}
|
||||||
for (const doc of docs) {
|
for (const doc of docs) {
|
||||||
const filePath = join(config.scriptPath, doc.alias);
|
const filePath = join(config.scriptPath, doc.alias);
|
||||||
@@ -294,7 +321,8 @@ export default class SubscriptionService {
|
|||||||
return doc.get({ plain: true });
|
return doc.get({ plain: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
public async run(ids: number[]) {
|
public async run(ids: number[], userId?: number) {
|
||||||
|
await this.checkOwnership(ids, userId);
|
||||||
await SubscriptionModel.update(
|
await SubscriptionModel.update(
|
||||||
{ status: SubscriptionStatus.queued },
|
{ status: SubscriptionStatus.queued },
|
||||||
{ where: { id: ids } },
|
{ where: { id: ids } },
|
||||||
@@ -304,7 +332,8 @@ export default class SubscriptionService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public async stop(ids: number[]) {
|
public async stop(ids: number[], userId?: number) {
|
||||||
|
await this.checkOwnership(ids, userId);
|
||||||
const docs = await SubscriptionModel.findAll({ where: { id: ids } });
|
const docs = await SubscriptionModel.findAll({ where: { id: ids } });
|
||||||
for (const doc of docs) {
|
for (const doc of docs) {
|
||||||
if (doc.pid) {
|
if (doc.pid) {
|
||||||
@@ -339,7 +368,8 @@ export default class SubscriptionService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public async disabled(ids: number[]) {
|
public async disabled(ids: number[], userId?: number) {
|
||||||
|
await this.checkOwnership(ids, userId);
|
||||||
await SubscriptionModel.update({ is_disabled: 1 }, { where: { id: ids } });
|
await SubscriptionModel.update({ is_disabled: 1 }, { where: { id: ids } });
|
||||||
const docs = await SubscriptionModel.findAll({ where: { id: ids } });
|
const docs = await SubscriptionModel.findAll({ where: { id: ids } });
|
||||||
await this.setSshConfig();
|
await this.setSshConfig();
|
||||||
@@ -348,7 +378,8 @@ export default class SubscriptionService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async enabled(ids: number[]) {
|
public async enabled(ids: number[], userId?: number) {
|
||||||
|
await this.checkOwnership(ids, userId);
|
||||||
await SubscriptionModel.update({ is_disabled: 0 }, { where: { id: ids } });
|
await SubscriptionModel.update({ is_disabled: 0 }, { where: { id: ids } });
|
||||||
const docs = await SubscriptionModel.findAll({ where: { id: ids } });
|
const docs = await SubscriptionModel.findAll({ where: { id: ids } });
|
||||||
await this.setSshConfig();
|
await this.setSshConfig();
|
||||||
@@ -384,7 +415,7 @@ export default class SubscriptionService {
|
|||||||
files.map(async (x) => ({
|
files.map(async (x) => ({
|
||||||
filename: x,
|
filename: x,
|
||||||
directory: relativeDir.replace(config.logPath, ''),
|
directory: relativeDir.replace(config.logPath, ''),
|
||||||
time: (await fs.lstat(`${dir}/${x}`)).mtime.getTime(),
|
time: (await fs.lstat(`${dir}/${x}`)).birthtimeMs,
|
||||||
})),
|
})),
|
||||||
)
|
)
|
||||||
).sort((a, b) => b.time - a.time);
|
).sort((a, b) => b.time - a.time);
|
||||||
|
|||||||
+46
-9
@@ -7,7 +7,7 @@ import path from 'path';
|
|||||||
import { Inject, Service } from 'typedi';
|
import { Inject, Service } from 'typedi';
|
||||||
import winston from 'winston';
|
import winston from 'winston';
|
||||||
import config from '../config';
|
import config from '../config';
|
||||||
import { TASK_COMMAND } from '../config/const';
|
import { NotificationModeStringMap, TASK_COMMAND } from '../config/const';
|
||||||
import {
|
import {
|
||||||
getPid,
|
getPid,
|
||||||
killTask,
|
killTask,
|
||||||
@@ -47,7 +47,7 @@ export default class SystemService {
|
|||||||
@Inject('logger') private logger: winston.Logger,
|
@Inject('logger') private logger: winston.Logger,
|
||||||
private scheduleService: ScheduleService,
|
private scheduleService: ScheduleService,
|
||||||
private sockService: SockService,
|
private sockService: SockService,
|
||||||
) {}
|
) { }
|
||||||
|
|
||||||
public async getSystemConfig() {
|
public async getSystemConfig() {
|
||||||
const doc = await this.getDb({ type: AuthDataType.systemConfig });
|
const doc = await this.getDb({ type: AuthDataType.systemConfig });
|
||||||
@@ -287,7 +287,7 @@ export default class SystemService {
|
|||||||
);
|
);
|
||||||
const text = await body.text();
|
const text = await body.text();
|
||||||
lastVersionContent = parseContentVersion(text);
|
lastVersionContent = parseContentVersion(text);
|
||||||
} catch (error) {}
|
} catch (error) { }
|
||||||
|
|
||||||
if (!lastVersionContent) {
|
if (!lastVersionContent) {
|
||||||
lastVersionContent = currentVersionContent;
|
lastVersionContent = currentVersionContent;
|
||||||
@@ -373,8 +373,27 @@ export default class SystemService {
|
|||||||
return { code: 200 };
|
return { code: 200 };
|
||||||
}
|
}
|
||||||
|
|
||||||
public async notify({ title, content }: { title: string; content: string }) {
|
public async notify({
|
||||||
const isSuccess = await this.notificationService.notify(title, content);
|
title,
|
||||||
|
content,
|
||||||
|
notificationInfo,
|
||||||
|
}: {
|
||||||
|
title: string;
|
||||||
|
content: string;
|
||||||
|
notificationInfo?: NotificationInfo;
|
||||||
|
}) {
|
||||||
|
const typeString =
|
||||||
|
typeof notificationInfo?.type === 'number'
|
||||||
|
? NotificationModeStringMap[notificationInfo.type]
|
||||||
|
: undefined;
|
||||||
|
if (notificationInfo && typeString) {
|
||||||
|
notificationInfo.type = typeString;
|
||||||
|
}
|
||||||
|
const isSuccess = await this.notificationService.notify(
|
||||||
|
title,
|
||||||
|
content,
|
||||||
|
notificationInfo,
|
||||||
|
);
|
||||||
if (isSuccess) {
|
if (isSuccess) {
|
||||||
return { code: 200, message: '通知发送成功' };
|
return { code: 200, message: '通知发送成功' };
|
||||||
} else {
|
} else {
|
||||||
@@ -382,11 +401,12 @@ export default class SystemService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async run({ command }: { command: string }, callback: TaskCallbacks) {
|
public async run({ command, logPath }: { command: string; logPath?: string }, callback: TaskCallbacks) {
|
||||||
if (!command.startsWith(TASK_COMMAND)) {
|
if (!command.startsWith(TASK_COMMAND)) {
|
||||||
command = `${TASK_COMMAND} ${command}`;
|
command = `${TASK_COMMAND} ${command}`;
|
||||||
}
|
}
|
||||||
this.scheduleService.runTask(`real_time=true ${command}`, callback, {
|
const logPathPrefix = logPath ? `real_log_path=${logPath}` : ''
|
||||||
|
this.scheduleService.runTask(`${logPathPrefix} real_time=true ${command}`, callback, {
|
||||||
command,
|
command,
|
||||||
id: command.replace(/ /g, '-'),
|
id: command.replace(/ /g, '-'),
|
||||||
runOrigin: 'system',
|
runOrigin: 'system',
|
||||||
@@ -415,10 +435,16 @@ export default class SystemService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async exportData(res: Response) {
|
public async exportData(res: Response, type?: string[]) {
|
||||||
try {
|
try {
|
||||||
|
let dataDirs = ['db', 'upload'];
|
||||||
|
if (type && type.length) {
|
||||||
|
dataDirs = dataDirs.concat(type.filter((x) => x !== 'base'));
|
||||||
|
}
|
||||||
|
const dataPaths = dataDirs.map((dir) => `data/${dir}`);
|
||||||
await promiseExec(
|
await promiseExec(
|
||||||
`cd ${config.dataPath} && cd ../ && tar -zcvf ${config.dataTgzFile} data/`,
|
`cd ${config.dataPath} && cd ../ && tar -zcvf ${config.dataTgzFile
|
||||||
|
} ${dataPaths.join(' ')}`,
|
||||||
);
|
);
|
||||||
res.download(config.dataTgzFile);
|
res.download(config.dataTgzFile);
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
@@ -503,4 +529,15 @@ export default class SystemService {
|
|||||||
return { code: 400, message: '设置时区失败' };
|
return { code: 400, message: '设置时区失败' };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async cleanDependence(type: 'node' | 'python3') {
|
||||||
|
if (!type || !['node', 'python3'].includes(type)) {
|
||||||
|
return { code: 400, message: '参数错误' };
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const finalPath = path.join(config.dependenceCachePath, type);
|
||||||
|
await fs.promises.rm(finalPath, { recursive: true });
|
||||||
|
} catch (error) { }
|
||||||
|
return { code: 200 };
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+51
-16
@@ -24,12 +24,17 @@ import uniq from 'lodash/uniq';
|
|||||||
import pickBy from 'lodash/pickBy';
|
import pickBy from 'lodash/pickBy';
|
||||||
import isNil from 'lodash/isNil';
|
import isNil from 'lodash/isNil';
|
||||||
import { shareStore } from '../shared/store';
|
import { shareStore } from '../shared/store';
|
||||||
|
import UserManagementService from './userManagement';
|
||||||
|
import { UserRole } from '../data/user';
|
||||||
|
|
||||||
@Service()
|
@Service()
|
||||||
export default class UserService {
|
export default class UserService {
|
||||||
@Inject((type) => NotificationService)
|
@Inject((type) => NotificationService)
|
||||||
private notificationService!: NotificationService;
|
private notificationService!: NotificationService;
|
||||||
|
|
||||||
|
@Inject((type) => UserManagementService)
|
||||||
|
private userManagementService!: UserManagementService;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
@Inject('logger') private logger: winston.Logger,
|
@Inject('logger') private logger: winston.Logger,
|
||||||
private scheduleService: ScheduleService,
|
private scheduleService: ScheduleService,
|
||||||
@@ -93,27 +98,57 @@ export default class UserService {
|
|||||||
const { country, province, city, isp } = ipAddress;
|
const { country, province, city, isp } = ipAddress;
|
||||||
address = uniq([country, province, city, isp]).filter(Boolean).join(' ');
|
address = uniq([country, province, city, isp]).filter(Boolean).join(' ');
|
||||||
}
|
}
|
||||||
if (username === cUsername && password === cPassword) {
|
|
||||||
|
// Check if this is a regular user (not admin) trying to login
|
||||||
|
let authenticatedUser = null;
|
||||||
|
let userId: number | undefined = undefined;
|
||||||
|
let userRole = UserRole.admin;
|
||||||
|
|
||||||
|
// First check if it's the system admin
|
||||||
|
const isSystemAdmin = username === cUsername && password === cPassword;
|
||||||
|
|
||||||
|
if (!isSystemAdmin) {
|
||||||
|
// Try to authenticate as a regular user
|
||||||
|
try {
|
||||||
|
authenticatedUser = await this.userManagementService.authenticate(username, password);
|
||||||
|
if (authenticatedUser) {
|
||||||
|
userId = authenticatedUser.id;
|
||||||
|
userRole = authenticatedUser.role;
|
||||||
|
}
|
||||||
|
} catch (e: any) {
|
||||||
|
// User disabled or other error
|
||||||
|
return { code: 400, message: e.message };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isSystemAdmin || authenticatedUser) {
|
||||||
const data = createRandomString(50, 100);
|
const data = createRandomString(50, 100);
|
||||||
const expiration = twoFactorActivated ? '60d' : '20d';
|
const expiration = (isSystemAdmin && twoFactorActivated) ? '60d' : '20d';
|
||||||
let token = jwt.sign({ data }, config.jwt.secret, {
|
let token = jwt.sign(
|
||||||
|
{ data, userId, role: userRole },
|
||||||
|
config.jwt.secret,
|
||||||
|
{
|
||||||
expiresIn: config.jwt.expiresIn || expiration,
|
expiresIn: config.jwt.expiresIn || expiration,
|
||||||
algorithm: 'HS384',
|
algorithm: 'HS384',
|
||||||
});
|
});
|
||||||
|
|
||||||
await this.updateAuthInfo(content, {
|
// Only update authInfo for system admin
|
||||||
token,
|
if (isSystemAdmin) {
|
||||||
tokens: {
|
await this.updateAuthInfo(content, {
|
||||||
...tokens,
|
token,
|
||||||
[req.platform]: token,
|
tokens: {
|
||||||
},
|
...tokens,
|
||||||
lastlogon: timestamp,
|
[req.platform]: token,
|
||||||
retries: 0,
|
},
|
||||||
lastip: ip,
|
lastlogon: timestamp,
|
||||||
lastaddr: address,
|
retries: 0,
|
||||||
platform: req.platform,
|
lastip: ip,
|
||||||
isTwoFactorChecking: false,
|
lastaddr: address,
|
||||||
});
|
platform: req.platform,
|
||||||
|
isTwoFactorChecking: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
this.notificationService.notify(
|
this.notificationService.notify(
|
||||||
'登录通知',
|
'登录通知',
|
||||||
`你于${dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss')}在 ${address} ${
|
`你于${dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss')}在 ${address} ${
|
||||||
|
|||||||
@@ -0,0 +1,125 @@
|
|||||||
|
import { Service, Inject } from 'typedi';
|
||||||
|
import winston from 'winston';
|
||||||
|
import { User, UserModel, UserRole, UserStatus } from '../data/user';
|
||||||
|
import { Op } from 'sequelize';
|
||||||
|
import bcrypt from 'bcrypt';
|
||||||
|
|
||||||
|
@Service()
|
||||||
|
export default class UserManagementService {
|
||||||
|
constructor(@Inject('logger') private logger: winston.Logger) {}
|
||||||
|
|
||||||
|
private async hashPassword(password: string): Promise<string> {
|
||||||
|
const saltRounds = 10;
|
||||||
|
return bcrypt.hash(password, saltRounds);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async verifyPassword(password: string, hash: string): Promise<boolean> {
|
||||||
|
return bcrypt.compare(password, hash);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async list(searchText?: string): Promise<User[]> {
|
||||||
|
let query: any = {};
|
||||||
|
if (searchText) {
|
||||||
|
query = {
|
||||||
|
username: { [Op.like]: `%${searchText}%` },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const docs = await UserModel.findAll({ where: query });
|
||||||
|
return docs.map((x) => x.get({ plain: true }));
|
||||||
|
}
|
||||||
|
|
||||||
|
public async get(id: number): Promise<User> {
|
||||||
|
const doc = await UserModel.findByPk(id);
|
||||||
|
if (!doc) {
|
||||||
|
throw new Error('用户不存在');
|
||||||
|
}
|
||||||
|
return doc.get({ plain: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
public async getByUsername(username: string): Promise<User | null> {
|
||||||
|
const doc = await UserModel.findOne({ where: { username } });
|
||||||
|
if (!doc) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return doc.get({ plain: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
public async create(payload: User): Promise<User> {
|
||||||
|
const existingUser = await this.getByUsername(payload.username);
|
||||||
|
if (existingUser) {
|
||||||
|
throw new Error('用户名已存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (payload.password.length < 6) {
|
||||||
|
throw new Error('密码长度至少为6位');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hash the password before storing
|
||||||
|
const hashedPassword = await this.hashPassword(payload.password);
|
||||||
|
const userWithHashedPassword = { ...payload, password: hashedPassword };
|
||||||
|
|
||||||
|
const doc = await UserModel.create(userWithHashedPassword);
|
||||||
|
return doc.get({ plain: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
public async update(payload: User): Promise<User> {
|
||||||
|
if (!payload.id) {
|
||||||
|
throw new Error('缺少用户ID');
|
||||||
|
}
|
||||||
|
|
||||||
|
const existingUser = await this.get(payload.id);
|
||||||
|
if (!existingUser) {
|
||||||
|
throw new Error('用户不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (payload.password && payload.password.length < 6) {
|
||||||
|
throw new Error('密码长度至少为6位');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if username is being changed and if new username already exists
|
||||||
|
if (payload.username !== existingUser.username) {
|
||||||
|
const userWithSameUsername = await this.getByUsername(payload.username);
|
||||||
|
if (userWithSameUsername && userWithSameUsername.id !== payload.id) {
|
||||||
|
throw new Error('用户名已存在');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hash the password if it's being updated
|
||||||
|
const updatePayload = { ...payload };
|
||||||
|
if (payload.password) {
|
||||||
|
updatePayload.password = await this.hashPassword(payload.password);
|
||||||
|
}
|
||||||
|
|
||||||
|
const [, [updated]] = await UserModel.update(updatePayload, {
|
||||||
|
where: { id: payload.id },
|
||||||
|
returning: true,
|
||||||
|
});
|
||||||
|
return updated.get({ plain: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
public async delete(ids: number[]): Promise<number> {
|
||||||
|
const count = await UserModel.destroy({ where: { id: ids } });
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async authenticate(
|
||||||
|
username: string,
|
||||||
|
password: string,
|
||||||
|
): Promise<User | null> {
|
||||||
|
const user = await this.getByUsername(username);
|
||||||
|
if (!user) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const isPasswordValid = await this.verifyPassword(password, user.password);
|
||||||
|
if (!isPasswordValid) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (user.status === UserStatus.disabled) {
|
||||||
|
throw new Error('用户已被禁用');
|
||||||
|
}
|
||||||
|
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -13,7 +13,7 @@ function getUniqueLockPath(filePath: string) {
|
|||||||
|
|
||||||
export async function writeFileWithLock(
|
export async function writeFileWithLock(
|
||||||
filePath: string,
|
filePath: string,
|
||||||
content: string | Buffer,
|
content: string,
|
||||||
options: Parameters<typeof writeFile>[2] = {},
|
options: Parameters<typeof writeFile>[2] = {},
|
||||||
) {
|
) {
|
||||||
if (typeof options === 'string') {
|
if (typeof options === 'string') {
|
||||||
|
|||||||
Vendored
+5
@@ -6,6 +6,11 @@ declare global {
|
|||||||
namespace Express {
|
namespace Express {
|
||||||
interface Request {
|
interface Request {
|
||||||
platform: 'desktop' | 'mobile';
|
platform: 'desktop' | 'mobile';
|
||||||
|
user?: {
|
||||||
|
userId?: number;
|
||||||
|
role?: number;
|
||||||
|
};
|
||||||
|
auth?: any;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
import { Joi } from 'celebrate';
|
import { Joi } from 'celebrate';
|
||||||
import cron_parser from 'cron-parser';
|
import cron_parser from 'cron-parser';
|
||||||
import { ScheduleType } from '../interface/schedule';
|
import { ScheduleType } from '../interface/schedule';
|
||||||
|
import path from 'path';
|
||||||
|
import config from '../config';
|
||||||
|
|
||||||
const validateSchedule = (value: string, helpers: any) => {
|
const validateSchedule = (value: string, helpers: any) => {
|
||||||
if (
|
if (
|
||||||
@@ -37,4 +39,42 @@ export const commonCronSchema = {
|
|||||||
extra_schedules: Joi.array().optional().allow(null),
|
extra_schedules: Joi.array().optional().allow(null),
|
||||||
task_before: Joi.string().optional().allow('').allow(null),
|
task_before: Joi.string().optional().allow('').allow(null),
|
||||||
task_after: Joi.string().optional().allow('').allow(null),
|
task_after: Joi.string().optional().allow('').allow(null),
|
||||||
|
log_name: Joi.string()
|
||||||
|
.optional()
|
||||||
|
.allow('')
|
||||||
|
.allow(null)
|
||||||
|
.custom((value, helpers) => {
|
||||||
|
if (!value) return value;
|
||||||
|
|
||||||
|
// Check if it's an absolute path
|
||||||
|
if (value.startsWith('/')) {
|
||||||
|
// Allow /dev/null as special case
|
||||||
|
if (value === '/dev/null') {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
// For other absolute paths, ensure they are within the safe log directory
|
||||||
|
const normalizedValue = path.normalize(value);
|
||||||
|
const normalizedLogPath = path.normalize(config.logPath);
|
||||||
|
|
||||||
|
if (!normalizedValue.startsWith(normalizedLogPath)) {
|
||||||
|
return helpers.error('string.unsafePath');
|
||||||
|
}
|
||||||
|
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!/^(?!.*(?:^|\/)\.{1,2}(?:\/|$))(?:\/)?(?:[\w.-]+\/)*[\w.-]+\/?$/.test(value)) {
|
||||||
|
return helpers.error('string.pattern.base');
|
||||||
|
}
|
||||||
|
if (value.length > 100) {
|
||||||
|
return helpers.error('string.max');
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
})
|
||||||
|
.messages({
|
||||||
|
'string.pattern.base': '日志名称只能包含字母、数字、下划线和连字符',
|
||||||
|
'string.max': '日志名称不能超过100个字符',
|
||||||
|
'string.unsafePath': '绝对路径必须在日志目录内或使用 /dev/null',
|
||||||
|
}),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -39,7 +39,6 @@ RUN set -x \
|
|||||||
tzdata \
|
tzdata \
|
||||||
perl \
|
perl \
|
||||||
openssl \
|
openssl \
|
||||||
nginx \
|
|
||||||
nodejs \
|
nodejs \
|
||||||
jq \
|
jq \
|
||||||
openssh \
|
openssh \
|
||||||
@@ -84,6 +83,6 @@ COPY --from=builder /tmp/build/node_modules/. /ql/node_modules/
|
|||||||
WORKDIR ${QL_DIR}
|
WORKDIR ${QL_DIR}
|
||||||
|
|
||||||
HEALTHCHECK --interval=5s --timeout=2s --retries=20 \
|
HEALTHCHECK --interval=5s --timeout=2s --retries=20 \
|
||||||
CMD curl -sf --noproxy '*' http://127.0.0.1:5600/api/health || exit 1
|
CMD curl -sf --noproxy '*' http://127.0.0.1:5700/api/health || exit 1
|
||||||
|
|
||||||
ENTRYPOINT ["./docker/docker-entrypoint.sh"]
|
ENTRYPOINT ["./docker/docker-entrypoint.sh"]
|
||||||
|
|||||||
+1
-2
@@ -39,7 +39,6 @@ RUN set -x \
|
|||||||
tzdata \
|
tzdata \
|
||||||
perl \
|
perl \
|
||||||
openssl \
|
openssl \
|
||||||
nginx \
|
|
||||||
nodejs \
|
nodejs \
|
||||||
jq \
|
jq \
|
||||||
openssh \
|
openssh \
|
||||||
@@ -84,6 +83,6 @@ COPY --from=builder /tmp/build/node_modules/. /ql/node_modules/
|
|||||||
WORKDIR ${QL_DIR}
|
WORKDIR ${QL_DIR}
|
||||||
|
|
||||||
HEALTHCHECK --interval=5s --timeout=2s --retries=20 \
|
HEALTHCHECK --interval=5s --timeout=2s --retries=20 \
|
||||||
CMD curl -sf --noproxy '*' http://127.0.0.1:5600/api/health || exit 1
|
CMD curl -sf --noproxy '*' http://127.0.0.1:5700/api/health || exit 1
|
||||||
|
|
||||||
ENTRYPOINT ["./docker/docker-entrypoint.sh"]
|
ENTRYPOINT ["./docker/docker-entrypoint.sh"]
|
||||||
|
|||||||
@@ -14,26 +14,20 @@ log_with_style() {
|
|||||||
|
|
||||||
log_with_style "INFO" "🚀 1. 检测配置文件..."
|
log_with_style "INFO" "🚀 1. 检测配置文件..."
|
||||||
import_config "$@"
|
import_config "$@"
|
||||||
make_dir /etc/nginx/conf.d
|
|
||||||
make_dir /run/nginx
|
|
||||||
init_nginx
|
|
||||||
fix_config
|
fix_config
|
||||||
|
|
||||||
pm2 l &>/dev/null
|
pm2 l &>/dev/null
|
||||||
|
|
||||||
log_with_style "INFO" "🔄 2. 启动 nginx..."
|
log_with_style "INFO" "⚙️ 2. 启动 pm2 服务..."
|
||||||
nginx -s reload 2>/dev/null || nginx -c /etc/nginx/nginx.conf
|
|
||||||
|
|
||||||
log_with_style "INFO" "⚙️ 3. 启动 pm2 服务..."
|
|
||||||
reload_pm2
|
reload_pm2
|
||||||
|
|
||||||
if [[ $AutoStartBot == true ]]; then
|
if [[ $AutoStartBot == true ]]; then
|
||||||
log_with_style "INFO" "🤖 4. 启动 bot..."
|
log_with_style "INFO" "🤖 3. 启动 bot..."
|
||||||
nohup ql bot >$dir_log/bot.log 2>&1 &
|
nohup ql bot >$dir_log/bot.log 2>&1 &
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if [[ $EnableExtraShell == true ]]; then
|
if [[ $EnableExtraShell == true ]]; then
|
||||||
log_with_style "INFO" "🛠️ 5. 执行自定义脚本..."
|
log_with_style "INFO" "🛠️ 4. 执行自定义脚本..."
|
||||||
nohup ql extra >$dir_log/extra.log 2>&1 &
|
nohup ql extra >$dir_log/extra.log 2>&1 &
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
|||||||
@@ -1,61 +0,0 @@
|
|||||||
upstream baseApi {
|
|
||||||
server 0.0.0.0:5600;
|
|
||||||
}
|
|
||||||
|
|
||||||
map $http_upgrade $connection_upgrade {
|
|
||||||
default keep-alive;
|
|
||||||
'websocket' upgrade;
|
|
||||||
}
|
|
||||||
|
|
||||||
server {
|
|
||||||
IPV4_CONFIG
|
|
||||||
IPV6_CONFIG
|
|
||||||
ssl_session_timeout 5m;
|
|
||||||
|
|
||||||
location QL_BASE_URLapi/ {
|
|
||||||
proxy_set_header Host $http_host;
|
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
|
||||||
proxy_pass http://baseApi/api/;
|
|
||||||
proxy_buffering off;
|
|
||||||
proxy_redirect default;
|
|
||||||
proxy_connect_timeout 1800;
|
|
||||||
proxy_send_timeout 1800;
|
|
||||||
proxy_read_timeout 1800;
|
|
||||||
|
|
||||||
proxy_set_header Upgrade $http_upgrade;
|
|
||||||
proxy_set_header Connection $connection_upgrade;
|
|
||||||
}
|
|
||||||
|
|
||||||
location QL_BASE_URLopen/ {
|
|
||||||
proxy_set_header Host $http_host;
|
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
|
||||||
proxy_pass http://baseApi/open/;
|
|
||||||
proxy_buffering off;
|
|
||||||
proxy_redirect default;
|
|
||||||
proxy_connect_timeout 1800;
|
|
||||||
proxy_send_timeout 1800;
|
|
||||||
proxy_read_timeout 1800;
|
|
||||||
}
|
|
||||||
|
|
||||||
gzip on;
|
|
||||||
gzip_static on;
|
|
||||||
gzip_types text/plain application/json application/javascript application/x-javascript text/css application/xml text/javascript;
|
|
||||||
gzip_proxied any;
|
|
||||||
gzip_vary on;
|
|
||||||
gzip_comp_level 6;
|
|
||||||
gzip_buffers 16 8k;
|
|
||||||
gzip_http_version 1.0;
|
|
||||||
QL_ROOT_CONFIG
|
|
||||||
|
|
||||||
location QL_BASE_URL_LOCATION {
|
|
||||||
QL_ALIAS_CONFIG
|
|
||||||
index index.html index.htm;
|
|
||||||
try_files $uri QL_BASE_URLindex.html;
|
|
||||||
}
|
|
||||||
|
|
||||||
location ~ .*\.(html)$ {
|
|
||||||
add_header Cache-Control no-cache;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
user root;
|
|
||||||
worker_processes auto;
|
|
||||||
pcre_jit on;
|
|
||||||
error_log /var/log/nginx/error.log warn;
|
|
||||||
include /etc/nginx/modules/*.conf;
|
|
||||||
|
|
||||||
events {
|
|
||||||
worker_connections 1024;
|
|
||||||
}
|
|
||||||
|
|
||||||
http {
|
|
||||||
include /etc/nginx/mime.types;
|
|
||||||
default_type application/octet-stream;
|
|
||||||
|
|
||||||
server_tokens off;
|
|
||||||
|
|
||||||
client_max_body_size 4096m;
|
|
||||||
client_body_buffer_size 20m;
|
|
||||||
|
|
||||||
keepalive_timeout 65;
|
|
||||||
|
|
||||||
sendfile on;
|
|
||||||
|
|
||||||
tcp_nodelay on;
|
|
||||||
|
|
||||||
ssl_prefer_server_ciphers on;
|
|
||||||
|
|
||||||
ssl_session_cache shared:SSL:2m;
|
|
||||||
|
|
||||||
gzip on;
|
|
||||||
gzip_static on;
|
|
||||||
gzip_types text/plain application/json application/javascript application/x-javascript text/css application/xml text/javascript;
|
|
||||||
gzip_proxied any;
|
|
||||||
gzip_vary on;
|
|
||||||
gzip_comp_level 6;
|
|
||||||
gzip_buffers 16 8k;
|
|
||||||
gzip_http_version 1.0;
|
|
||||||
|
|
||||||
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
|
|
||||||
'$status $body_bytes_sent "$http_referer" '
|
|
||||||
'"$http_user_agent" "$http_x_forwarded_for"';
|
|
||||||
|
|
||||||
access_log /var/log/nginx/access.log main;
|
|
||||||
include /etc/nginx/conf.d/*.conf;
|
|
||||||
}
|
|
||||||
Executable
+317
@@ -0,0 +1,317 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Multi-User Data Migration Script
|
||||||
|
*
|
||||||
|
* This script migrates existing data (Cron, Env, Subscription, Dependence)
|
||||||
|
* to be associated with specific users.
|
||||||
|
*
|
||||||
|
* Usage:
|
||||||
|
* node migrate-to-multiuser.js --userId=1
|
||||||
|
* node migrate-to-multiuser.js --username=admin
|
||||||
|
* node migrate-to-multiuser.js --list-users
|
||||||
|
*
|
||||||
|
* Options:
|
||||||
|
* --userId=<id> Assign all legacy data to user with this ID
|
||||||
|
* --username=<name> Assign all legacy data to user with this username
|
||||||
|
* --list-users List all users in the system
|
||||||
|
* --dry-run Show what would be changed without making changes
|
||||||
|
* --help Show this help message
|
||||||
|
*/
|
||||||
|
|
||||||
|
const path = require('path');
|
||||||
|
const fs = require('fs');
|
||||||
|
const Sequelize = require('sequelize');
|
||||||
|
|
||||||
|
// Load environment variables
|
||||||
|
require('dotenv').config();
|
||||||
|
|
||||||
|
// Configuration
|
||||||
|
const config = {
|
||||||
|
dbPath: process.env.QL_DATA_DIR || path.join(__dirname, '../data'),
|
||||||
|
rootPath: __dirname,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Initialize Sequelize
|
||||||
|
const sequelize = new Sequelize({
|
||||||
|
dialect: 'sqlite',
|
||||||
|
storage: path.join(config.dbPath, 'database.sqlite'),
|
||||||
|
logging: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Define models
|
||||||
|
const UserModel = sequelize.define('User', {
|
||||||
|
username: Sequelize.STRING,
|
||||||
|
password: Sequelize.STRING,
|
||||||
|
role: Sequelize.NUMBER,
|
||||||
|
status: Sequelize.NUMBER,
|
||||||
|
});
|
||||||
|
|
||||||
|
const CrontabModel = sequelize.define('Crontab', {
|
||||||
|
name: Sequelize.STRING,
|
||||||
|
command: Sequelize.STRING,
|
||||||
|
schedule: Sequelize.STRING,
|
||||||
|
userId: Sequelize.NUMBER,
|
||||||
|
});
|
||||||
|
|
||||||
|
const EnvModel = sequelize.define('Env', {
|
||||||
|
name: Sequelize.STRING,
|
||||||
|
value: Sequelize.STRING,
|
||||||
|
userId: Sequelize.NUMBER,
|
||||||
|
});
|
||||||
|
|
||||||
|
const SubscriptionModel = sequelize.define('Subscription', {
|
||||||
|
name: Sequelize.STRING,
|
||||||
|
url: Sequelize.STRING,
|
||||||
|
userId: Sequelize.NUMBER,
|
||||||
|
});
|
||||||
|
|
||||||
|
const DependenceModel = sequelize.define('Dependence', {
|
||||||
|
name: Sequelize.STRING,
|
||||||
|
type: Sequelize.NUMBER,
|
||||||
|
userId: Sequelize.NUMBER,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Parse command line arguments
|
||||||
|
function parseArgs() {
|
||||||
|
const args = {
|
||||||
|
userId: null,
|
||||||
|
username: null,
|
||||||
|
listUsers: false,
|
||||||
|
dryRun: false,
|
||||||
|
help: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
process.argv.slice(2).forEach(arg => {
|
||||||
|
if (arg.startsWith('--userId=')) {
|
||||||
|
args.userId = parseInt(arg.split('=')[1]);
|
||||||
|
} else if (arg.startsWith('--username=')) {
|
||||||
|
args.username = arg.split('=')[1];
|
||||||
|
} else if (arg === '--list-users') {
|
||||||
|
args.listUsers = true;
|
||||||
|
} else if (arg === '--dry-run') {
|
||||||
|
args.dryRun = true;
|
||||||
|
} else if (arg === '--help' || arg === '-h') {
|
||||||
|
args.help = true;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return args;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Show help
|
||||||
|
function showHelp() {
|
||||||
|
console.log(`
|
||||||
|
Multi-User Data Migration Script
|
||||||
|
|
||||||
|
This script migrates existing data (Cron, Env, Subscription, Dependence)
|
||||||
|
to be associated with specific users.
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
node migrate-to-multiuser.js --userId=1
|
||||||
|
node migrate-to-multiuser.js --username=admin
|
||||||
|
node migrate-to-multiuser.js --list-users
|
||||||
|
|
||||||
|
Options:
|
||||||
|
--userId=<id> Assign all legacy data to user with this ID
|
||||||
|
--username=<name> Assign all legacy data to user with this username
|
||||||
|
--list-users List all users in the system
|
||||||
|
--dry-run Show what would be changed without making changes
|
||||||
|
--help Show this help message
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
# List all users
|
||||||
|
node migrate-to-multiuser.js --list-users
|
||||||
|
|
||||||
|
# Migrate all data to user ID 1 (dry run)
|
||||||
|
node migrate-to-multiuser.js --userId=1 --dry-run
|
||||||
|
|
||||||
|
# Migrate all data to user 'admin'
|
||||||
|
node migrate-to-multiuser.js --username=admin
|
||||||
|
|
||||||
|
Note: This script will only migrate data where userId is NULL or undefined.
|
||||||
|
Data already assigned to users will not be changed.
|
||||||
|
`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// List all users
|
||||||
|
async function listUsers() {
|
||||||
|
const users = await UserModel.findAll();
|
||||||
|
|
||||||
|
if (users.length === 0) {
|
||||||
|
console.log('\nNo users found in the database.');
|
||||||
|
console.log('Please create users first using the User Management interface.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('\nUsers in the system:');
|
||||||
|
console.log('ID\tUsername\tRole\t\tStatus');
|
||||||
|
console.log('--\t--------\t----\t\t------');
|
||||||
|
|
||||||
|
users.forEach(user => {
|
||||||
|
const role = user.role === 0 ? 'Admin' : 'User';
|
||||||
|
const status = user.status === 0 ? 'Enabled' : 'Disabled';
|
||||||
|
console.log(`${user.id}\t${user.username}\t\t${role}\t\t${status}`);
|
||||||
|
});
|
||||||
|
console.log('');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get statistics of legacy data
|
||||||
|
async function getStatistics() {
|
||||||
|
const stats = {
|
||||||
|
crons: await CrontabModel.count({ where: { userId: null } }),
|
||||||
|
envs: await EnvModel.count({ where: { userId: null } }),
|
||||||
|
subscriptions: await SubscriptionModel.count({ where: { userId: null } }),
|
||||||
|
dependences: await DependenceModel.count({ where: { userId: null } }),
|
||||||
|
};
|
||||||
|
|
||||||
|
return stats;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Migrate data to a specific user
|
||||||
|
async function migrateData(userId, dryRun = false) {
|
||||||
|
const stats = await getStatistics();
|
||||||
|
|
||||||
|
console.log('\nLegacy Data Statistics:');
|
||||||
|
console.log(` Cron tasks: ${stats.crons}`);
|
||||||
|
console.log(` Environment variables: ${stats.envs}`);
|
||||||
|
console.log(` Subscriptions: ${stats.subscriptions}`);
|
||||||
|
console.log(` Dependencies: ${stats.dependences}`);
|
||||||
|
console.log('');
|
||||||
|
|
||||||
|
if (stats.crons + stats.envs + stats.subscriptions + stats.dependences === 0) {
|
||||||
|
console.log('No legacy data found. All data is already assigned to users.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (dryRun) {
|
||||||
|
console.log('DRY RUN: No changes will be made.\n');
|
||||||
|
console.log(`Would assign all legacy data to user ID ${userId}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`Migrating data to user ID ${userId}...`);
|
||||||
|
|
||||||
|
const transaction = await sequelize.transaction();
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Migrate crons
|
||||||
|
if (stats.crons > 0) {
|
||||||
|
await CrontabModel.update(
|
||||||
|
{ userId },
|
||||||
|
{ where: { userId: null }, transaction }
|
||||||
|
);
|
||||||
|
console.log(`✓ Migrated ${stats.crons} cron tasks`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Migrate envs
|
||||||
|
if (stats.envs > 0) {
|
||||||
|
await EnvModel.update(
|
||||||
|
{ userId },
|
||||||
|
{ where: { userId: null }, transaction }
|
||||||
|
);
|
||||||
|
console.log(`✓ Migrated ${stats.envs} environment variables`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Migrate subscriptions
|
||||||
|
if (stats.subscriptions > 0) {
|
||||||
|
await SubscriptionModel.update(
|
||||||
|
{ userId },
|
||||||
|
{ where: { userId: null }, transaction }
|
||||||
|
);
|
||||||
|
console.log(`✓ Migrated ${stats.subscriptions} subscriptions`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Migrate dependences
|
||||||
|
if (stats.dependences > 0) {
|
||||||
|
await DependenceModel.update(
|
||||||
|
{ userId },
|
||||||
|
{ where: { userId: null }, transaction }
|
||||||
|
);
|
||||||
|
console.log(`✓ Migrated ${stats.dependences} dependencies`);
|
||||||
|
}
|
||||||
|
|
||||||
|
await transaction.commit();
|
||||||
|
console.log('\n✓ Migration completed successfully!');
|
||||||
|
} catch (error) {
|
||||||
|
await transaction.rollback();
|
||||||
|
console.error('\n✗ Migration failed:', error.message);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Main function
|
||||||
|
async function main() {
|
||||||
|
const args = parseArgs();
|
||||||
|
|
||||||
|
if (args.help) {
|
||||||
|
showHelp();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Test database connection
|
||||||
|
await sequelize.authenticate();
|
||||||
|
console.log('Database connection established.');
|
||||||
|
|
||||||
|
if (args.listUsers) {
|
||||||
|
await listUsers();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate arguments
|
||||||
|
if (!args.userId && !args.username) {
|
||||||
|
console.error('\nError: You must specify either --userId or --username');
|
||||||
|
console.log('Use --help for usage information.');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get user ID
|
||||||
|
let userId = args.userId;
|
||||||
|
|
||||||
|
if (args.username) {
|
||||||
|
const user = await UserModel.findOne({
|
||||||
|
where: { username: args.username }
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
console.error(`\nError: User '${args.username}' not found.`);
|
||||||
|
console.log('Use --list-users to see available users.');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
userId = user.id;
|
||||||
|
console.log(`Found user '${args.username}' with ID ${userId}`);
|
||||||
|
} else {
|
||||||
|
// Verify user exists
|
||||||
|
const user = await UserModel.findByPk(userId);
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
console.error(`\nError: User with ID ${userId} not found.`);
|
||||||
|
console.log('Use --list-users to see available users.');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`Found user '${user.username}' with ID ${userId}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Perform migration
|
||||||
|
await migrateData(userId, args.dryRun);
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('\nError:', error.message);
|
||||||
|
process.exit(1);
|
||||||
|
} finally {
|
||||||
|
await sequelize.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Run the script
|
||||||
|
if (require.main === module) {
|
||||||
|
main().catch(error => {
|
||||||
|
console.error('Fatal error:', error);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { main, listUsers, migrateData, getStatistics };
|
||||||
+13
-3
@@ -1,5 +1,15 @@
|
|||||||
{
|
{
|
||||||
"watch": ["back", ".env"],
|
"watch": [
|
||||||
|
"back",
|
||||||
|
".env"
|
||||||
|
],
|
||||||
"ext": "js,ts,json",
|
"ext": "js,ts,json",
|
||||||
"exec": "ts-node -P ./back/tsconfig.json ./back/app.ts"
|
"env": {
|
||||||
}
|
"NODE_ENV": "development",
|
||||||
|
"TS_NODE_PROJECT": "./back/tsconfig.json"
|
||||||
|
},
|
||||||
|
"verbose": true,
|
||||||
|
"execMap": {
|
||||||
|
"ts": "node --require ts-node/register"
|
||||||
|
}
|
||||||
|
}
|
||||||
+25
-25
@@ -2,13 +2,12 @@
|
|||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"start": "concurrently -n w: npm:start:*",
|
"start": "concurrently -n w: npm:start:*",
|
||||||
"start:back": "nodemon",
|
"start:back": "nodemon ./back/app.ts",
|
||||||
"start:front": "max dev",
|
"start:front": "max dev",
|
||||||
"build:front": "max build",
|
"build:front": "max build",
|
||||||
"build:back": "tsc -p back/tsconfig.json",
|
"build:back": "tsc -p back/tsconfig.json",
|
||||||
"panel": "npm run build:back && node static/build/app.js",
|
"panel": "npm run build:back && node static/build/app.js",
|
||||||
"gen:proto": "protoc --experimental_allow_proto3_optional --plugin=./node_modules/.bin/protoc-gen-ts_proto ./back/protos/*.proto --ts_proto_out=./ --ts_proto_opt=outputServices=grpc-js,env=node,esModuleInterop=true,snakeToCamel=false",
|
"gen:proto": "protoc --experimental_allow_proto3_optional --plugin=./node_modules/.bin/protoc-gen-ts_proto ./back/protos/*.proto --ts_proto_out=./ --ts_proto_opt=outputServices=grpc-js,env=node,esModuleInterop=true,snakeToCamel=false",
|
||||||
"gen:api": "python3 -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. ./back/protos/api.proto",
|
|
||||||
"prettier": "prettier --write '**/*.{js,jsx,tsx,ts,less,md,json}'",
|
"prettier": "prettier --write '**/*.{js,jsx,tsx,ts,less,md,json}'",
|
||||||
"postinstall": "max setup 2>/dev/null || true",
|
"postinstall": "max setup 2>/dev/null || true",
|
||||||
"test": "umi-test",
|
"test": "umi-test",
|
||||||
@@ -55,12 +54,16 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@grpc/grpc-js": "^1.12.3",
|
"@bufbuild/protobuf": "^2.10.0",
|
||||||
"@grpc/proto-loader": "^0.7.13",
|
"@grpc/grpc-js": "^1.14.0",
|
||||||
|
"@grpc/proto-loader": "^0.8.0",
|
||||||
|
"@keyv/sqlite": "^4.0.1",
|
||||||
"@otplib/preset-default": "^12.0.1",
|
"@otplib/preset-default": "^12.0.1",
|
||||||
|
"bcrypt": "^6.0.0",
|
||||||
"body-parser": "^1.20.3",
|
"body-parser": "^1.20.3",
|
||||||
"celebrate": "^15.0.3",
|
"celebrate": "^15.0.3",
|
||||||
"chokidar": "^4.0.1",
|
"chokidar": "^4.0.1",
|
||||||
|
"compression": "^1.7.4",
|
||||||
"cors": "^2.8.5",
|
"cors": "^2.8.5",
|
||||||
"cron-parser": "^4.9.0",
|
"cron-parser": "^4.9.0",
|
||||||
"cross-spawn": "^7.0.6",
|
"cross-spawn": "^7.0.6",
|
||||||
@@ -70,52 +73,49 @@
|
|||||||
"express-jwt": "^8.4.1",
|
"express-jwt": "^8.4.1",
|
||||||
"express-rate-limit": "^7.4.1",
|
"express-rate-limit": "^7.4.1",
|
||||||
"express-urlrewrite": "^2.0.3",
|
"express-urlrewrite": "^2.0.3",
|
||||||
"undici": "^7.9.0",
|
"helmet": "^8.1.0",
|
||||||
"hpagent": "^1.2.0",
|
"hpagent": "^1.2.0",
|
||||||
"http-proxy-middleware": "^3.0.3",
|
"http-proxy-middleware": "^3.0.3",
|
||||||
"iconv-lite": "^0.6.3",
|
"iconv-lite": "^0.6.3",
|
||||||
|
"ip2region": "2.3.0",
|
||||||
"js-yaml": "^4.1.0",
|
"js-yaml": "^4.1.0",
|
||||||
"jsonwebtoken": "^9.0.2",
|
"jsonwebtoken": "^9.0.2",
|
||||||
|
"keyv": "^5.2.3",
|
||||||
"lodash": "^4.17.21",
|
"lodash": "^4.17.21",
|
||||||
"multer": "1.4.5-lts.1",
|
"multer": "1.4.5-lts.1",
|
||||||
"node-schedule": "^2.1.0",
|
"node-schedule": "^2.1.0",
|
||||||
"nodemailer": "^6.9.16",
|
"nodemailer": "^6.9.16",
|
||||||
"p-queue-cjs": "7.3.4",
|
"p-queue-cjs": "7.3.4",
|
||||||
"@bufbuild/protobuf": "^2.2.3",
|
"proper-lockfile": "^4.1.2",
|
||||||
"ps-tree": "^1.2.0",
|
"ps-tree": "^1.2.0",
|
||||||
"reflect-metadata": "^0.2.2",
|
"reflect-metadata": "^0.2.2",
|
||||||
|
"request-ip": "3.3.0",
|
||||||
"sequelize": "^6.37.5",
|
"sequelize": "^6.37.5",
|
||||||
"serve-handler": "^6.1.6",
|
|
||||||
"sockjs": "^0.3.24",
|
"sockjs": "^0.3.24",
|
||||||
"sqlite3": "git+https://github.com/whyour/node-sqlite3.git#v1.0.3",
|
"sqlite3": "git+https://github.com/whyour/node-sqlite3.git#v1.0.3",
|
||||||
"toad-scheduler": "^3.0.1",
|
"toad-scheduler": "^3.0.1",
|
||||||
"typedi": "^0.10.0",
|
"typedi": "^0.10.0",
|
||||||
|
"undici": "^7.9.0",
|
||||||
"uuid": "^11.0.3",
|
"uuid": "^11.0.3",
|
||||||
"winston": "^3.17.0",
|
"winston": "^3.17.0",
|
||||||
"winston-daily-rotate-file": "^5.0.0",
|
"winston-daily-rotate-file": "^5.0.0"
|
||||||
"request-ip": "3.3.0",
|
|
||||||
"ip2region": "2.3.0",
|
|
||||||
"keyv": "^5.2.3",
|
|
||||||
"@keyv/sqlite": "^4.0.1",
|
|
||||||
"proper-lockfile": "^4.1.2",
|
|
||||||
"compression": "^1.7.4",
|
|
||||||
"helmet": "^6.0.1"
|
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"moment": "2.30.1",
|
|
||||||
"@ant-design/icons": "^5.0.1",
|
"@ant-design/icons": "^5.0.1",
|
||||||
"@ant-design/pro-layout": "6.38.22",
|
"@ant-design/pro-layout": "6.38.22",
|
||||||
"@codemirror/view": "^6.34.1",
|
|
||||||
"@codemirror/state": "^6.4.1",
|
"@codemirror/state": "^6.4.1",
|
||||||
|
"@codemirror/view": "^6.34.1",
|
||||||
"@monaco-editor/react": "4.2.1",
|
"@monaco-editor/react": "4.2.1",
|
||||||
"@react-hook/resize-observer": "^2.0.2",
|
"@react-hook/resize-observer": "^2.0.2",
|
||||||
"react-router-dom": "6.26.1",
|
"@types/bcrypt": "^6.0.0",
|
||||||
"@types/body-parser": "^1.19.2",
|
"@types/body-parser": "^1.19.2",
|
||||||
|
"@types/compression": "^1.7.2",
|
||||||
"@types/cors": "^2.8.12",
|
"@types/cors": "^2.8.12",
|
||||||
"@types/cross-spawn": "^6.0.2",
|
"@types/cross-spawn": "^6.0.2",
|
||||||
"@types/express": "^4.17.13",
|
"@types/express": "^4.17.13",
|
||||||
"@types/express-jwt": "^6.0.4",
|
"@types/express-jwt": "^6.0.4",
|
||||||
"@types/file-saver": "2.0.2",
|
"@types/file-saver": "2.0.2",
|
||||||
|
"@types/helmet": "^4.0.0",
|
||||||
"@types/js-yaml": "^4.0.5",
|
"@types/js-yaml": "^4.0.5",
|
||||||
"@types/jsonwebtoken": "^8.5.8",
|
"@types/jsonwebtoken": "^8.5.8",
|
||||||
"@types/lodash": "^4.14.185",
|
"@types/lodash": "^4.14.185",
|
||||||
@@ -123,17 +123,17 @@
|
|||||||
"@types/node": "^17.0.21",
|
"@types/node": "^17.0.21",
|
||||||
"@types/node-schedule": "^1.3.2",
|
"@types/node-schedule": "^1.3.2",
|
||||||
"@types/nodemailer": "^6.4.4",
|
"@types/nodemailer": "^6.4.4",
|
||||||
|
"@types/proper-lockfile": "^4.1.4",
|
||||||
|
"@types/ps-tree": "^1.1.6",
|
||||||
"@types/qrcode.react": "^1.0.2",
|
"@types/qrcode.react": "^1.0.2",
|
||||||
"@types/react": "^18.0.20",
|
"@types/react": "^18.0.20",
|
||||||
"@types/react-copy-to-clipboard": "^5.0.4",
|
"@types/react-copy-to-clipboard": "^5.0.4",
|
||||||
"@types/react-dom": "^18.0.6",
|
"@types/react-dom": "^18.0.6",
|
||||||
|
"@types/request-ip": "0.0.41",
|
||||||
"@types/serve-handler": "^6.1.1",
|
"@types/serve-handler": "^6.1.1",
|
||||||
"@types/sockjs": "^0.3.33",
|
"@types/sockjs": "^0.3.33",
|
||||||
"@types/sockjs-client": "^1.5.1",
|
"@types/sockjs-client": "^1.5.1",
|
||||||
"@types/uuid": "^8.3.4",
|
"@types/uuid": "^8.3.4",
|
||||||
"@types/request-ip": "0.0.41",
|
|
||||||
"@types/proper-lockfile": "^4.1.4",
|
|
||||||
"@types/ps-tree": "^1.1.6",
|
|
||||||
"@uiw/codemirror-extensions-langs": "^4.21.9",
|
"@uiw/codemirror-extensions-langs": "^4.21.9",
|
||||||
"@uiw/react-codemirror": "^4.21.9",
|
"@uiw/react-codemirror": "^4.21.9",
|
||||||
"@umijs/max": "^4.4.4",
|
"@umijs/max": "^4.4.4",
|
||||||
@@ -145,9 +145,9 @@
|
|||||||
"axios": "^1.4.0",
|
"axios": "^1.4.0",
|
||||||
"compression-webpack-plugin": "9.2.0",
|
"compression-webpack-plugin": "9.2.0",
|
||||||
"concurrently": "^7.0.0",
|
"concurrently": "^7.0.0",
|
||||||
"react-hotkeys-hook": "^4.6.1",
|
|
||||||
"file-saver": "2.0.2",
|
"file-saver": "2.0.2",
|
||||||
"lint-staged": "^13.0.3",
|
"lint-staged": "^13.0.3",
|
||||||
|
"moment": "2.30.1",
|
||||||
"monaco-editor": "0.33.0",
|
"monaco-editor": "0.33.0",
|
||||||
"nodemon": "^3.0.1",
|
"nodemon": "^3.0.1",
|
||||||
"prettier": "^2.5.1",
|
"prettier": "^2.5.1",
|
||||||
@@ -163,7 +163,9 @@
|
|||||||
"react-dnd": "^16.0.1",
|
"react-dnd": "^16.0.1",
|
||||||
"react-dnd-html5-backend": "^16.0.1",
|
"react-dnd-html5-backend": "^16.0.1",
|
||||||
"react-dom": "18.3.1",
|
"react-dom": "18.3.1",
|
||||||
|
"react-hotkeys-hook": "^4.6.1",
|
||||||
"react-intl-universal": "^2.12.0",
|
"react-intl-universal": "^2.12.0",
|
||||||
|
"react-router-dom": "6.26.1",
|
||||||
"react-split-pane": "^0.1.92",
|
"react-split-pane": "^0.1.92",
|
||||||
"sockjs-client": "^1.6.0",
|
"sockjs-client": "^1.6.0",
|
||||||
"ts-node": "^10.9.2",
|
"ts-node": "^10.9.2",
|
||||||
@@ -171,8 +173,6 @@
|
|||||||
"tslib": "^2.4.0",
|
"tslib": "^2.4.0",
|
||||||
"typescript": "5.2.2",
|
"typescript": "5.2.2",
|
||||||
"vh-check": "^2.0.5",
|
"vh-check": "^2.0.5",
|
||||||
"virtualizedtableforantd4": "1.3.0",
|
"virtualizedtableforantd4": "1.3.0"
|
||||||
"@types/compression": "^1.7.2",
|
|
||||||
"@types/helmet": "^4.0.0"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Generated
+59
-78
@@ -1,28 +1,27 @@
|
|||||||
lockfileVersion: '6.0'
|
lockfileVersion: '6.0'
|
||||||
|
|
||||||
settings:
|
|
||||||
autoInstallPeers: true
|
|
||||||
excludeLinksFromLockfile: false
|
|
||||||
|
|
||||||
overrides:
|
overrides:
|
||||||
sqlite3: git+https://github.com/whyour/node-sqlite3.git#v1.0.3
|
sqlite3: git+https://github.com/whyour/node-sqlite3.git#v1.0.3
|
||||||
|
|
||||||
dependencies:
|
dependencies:
|
||||||
'@bufbuild/protobuf':
|
'@bufbuild/protobuf':
|
||||||
specifier: ^2.2.3
|
specifier: ^2.10.0
|
||||||
version: 2.2.3
|
version: 2.10.0
|
||||||
'@grpc/grpc-js':
|
'@grpc/grpc-js':
|
||||||
specifier: ^1.12.3
|
specifier: ^1.14.0
|
||||||
version: 1.12.3
|
version: 1.14.0
|
||||||
'@grpc/proto-loader':
|
'@grpc/proto-loader':
|
||||||
specifier: ^0.7.13
|
specifier: ^0.8.0
|
||||||
version: 0.7.13
|
version: 0.8.0
|
||||||
'@keyv/sqlite':
|
'@keyv/sqlite':
|
||||||
specifier: ^4.0.1
|
specifier: ^4.0.1
|
||||||
version: 4.0.1
|
version: 4.0.1
|
||||||
'@otplib/preset-default':
|
'@otplib/preset-default':
|
||||||
specifier: ^12.0.1
|
specifier: ^12.0.1
|
||||||
version: 12.0.1
|
version: 12.0.1
|
||||||
|
bcrypt:
|
||||||
|
specifier: ^6.0.0
|
||||||
|
version: 6.0.0
|
||||||
body-parser:
|
body-parser:
|
||||||
specifier: ^1.20.3
|
specifier: ^1.20.3
|
||||||
version: 1.20.3
|
version: 1.20.3
|
||||||
@@ -63,8 +62,8 @@ dependencies:
|
|||||||
specifier: ^2.0.3
|
specifier: ^2.0.3
|
||||||
version: 2.0.3
|
version: 2.0.3
|
||||||
helmet:
|
helmet:
|
||||||
specifier: ^6.0.1
|
specifier: ^8.1.0
|
||||||
version: 6.2.0
|
version: 8.1.0
|
||||||
hpagent:
|
hpagent:
|
||||||
specifier: ^1.2.0
|
specifier: ^1.2.0
|
||||||
version: 1.2.0
|
version: 1.2.0
|
||||||
@@ -116,9 +115,6 @@ dependencies:
|
|||||||
sequelize:
|
sequelize:
|
||||||
specifier: ^6.37.5
|
specifier: ^6.37.5
|
||||||
version: 6.37.5(@whyour/sqlite3@1.0.3)
|
version: 6.37.5(@whyour/sqlite3@1.0.3)
|
||||||
serve-handler:
|
|
||||||
specifier: ^6.1.6
|
|
||||||
version: 6.1.6
|
|
||||||
sockjs:
|
sockjs:
|
||||||
specifier: ^0.3.24
|
specifier: ^0.3.24
|
||||||
version: 0.3.24
|
version: 0.3.24
|
||||||
@@ -163,6 +159,9 @@ devDependencies:
|
|||||||
'@react-hook/resize-observer':
|
'@react-hook/resize-observer':
|
||||||
specifier: ^2.0.2
|
specifier: ^2.0.2
|
||||||
version: 2.0.2(react@18.3.1)
|
version: 2.0.2(react@18.3.1)
|
||||||
|
'@types/bcrypt':
|
||||||
|
specifier: ^6.0.0
|
||||||
|
version: 6.0.0
|
||||||
'@types/body-parser':
|
'@types/body-parser':
|
||||||
specifier: ^1.19.2
|
specifier: ^1.19.2
|
||||||
version: 1.19.5
|
version: 1.19.5
|
||||||
@@ -1389,8 +1388,8 @@ packages:
|
|||||||
resolution: {integrity: sha512-h0OYmPR3A5Dfbetra/GzxBAzQk8sH7LhRkRUTdagX6nrtlUgJGYCTv4bBK33jsTQw9HDd8PE2x1Ma+iRKEDUsw==}
|
resolution: {integrity: sha512-h0OYmPR3A5Dfbetra/GzxBAzQk8sH7LhRkRUTdagX6nrtlUgJGYCTv4bBK33jsTQw9HDd8PE2x1Ma+iRKEDUsw==}
|
||||||
dev: true
|
dev: true
|
||||||
|
|
||||||
/@bufbuild/protobuf@2.2.3:
|
/@bufbuild/protobuf@2.10.0:
|
||||||
resolution: {integrity: sha512-tFQoXHJdkEOSwj5tRIZSPNUuXK3RaR7T1nUrPgbYX1pUbvqqaaZAsfo+NXBPsz5rZMSKVFrgK1WL8Q/MSLvprg==}
|
resolution: {integrity: sha512-fdRs9PSrBF7QUntpZpq6BTw58fhgGJojgg39m9oFOJGZT+nip9b0so5cYY1oWl5pvemDLr0cPPsH46vwThEbpQ==}
|
||||||
|
|
||||||
/@chenshuai2144/sketch-color@1.0.9(react@18.3.1):
|
/@chenshuai2144/sketch-color@1.0.9(react@18.3.1):
|
||||||
resolution: {integrity: sha512-obzSy26cb7Pm7OprWyVpgMpIlrZpZ0B7vbrU0RMbvRg0YAI890S5Xy02Aj1Nhl4+KTbi1lVYHt6HQP8Hm9s+1w==}
|
resolution: {integrity: sha512-obzSy26cb7Pm7OprWyVpgMpIlrZpZ0B7vbrU0RMbvRg0YAI890S5Xy02Aj1Nhl4+KTbi1lVYHt6HQP8Hm9s+1w==}
|
||||||
@@ -2585,22 +2584,22 @@ packages:
|
|||||||
dev: false
|
dev: false
|
||||||
optional: true
|
optional: true
|
||||||
|
|
||||||
/@grpc/grpc-js@1.12.3:
|
/@grpc/grpc-js@1.14.0:
|
||||||
resolution: {integrity: sha512-iaxAZnANdCwMNpJlyhkI1W1jQZIDZKFNtU2OpQDdgd+pBcU3t7G+PT7svobkW4WSZTdis+CVV6y8KIwu83HDYQ==}
|
resolution: {integrity: sha512-N8Jx6PaYzcTRNzirReJCtADVoq4z7+1KQ4E70jTg/koQiMoUSN1kbNjPOqpPbhMFhfU1/l7ixspPl8dNY+FoUg==}
|
||||||
engines: {node: '>=12.10.0'}
|
engines: {node: '>=12.10.0'}
|
||||||
dependencies:
|
dependencies:
|
||||||
'@grpc/proto-loader': 0.7.13
|
'@grpc/proto-loader': 0.8.0
|
||||||
'@js-sdsl/ordered-map': 4.4.2
|
'@js-sdsl/ordered-map': 4.4.2
|
||||||
dev: false
|
dev: false
|
||||||
|
|
||||||
/@grpc/proto-loader@0.7.13:
|
/@grpc/proto-loader@0.8.0:
|
||||||
resolution: {integrity: sha512-AiXO/bfe9bmxBjxxtYxFAXGZvMaN5s8kO+jBHAJCON8rJoB5YS/D6X7ZNc6XQkuHNmyl4CYaMI1fJ/Gn27RGGw==}
|
resolution: {integrity: sha512-rc1hOQtjIWGxcxpb9aHAfLpIctjEnsDehj0DAiVfBlmT84uvR0uUtN2hEi/ecvWVjXUGf5qPF4qEgiLOx1YIMQ==}
|
||||||
engines: {node: '>=6'}
|
engines: {node: '>=6'}
|
||||||
hasBin: true
|
hasBin: true
|
||||||
dependencies:
|
dependencies:
|
||||||
lodash.camelcase: 4.3.0
|
lodash.camelcase: 4.3.0
|
||||||
long: 5.2.3
|
long: 5.2.3
|
||||||
protobufjs: 7.4.0
|
protobufjs: 7.5.4
|
||||||
yargs: 17.7.2
|
yargs: 17.7.2
|
||||||
dev: false
|
dev: false
|
||||||
|
|
||||||
@@ -3789,6 +3788,12 @@ packages:
|
|||||||
'@babel/types': 7.26.0
|
'@babel/types': 7.26.0
|
||||||
dev: true
|
dev: true
|
||||||
|
|
||||||
|
/@types/bcrypt@6.0.0:
|
||||||
|
resolution: {integrity: sha512-/oJGukuH3D2+D+3H4JWLaAsJ/ji86dhRidzZ/Od7H/i8g+aCmvkeCc6Ni/f9uxGLSQVCRZkX2/lqEFG2BvWtlQ==}
|
||||||
|
dependencies:
|
||||||
|
'@types/node': 17.0.45
|
||||||
|
dev: true
|
||||||
|
|
||||||
/@types/body-parser@1.19.5:
|
/@types/body-parser@1.19.5:
|
||||||
resolution: {integrity: sha512-fB3Zu92ucau0iQ0JMCFQE7b/dv8Ot07NI3KaZIkIUNXq82k4eBAqUaneXfleGY9JWskeS9y+u0nXMyspcuQrCg==}
|
resolution: {integrity: sha512-fB3Zu92ucau0iQ0JMCFQE7b/dv8Ot07NI3KaZIkIUNXq82k4eBAqUaneXfleGY9JWskeS9y+u0nXMyspcuQrCg==}
|
||||||
dependencies:
|
dependencies:
|
||||||
@@ -3876,7 +3881,7 @@ packages:
|
|||||||
resolution: {integrity: sha512-ONIn/nSNQA57yRge3oaMQESef/6QhoeX7llWeDli0UZIfz8TQMkfNPTXA8VnnyeA1WUjG2pGqdjEIueYonMdfQ==}
|
resolution: {integrity: sha512-ONIn/nSNQA57yRge3oaMQESef/6QhoeX7llWeDli0UZIfz8TQMkfNPTXA8VnnyeA1WUjG2pGqdjEIueYonMdfQ==}
|
||||||
deprecated: This is a stub types definition. helmet provides its own type definitions, so you do not need this installed.
|
deprecated: This is a stub types definition. helmet provides its own type definitions, so you do not need this installed.
|
||||||
dependencies:
|
dependencies:
|
||||||
helmet: 6.2.0
|
helmet: 8.1.0
|
||||||
dev: true
|
dev: true
|
||||||
|
|
||||||
/@types/hoist-non-react-statics@3.3.5:
|
/@types/hoist-non-react-statics@3.3.5:
|
||||||
@@ -5750,6 +5755,15 @@ packages:
|
|||||||
/base64-js@1.5.1:
|
/base64-js@1.5.1:
|
||||||
resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==}
|
resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==}
|
||||||
|
|
||||||
|
/bcrypt@6.0.0:
|
||||||
|
resolution: {integrity: sha512-cU8v/EGSrnH+HnxV2z0J7/blxH8gq7Xh2JFT6Aroax7UohdmiJJlxApMxtKfuI7z68NvvVcmR78k2LbT6efhRg==}
|
||||||
|
engines: {node: '>= 18'}
|
||||||
|
requiresBuild: true
|
||||||
|
dependencies:
|
||||||
|
node-addon-api: 8.5.0
|
||||||
|
node-gyp-build: 4.8.4
|
||||||
|
dev: false
|
||||||
|
|
||||||
/before@0.0.1:
|
/before@0.0.1:
|
||||||
resolution: {integrity: sha512-1J5SWbkoVJH9DTALN8igB4p+nPKZzPrJ/HomqBDLpfUvDXCdjdBmBUcH5McZfur0lftVssVU6BZug5NYh87zTw==}
|
resolution: {integrity: sha512-1J5SWbkoVJH9DTALN8igB4p+nPKZzPrJ/HomqBDLpfUvDXCdjdBmBUcH5McZfur0lftVssVU6BZug5NYh87zTw==}
|
||||||
dev: true
|
dev: true
|
||||||
@@ -5962,11 +5976,6 @@ packages:
|
|||||||
streamsearch: 1.1.0
|
streamsearch: 1.1.0
|
||||||
dev: false
|
dev: false
|
||||||
|
|
||||||
/bytes@3.0.0:
|
|
||||||
resolution: {integrity: sha512-pMhOfFDPiv9t5jjIXkHosWmkSyQbvsgEVNkz0ERHbuLh2T/7j4Mqqpz523Fe8MVY89KC6Sh/QfS2sM+SjgFDcw==}
|
|
||||||
engines: {node: '>= 0.8'}
|
|
||||||
dev: false
|
|
||||||
|
|
||||||
/bytes@3.1.2:
|
/bytes@3.1.2:
|
||||||
resolution: {integrity: sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==}
|
resolution: {integrity: sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==}
|
||||||
engines: {node: '>= 0.8'}
|
engines: {node: '>= 0.8'}
|
||||||
@@ -6384,11 +6393,6 @@ packages:
|
|||||||
resolution: {integrity: sha512-xFxOwqIzR/e1k1gLiWEophSCMqXcwVHIH7akf7b/vxcUeGunlj3hvZaaqxwHsTgn+IndtkQJgSztIDWeumWJDQ==}
|
resolution: {integrity: sha512-xFxOwqIzR/e1k1gLiWEophSCMqXcwVHIH7akf7b/vxcUeGunlj3hvZaaqxwHsTgn+IndtkQJgSztIDWeumWJDQ==}
|
||||||
dev: true
|
dev: true
|
||||||
|
|
||||||
/content-disposition@0.5.2:
|
|
||||||
resolution: {integrity: sha512-kRGRZw3bLlFISDBgwTSA1TMBFN6J6GWDeubmDE3AF+3+yXL8hTWv8r5rkLbqYXY4RjPk/EzHnClI3zQf1cFmHA==}
|
|
||||||
engines: {node: '>= 0.6'}
|
|
||||||
dev: false
|
|
||||||
|
|
||||||
/content-disposition@0.5.4:
|
/content-disposition@0.5.4:
|
||||||
resolution: {integrity: sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==}
|
resolution: {integrity: sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==}
|
||||||
engines: {node: '>= 0.6'}
|
engines: {node: '>= 0.6'}
|
||||||
@@ -8480,9 +8484,9 @@ packages:
|
|||||||
hasBin: true
|
hasBin: true
|
||||||
dev: true
|
dev: true
|
||||||
|
|
||||||
/helmet@6.2.0:
|
/helmet@8.1.0:
|
||||||
resolution: {integrity: sha512-DWlwuXLLqbrIOltR6tFQXShj/+7Cyp0gLi6uAb8qMdFh/YBBFbKSgQ6nbXmScYd8emMctuthmgIa7tUfo9Rtyg==}
|
resolution: {integrity: sha512-jOiHyAZsmnr8LqoPGmCjYAaiuWwjAPLgY8ZX2XrmHawt99/u1y6RgrZMTeoPfpUbV96HOalYgz1qzkRbw54Pmg==}
|
||||||
engines: {node: '>=14.0.0'}
|
engines: {node: '>=18.0.0'}
|
||||||
|
|
||||||
/history@5.3.0:
|
/history@5.3.0:
|
||||||
resolution: {integrity: sha512-ZqaKwjjrAYUYfLG+htGaIIZ4nioX2L70ZUMIFysS3xvBsSG4x/n1V6TXV3N8ZYNuFGlDirFg32T7B6WOUPDYcQ==}
|
resolution: {integrity: sha512-ZqaKwjjrAYUYfLG+htGaIIZ4nioX2L70ZUMIFysS3xvBsSG4x/n1V6TXV3N8ZYNuFGlDirFg32T7B6WOUPDYcQ==}
|
||||||
@@ -9961,11 +9965,6 @@ packages:
|
|||||||
brorand: 1.1.0
|
brorand: 1.1.0
|
||||||
dev: true
|
dev: true
|
||||||
|
|
||||||
/mime-db@1.33.0:
|
|
||||||
resolution: {integrity: sha512-BHJ/EKruNIqJf/QahvxwQZXKygOQ256myeN/Ew+THcAa5q+PjyTTMMeNQC4DZw5AwfvelsUrA6B67NKMqXDbzQ==}
|
|
||||||
engines: {node: '>= 0.6'}
|
|
||||||
dev: false
|
|
||||||
|
|
||||||
/mime-db@1.52.0:
|
/mime-db@1.52.0:
|
||||||
resolution: {integrity: sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==}
|
resolution: {integrity: sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==}
|
||||||
engines: {node: '>= 0.6'}
|
engines: {node: '>= 0.6'}
|
||||||
@@ -9974,13 +9973,6 @@ packages:
|
|||||||
resolution: {integrity: sha512-oHlN/w+3MQ3rba9rqFr6V/ypF10LSkdwUysQL7GkXoTgIWeV+tcXGA852TBxH+gsh8UWoyhR1hKcoMJTuWflpg==}
|
resolution: {integrity: sha512-oHlN/w+3MQ3rba9rqFr6V/ypF10LSkdwUysQL7GkXoTgIWeV+tcXGA852TBxH+gsh8UWoyhR1hKcoMJTuWflpg==}
|
||||||
engines: {node: '>= 0.6'}
|
engines: {node: '>= 0.6'}
|
||||||
|
|
||||||
/mime-types@2.1.18:
|
|
||||||
resolution: {integrity: sha512-lc/aahn+t4/SWV/qcmumYjymLsWfN3ELhpmVuUFjgsORruuZPVSwAQryq+HHGvO/SI2KVX26bx+En+zhM8g8hQ==}
|
|
||||||
engines: {node: '>= 0.6'}
|
|
||||||
dependencies:
|
|
||||||
mime-db: 1.33.0
|
|
||||||
dev: false
|
|
||||||
|
|
||||||
/mime-types@2.1.35:
|
/mime-types@2.1.35:
|
||||||
resolution: {integrity: sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==}
|
resolution: {integrity: sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==}
|
||||||
engines: {node: '>= 0.6'}
|
engines: {node: '>= 0.6'}
|
||||||
@@ -10237,6 +10229,11 @@ packages:
|
|||||||
resolution: {integrity: sha512-73sE9+3UaLYYFmDsFZnqCInzPyh3MqIwZO9cw58yIqAZhONrrabrYyYe3TuIqtIiOuTXVhsGau8hcrhhwSsDIQ==}
|
resolution: {integrity: sha512-73sE9+3UaLYYFmDsFZnqCInzPyh3MqIwZO9cw58yIqAZhONrrabrYyYe3TuIqtIiOuTXVhsGau8hcrhhwSsDIQ==}
|
||||||
dev: false
|
dev: false
|
||||||
|
|
||||||
|
/node-addon-api@8.5.0:
|
||||||
|
resolution: {integrity: sha512-/bRZty2mXUIFY/xU5HLvveNHlswNJej+RnxBjOMkidWfwZzgTbPG1E3K5TOxRLOR+5hX7bSofy8yf1hZevMS8A==}
|
||||||
|
engines: {node: ^18 || ^20 || >= 21}
|
||||||
|
dev: false
|
||||||
|
|
||||||
/node-domexception@1.0.0:
|
/node-domexception@1.0.0:
|
||||||
resolution: {integrity: sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==}
|
resolution: {integrity: sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==}
|
||||||
engines: {node: '>=10.5.0'}
|
engines: {node: '>=10.5.0'}
|
||||||
@@ -10263,6 +10260,11 @@ packages:
|
|||||||
formdata-polyfill: 4.0.10
|
formdata-polyfill: 4.0.10
|
||||||
dev: true
|
dev: true
|
||||||
|
|
||||||
|
/node-gyp-build@4.8.4:
|
||||||
|
resolution: {integrity: sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==}
|
||||||
|
hasBin: true
|
||||||
|
dev: false
|
||||||
|
|
||||||
/node-gyp@8.4.1:
|
/node-gyp@8.4.1:
|
||||||
resolution: {integrity: sha512-olTJRgUtAb/hOXG0E93wZDs5YiJlgbXxTwQAFHyNlRsXQnYzUaF2aGgujZbw+hR8aF4ZG/rST57bWMWD16jr9w==}
|
resolution: {integrity: sha512-olTJRgUtAb/hOXG0E93wZDs5YiJlgbXxTwQAFHyNlRsXQnYzUaF2aGgujZbw+hR8aF4ZG/rST57bWMWD16jr9w==}
|
||||||
engines: {node: '>= 10.12.0'}
|
engines: {node: '>= 10.12.0'}
|
||||||
@@ -10776,10 +10778,6 @@ packages:
|
|||||||
engines: {node: '>=0.10.0'}
|
engines: {node: '>=0.10.0'}
|
||||||
requiresBuild: true
|
requiresBuild: true
|
||||||
|
|
||||||
/path-is-inside@1.0.2:
|
|
||||||
resolution: {integrity: sha512-DUWJr3+ULp4zXmol/SZkFf3JGsS9/SIv+Y3Rt93/UjPpDpklB5f1er4O3POIbUuUJ3FXgqte2Q7SrU6zAqwk8w==}
|
|
||||||
dev: false
|
|
||||||
|
|
||||||
/path-key@3.1.1:
|
/path-key@3.1.1:
|
||||||
resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==}
|
resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==}
|
||||||
engines: {node: '>=8'}
|
engines: {node: '>=8'}
|
||||||
@@ -10814,10 +10812,6 @@ packages:
|
|||||||
resolution: {integrity: sha512-G6zHoVqC6GGTQkZwF4lkuEyMbVOjoBKAEybQUypI1WTkqinCOrq2x6U2+phkJ1XsEMTy4LjtwPI7HW+NVrRR2w==}
|
resolution: {integrity: sha512-G6zHoVqC6GGTQkZwF4lkuEyMbVOjoBKAEybQUypI1WTkqinCOrq2x6U2+phkJ1XsEMTy4LjtwPI7HW+NVrRR2w==}
|
||||||
dev: true
|
dev: true
|
||||||
|
|
||||||
/path-to-regexp@3.3.0:
|
|
||||||
resolution: {integrity: sha512-qyCH421YQPS2WFDxDjftfc1ZR5WKQzVzqsp4n9M2kQhVOo/ByahFoUNJfl58kOcEGfQ//7weFTDhm+ss8Ecxgw==}
|
|
||||||
dev: false
|
|
||||||
|
|
||||||
/path-to-regexp@6.3.0:
|
/path-to-regexp@6.3.0:
|
||||||
resolution: {integrity: sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ==}
|
resolution: {integrity: sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ==}
|
||||||
dev: false
|
dev: false
|
||||||
@@ -11603,8 +11597,8 @@ packages:
|
|||||||
signal-exit: 3.0.7
|
signal-exit: 3.0.7
|
||||||
dev: false
|
dev: false
|
||||||
|
|
||||||
/protobufjs@7.4.0:
|
/protobufjs@7.5.4:
|
||||||
resolution: {integrity: sha512-mRUWCc3KUU4w1jU8sGxICXH/gNS94DvI1gxqDvBzhj1JpcsimQkYiOJfwsPUykUI5ZaspFbSgmBLER8IrQ3tqw==}
|
resolution: {integrity: sha512-CvexbZtbov6jW2eXAvLukXjXUW1TzFaivC46BpWc/3BpcCysb5Vffu+B3XHMm8lVEuy2Mm4XGex8hBSg1yapPg==}
|
||||||
engines: {node: '>=12.0.0'}
|
engines: {node: '>=12.0.0'}
|
||||||
requiresBuild: true
|
requiresBuild: true
|
||||||
dependencies:
|
dependencies:
|
||||||
@@ -11808,11 +11802,6 @@ packages:
|
|||||||
safe-buffer: 5.2.1
|
safe-buffer: 5.2.1
|
||||||
dev: true
|
dev: true
|
||||||
|
|
||||||
/range-parser@1.2.0:
|
|
||||||
resolution: {integrity: sha512-kA5WQoNVo4t9lNx2kQNFCxKeBl5IbbSNBl1M/tLkw9WCn+hxNBAW5Qh8gdhs63CJnhjJ2zQWFoqPJP2sK1AV5A==}
|
|
||||||
engines: {node: '>= 0.6'}
|
|
||||||
dev: false
|
|
||||||
|
|
||||||
/range-parser@1.2.1:
|
/range-parser@1.2.1:
|
||||||
resolution: {integrity: sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==}
|
resolution: {integrity: sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==}
|
||||||
engines: {node: '>= 0.6'}
|
engines: {node: '>= 0.6'}
|
||||||
@@ -13412,18 +13401,6 @@ packages:
|
|||||||
randombytes: 2.1.0
|
randombytes: 2.1.0
|
||||||
dev: true
|
dev: true
|
||||||
|
|
||||||
/serve-handler@6.1.6:
|
|
||||||
resolution: {integrity: sha512-x5RL9Y2p5+Sh3D38Fh9i/iQ5ZK+e4xuXRd/pGbM4D13tgo/MGwbttUk8emytcr1YYzBYs+apnUngBDFYfpjPuQ==}
|
|
||||||
dependencies:
|
|
||||||
bytes: 3.0.0
|
|
||||||
content-disposition: 0.5.2
|
|
||||||
mime-types: 2.1.18
|
|
||||||
minimatch: 3.1.2
|
|
||||||
path-is-inside: 1.0.2
|
|
||||||
path-to-regexp: 3.3.0
|
|
||||||
range-parser: 1.2.0
|
|
||||||
dev: false
|
|
||||||
|
|
||||||
/serve-static@1.16.2:
|
/serve-static@1.16.2:
|
||||||
resolution: {integrity: sha512-VqpjJZKadQB/PEbEwvFdO43Ax5dFBZ2UECszz8bQ7pi7wt//PWe1P6MN7eCnjsatYtBT6EuiClbjSWP2WrIoTw==}
|
resolution: {integrity: sha512-VqpjJZKadQB/PEbEwvFdO43Ax5dFBZ2UECszz8bQ7pi7wt//PWe1P6MN7eCnjsatYtBT6EuiClbjSWP2WrIoTw==}
|
||||||
engines: {node: '>= 0.8.0'}
|
engines: {node: '>= 0.8.0'}
|
||||||
@@ -14383,14 +14360,14 @@ packages:
|
|||||||
/ts-proto-descriptors@2.0.0:
|
/ts-proto-descriptors@2.0.0:
|
||||||
resolution: {integrity: sha512-wHcTH3xIv11jxgkX5OyCSFfw27agpInAd6yh89hKG6zqIXnjW9SYqSER2CVQxdPj4czeOhGagNvZBEbJPy7qkw==}
|
resolution: {integrity: sha512-wHcTH3xIv11jxgkX5OyCSFfw27agpInAd6yh89hKG6zqIXnjW9SYqSER2CVQxdPj4czeOhGagNvZBEbJPy7qkw==}
|
||||||
dependencies:
|
dependencies:
|
||||||
'@bufbuild/protobuf': 2.2.3
|
'@bufbuild/protobuf': 2.10.0
|
||||||
dev: true
|
dev: true
|
||||||
|
|
||||||
/ts-proto@2.6.1:
|
/ts-proto@2.6.1:
|
||||||
resolution: {integrity: sha512-4LTT99MkwkF1+fIA0b2mZu/58Qlpq3Q1g53TwEMZZgR1w/uX00PoVT4Z8aKJxMw0LeKQD4s9NrJYsF27Clckrg==}
|
resolution: {integrity: sha512-4LTT99MkwkF1+fIA0b2mZu/58Qlpq3Q1g53TwEMZZgR1w/uX00PoVT4Z8aKJxMw0LeKQD4s9NrJYsF27Clckrg==}
|
||||||
hasBin: true
|
hasBin: true
|
||||||
dependencies:
|
dependencies:
|
||||||
'@bufbuild/protobuf': 2.2.3
|
'@bufbuild/protobuf': 2.10.0
|
||||||
case-anything: 2.1.13
|
case-anything: 2.1.13
|
||||||
ts-poet: 6.9.0
|
ts-poet: 6.9.0
|
||||||
ts-proto-descriptors: 2.0.0
|
ts-proto-descriptors: 2.0.0
|
||||||
@@ -15263,3 +15240,7 @@ packages:
|
|||||||
- encoding
|
- encoding
|
||||||
- supports-color
|
- supports-color
|
||||||
dev: false
|
dev: false
|
||||||
|
|
||||||
|
settings:
|
||||||
|
autoInstallPeers: true
|
||||||
|
excludeLinksFromLockfile: false
|
||||||
|
|||||||
@@ -226,9 +226,17 @@ export QMSG_TYPE=""
|
|||||||
## ntfy_url 填写ntfy地址,如https://ntfy.sh
|
## ntfy_url 填写ntfy地址,如https://ntfy.sh
|
||||||
## ntfy_topic 填写ntfy的消息应用topic
|
## ntfy_topic 填写ntfy的消息应用topic
|
||||||
## ntfy_priority 填写推送消息优先级,默认为3
|
## ntfy_priority 填写推送消息优先级,默认为3
|
||||||
|
## ntfy_token 填写推送token,可选
|
||||||
|
## ntfy_username 填写推送用户名称,可选
|
||||||
|
## ntfy_password 填写推送用户密码,可选
|
||||||
|
## ntfy_actions 填写推送用户动作,可选
|
||||||
export NTFY_URL=""
|
export NTFY_URL=""
|
||||||
export NTFY_TOPIC=""
|
export NTFY_TOPIC=""
|
||||||
export NTFY_PRIORITY="3"
|
export NTFY_PRIORITY="3"
|
||||||
|
export NTFY_TOKEN=""
|
||||||
|
export NTFY_USERNAME=""
|
||||||
|
export NTFY_PASSWORD=""
|
||||||
|
export NTFY_ACTIONS=""
|
||||||
|
|
||||||
## 21. wxPusher
|
## 21. wxPusher
|
||||||
## 官方文档: https://wxpusher.zjiecode.com/docs/
|
## 官方文档: https://wxpusher.zjiecode.com/docs/
|
||||||
|
|||||||
+15
-1
@@ -140,6 +140,10 @@ const push_config = {
|
|||||||
NTFY_URL: '', // ntfy地址,如https://ntfy.sh,默认为https://ntfy.sh
|
NTFY_URL: '', // ntfy地址,如https://ntfy.sh,默认为https://ntfy.sh
|
||||||
NTFY_TOPIC: '', // ntfy的消息应用topic
|
NTFY_TOPIC: '', // ntfy的消息应用topic
|
||||||
NTFY_PRIORITY: '3', // 推送消息优先级,默认为3
|
NTFY_PRIORITY: '3', // 推送消息优先级,默认为3
|
||||||
|
NTFY_TOKEN: '', // 推送token,可选
|
||||||
|
NTFY_USERNAME: '', // 推送用户名称,可选
|
||||||
|
NTFY_PASSWORD: '', // 推送用户密码,可选
|
||||||
|
NTFY_ACTIONS: '', // 推送用户动作,可选
|
||||||
|
|
||||||
// 官方文档: https://wxpusher.zjiecode.com/docs/
|
// 官方文档: https://wxpusher.zjiecode.com/docs/
|
||||||
// 管理后台: https://wxpusher.zjiecode.com/admin/
|
// 管理后台: https://wxpusher.zjiecode.com/admin/
|
||||||
@@ -1258,7 +1262,7 @@ function ntfyNotify(text, desp) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return new Promise((resolve) => {
|
return new Promise((resolve) => {
|
||||||
const { NTFY_URL, NTFY_TOPIC, NTFY_PRIORITY } = push_config;
|
const { NTFY_URL, NTFY_TOPIC, NTFY_PRIORITY, NTFY_TOKEN, NTFY_USERNAME, NTFY_PASSWORD, NTFY_ACTIONS } = push_config;
|
||||||
if (NTFY_TOPIC) {
|
if (NTFY_TOPIC) {
|
||||||
const options = {
|
const options = {
|
||||||
url: `${NTFY_URL || 'https://ntfy.sh'}/${NTFY_TOPIC}`,
|
url: `${NTFY_URL || 'https://ntfy.sh'}/${NTFY_TOPIC}`,
|
||||||
@@ -1266,9 +1270,19 @@ function ntfyNotify(text, desp) {
|
|||||||
headers: {
|
headers: {
|
||||||
Title: `${encodeRFC2047(text)}`,
|
Title: `${encodeRFC2047(text)}`,
|
||||||
Priority: NTFY_PRIORITY || '3',
|
Priority: NTFY_PRIORITY || '3',
|
||||||
|
Icon: 'https://qn.whyour.cn/logo.png',
|
||||||
},
|
},
|
||||||
timeout,
|
timeout,
|
||||||
};
|
};
|
||||||
|
if (NTFY_TOKEN) {
|
||||||
|
options.headers['Authorization'] = `Bearer ${NTFY_TOKEN}`;
|
||||||
|
} else if (NTFY_USERNAME && NTFY_PASSWORD) {
|
||||||
|
options.headers['Authorization'] = `Basic ${Buffer.from(`${NTFY_USERNAME}:${NTFY_PASSWORD}`).toString('base64')}`;
|
||||||
|
}
|
||||||
|
if (NTFY_ACTIONS) {
|
||||||
|
options.headers['Actions'] = encodeRFC2047(NTFY_ACTIONS);
|
||||||
|
}
|
||||||
|
|
||||||
$.post(options, (err, resp, data) => {
|
$.post(options, (err, resp, data) => {
|
||||||
try {
|
try {
|
||||||
if (err) {
|
if (err) {
|
||||||
|
|||||||
+12
-1
@@ -126,6 +126,10 @@ push_config = {
|
|||||||
'NTFY_URL': '', # ntfy地址,如https://ntfy.sh
|
'NTFY_URL': '', # ntfy地址,如https://ntfy.sh
|
||||||
'NTFY_TOPIC': '', # ntfy的消息应用topic
|
'NTFY_TOPIC': '', # ntfy的消息应用topic
|
||||||
'NTFY_PRIORITY':'3', # 推送消息优先级,默认为3
|
'NTFY_PRIORITY':'3', # 推送消息优先级,默认为3
|
||||||
|
'NTFY_TOKEN': '', # 推送token,可选
|
||||||
|
'NTFY_USERNAME': '', # 推送用户名称,可选
|
||||||
|
'NTFY_PASSWORD': '', # 推送用户密码,可选
|
||||||
|
'NTFY_ACTIONS': '', # 推送用户动作,可选
|
||||||
|
|
||||||
'WXPUSHER_APP_TOKEN': '', # wxpusher 的 appToken 官方文档: https://wxpusher.zjiecode.com/docs/ 管理后台: https://wxpusher.zjiecode.com/admin/
|
'WXPUSHER_APP_TOKEN': '', # wxpusher 的 appToken 官方文档: https://wxpusher.zjiecode.com/docs/ 管理后台: https://wxpusher.zjiecode.com/admin/
|
||||||
'WXPUSHER_TOPIC_IDS': '', # wxpusher 的 主题ID,多个用英文分号;分隔 topic_ids 与 uids 至少配置一个才行
|
'WXPUSHER_TOPIC_IDS': '', # wxpusher 的 主题ID,多个用英文分号;分隔 topic_ids 与 uids 至少配置一个才行
|
||||||
@@ -806,7 +810,14 @@ def ntfy(title: str, content: str) -> None:
|
|||||||
encoded_title = encode_rfc2047(title)
|
encoded_title = encode_rfc2047(title)
|
||||||
|
|
||||||
data = content.encode(encoding="utf-8")
|
data = content.encode(encoding="utf-8")
|
||||||
headers = {"Title": encoded_title, "Priority": priority} # 使用编码后的 title
|
headers = {"Title": encoded_title, "Priority": priority, "Icon": "https://qn.whyour.cn/logo.png"} # 使用编码后的 title
|
||||||
|
if push_config.get("NTFY_TOKEN"):
|
||||||
|
headers['Authorization'] = "Bearer " + push_config.get("NTFY_TOKEN")
|
||||||
|
elif push_config.get("NTFY_USERNAME") and push_config.get("NTFY_PASSWORD"):
|
||||||
|
authStr = push_config.get("NTFY_USERNAME") + ":" + push_config.get("NTFY_PASSWORD")
|
||||||
|
headers['Authorization'] = "Basic " + base64.b64encode(authStr.encode('utf-8')).decode('utf-8')
|
||||||
|
if push_config.get("NTFY_ACTIONS"):
|
||||||
|
headers['Actions'] = encode_rfc2047(push_config.get("NTFY_ACTIONS"))
|
||||||
|
|
||||||
url = push_config.get("NTFY_URL") + "/" + push_config.get("NTFY_TOPIC")
|
url = push_config.get("NTFY_URL") + "/" + push_config.get("NTFY_TOPIC")
|
||||||
response = requests.post(url, data=data, headers=headers)
|
response = requests.post(url, data=data, headers=headers)
|
||||||
|
|||||||
+8
-48
@@ -41,14 +41,9 @@ add_cron_api() {
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
local api=$(
|
local api=$(
|
||||||
curl -s --noproxy "*" "http://0.0.0.0:5600/open/crons?t=$currentTimeStamp" \
|
curl -s --noproxy "*" "http://0.0.0.0:5700/open/crons?t=$currentTimeStamp" \
|
||||||
-H "Accept: application/json" \
|
|
||||||
-H "Authorization: Bearer ${__ql_token__}" \
|
-H "Authorization: Bearer ${__ql_token__}" \
|
||||||
-H "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36" \
|
|
||||||
-H "Content-Type: application/json;charset=UTF-8" \
|
-H "Content-Type: application/json;charset=UTF-8" \
|
||||||
-H "Origin: http://0.0.0.0:5700" \
|
|
||||||
-H "Referer: http://0.0.0.0:5700/crontab" \
|
|
||||||
-H "Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7" \
|
|
||||||
--data-raw "{\"name\":\"${name//\"/\\\"}\",\"command\":\"${command//\"/\\\"}\",\"schedule\":\"$schedule\",\"sub_id\":$sub_id}" \
|
--data-raw "{\"name\":\"${name//\"/\\\"}\",\"command\":\"${command//\"/\\\"}\",\"schedule\":\"$schedule\",\"sub_id\":$sub_id}" \
|
||||||
--compressed
|
--compressed
|
||||||
)
|
)
|
||||||
@@ -76,15 +71,10 @@ update_cron_api() {
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
local api=$(
|
local api=$(
|
||||||
curl -s --noproxy "*" "http://0.0.0.0:5600/open/crons?t=$currentTimeStamp" \
|
curl -s --noproxy "*" "http://0.0.0.0:5700/open/crons?t=$currentTimeStamp" \
|
||||||
-X 'PUT' \
|
-X 'PUT' \
|
||||||
-H "Accept: application/json" \
|
|
||||||
-H "Authorization: Bearer ${__ql_token__}" \
|
-H "Authorization: Bearer ${__ql_token__}" \
|
||||||
-H "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36" \
|
|
||||||
-H "Content-Type: application/json;charset=UTF-8" \
|
-H "Content-Type: application/json;charset=UTF-8" \
|
||||||
-H "Origin: http://0.0.0.0:5700" \
|
|
||||||
-H "Referer: http://0.0.0.0:5700/crontab" \
|
|
||||||
-H "Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7" \
|
|
||||||
--data-raw "{\"name\":\"${name//\"/\\\"}\",\"command\":\"${command//\"/\\\"}\",\"schedule\":\"$schedule\",\"id\":\"$id\"}" \
|
--data-raw "{\"name\":\"${name//\"/\\\"}\",\"command\":\"${command//\"/\\\"}\",\"schedule\":\"$schedule\",\"id\":\"$id\"}" \
|
||||||
--compressed
|
--compressed
|
||||||
)
|
)
|
||||||
@@ -108,15 +98,10 @@ update_cron_command_api() {
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
local api=$(
|
local api=$(
|
||||||
curl -s --noproxy "*" "http://0.0.0.0:5600/open/crons?t=$currentTimeStamp" \
|
curl -s --noproxy "*" "http://0.0.0.0:5700/open/crons?t=$currentTimeStamp" \
|
||||||
-X 'PUT' \
|
-X 'PUT' \
|
||||||
-H "Accept: application/json" \
|
|
||||||
-H "Authorization: Bearer ${__ql_token__}" \
|
-H "Authorization: Bearer ${__ql_token__}" \
|
||||||
-H "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36" \
|
|
||||||
-H "Content-Type: application/json;charset=UTF-8" \
|
-H "Content-Type: application/json;charset=UTF-8" \
|
||||||
-H "Origin: http://0.0.0.0:5700" \
|
|
||||||
-H "Referer: http://0.0.0.0:5700/crontab" \
|
|
||||||
-H "Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7" \
|
|
||||||
--data-raw "{\"command\":\"${command//\"/\\\"}\",\"id\":\"$id\"}" \
|
--data-raw "{\"command\":\"${command//\"/\\\"}\",\"id\":\"$id\"}" \
|
||||||
--compressed
|
--compressed
|
||||||
)
|
)
|
||||||
@@ -133,15 +118,10 @@ del_cron_api() {
|
|||||||
local ids="$1"
|
local ids="$1"
|
||||||
local currentTimeStamp=$(date +%s)
|
local currentTimeStamp=$(date +%s)
|
||||||
local api=$(
|
local api=$(
|
||||||
curl -s --noproxy "*" "http://0.0.0.0:5600/open/crons?t=$currentTimeStamp" \
|
curl -s --noproxy "*" "http://0.0.0.0:5700/open/crons?t=$currentTimeStamp" \
|
||||||
-X 'DELETE' \
|
-X 'DELETE' \
|
||||||
-H "Accept: application/json" \
|
|
||||||
-H "Authorization: Bearer ${__ql_token__}" \
|
-H "Authorization: Bearer ${__ql_token__}" \
|
||||||
-H "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36" \
|
|
||||||
-H "Content-Type: application/json;charset=UTF-8" \
|
-H "Content-Type: application/json;charset=UTF-8" \
|
||||||
-H "Origin: http://0.0.0.0:5700" \
|
|
||||||
-H "Referer: http://0.0.0.0:5700/crontab" \
|
|
||||||
-H "Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7" \
|
|
||||||
--data-raw "[$ids]" \
|
--data-raw "[$ids]" \
|
||||||
--compressed
|
--compressed
|
||||||
)
|
)
|
||||||
@@ -163,15 +143,10 @@ update_cron() {
|
|||||||
local runningTime="${6:-0}"
|
local runningTime="${6:-0}"
|
||||||
local currentTimeStamp=$(date +%s)
|
local currentTimeStamp=$(date +%s)
|
||||||
local api=$(
|
local api=$(
|
||||||
curl -s --noproxy "*" "http://0.0.0.0:5600/open/crons/status?t=$currentTimeStamp" \
|
curl -s --noproxy "*" "http://0.0.0.0:5700/open/crons/status?t=$currentTimeStamp" \
|
||||||
-X 'PUT' \
|
-X 'PUT' \
|
||||||
-H "Accept: application/json" \
|
|
||||||
-H "Authorization: Bearer ${__ql_token__}" \
|
-H "Authorization: Bearer ${__ql_token__}" \
|
||||||
-H "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36" \
|
|
||||||
-H "Content-Type: application/json;charset=UTF-8" \
|
-H "Content-Type: application/json;charset=UTF-8" \
|
||||||
-H "Origin: http://0.0.0.0:5700" \
|
|
||||||
-H "Referer: http://0.0.0.0:5700/crontab" \
|
|
||||||
-H "Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7" \
|
|
||||||
--data-raw "{\"ids\":[$ids],\"status\":\"$status\",\"pid\":\"$pid\",\"log_path\":\"$logPath\",\"last_execution_time\":$lastExecutingTime,\"last_running_time\":$runningTime}" \
|
--data-raw "{\"ids\":[$ids],\"status\":\"$status\",\"pid\":\"$pid\",\"log_path\":\"$logPath\",\"last_execution_time\":$lastExecutingTime,\"last_running_time\":$runningTime}" \
|
||||||
--compressed
|
--compressed
|
||||||
)
|
)
|
||||||
@@ -190,15 +165,10 @@ notify_api() {
|
|||||||
local content="$2"
|
local content="$2"
|
||||||
local currentTimeStamp=$(date +%s)
|
local currentTimeStamp=$(date +%s)
|
||||||
local api=$(
|
local api=$(
|
||||||
curl -s --noproxy "*" "http://0.0.0.0:5600/open/system/notify?t=$currentTimeStamp" \
|
curl -s --noproxy "*" "http://0.0.0.0:5700/open/system/notify?t=$currentTimeStamp" \
|
||||||
-X 'PUT' \
|
-X 'PUT' \
|
||||||
-H "Accept: application/json" \
|
|
||||||
-H "Authorization: Bearer ${__ql_token__}" \
|
-H "Authorization: Bearer ${__ql_token__}" \
|
||||||
-H "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36" \
|
|
||||||
-H "Content-Type: application/json;charset=UTF-8" \
|
-H "Content-Type: application/json;charset=UTF-8" \
|
||||||
-H "Origin: http://0.0.0.0:5700" \
|
|
||||||
-H "Referer: http://0.0.0.0:5700/crontab" \
|
|
||||||
-H "Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7" \
|
|
||||||
--data-raw "{\"title\":\"${title//\"/\\\"}\",\"content\":\"${content//\"/\\\"}\"}" \
|
--data-raw "{\"title\":\"${title//\"/\\\"}\",\"content\":\"${content//\"/\\\"}\"}" \
|
||||||
--compressed
|
--compressed
|
||||||
)
|
)
|
||||||
@@ -215,14 +185,9 @@ find_cron_api() {
|
|||||||
local params="$1"
|
local params="$1"
|
||||||
local currentTimeStamp=$(date +%s)
|
local currentTimeStamp=$(date +%s)
|
||||||
local api=$(
|
local api=$(
|
||||||
curl -s --noproxy "*" "http://0.0.0.0:5600/open/crons/detail?$params&t=$currentTimeStamp" \
|
curl -s --noproxy "*" "http://0.0.0.0:5700/open/crons/detail?$params&t=$currentTimeStamp" \
|
||||||
-H "Accept: application/json" \
|
|
||||||
-H "Authorization: Bearer ${__ql_token__}" \
|
-H "Authorization: Bearer ${__ql_token__}" \
|
||||||
-H "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36" \
|
|
||||||
-H "Content-Type: application/json;charset=UTF-8" \
|
-H "Content-Type: application/json;charset=UTF-8" \
|
||||||
-H "Origin: http://0.0.0.0:5700" \
|
|
||||||
-H "Referer: http://0.0.0.0:5700/crontab" \
|
|
||||||
-H "Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7" \
|
|
||||||
--compressed
|
--compressed
|
||||||
)
|
)
|
||||||
data=$(echo "$api" | jq -r .data)
|
data=$(echo "$api" | jq -r .data)
|
||||||
@@ -239,15 +204,10 @@ update_auth_config() {
|
|||||||
local tip="$2"
|
local tip="$2"
|
||||||
local currentTimeStamp=$(date +%s)
|
local currentTimeStamp=$(date +%s)
|
||||||
local api=$(
|
local api=$(
|
||||||
curl -s --noproxy "*" "http://0.0.0.0:5600/open/system/auth/reset?t=$currentTimeStamp" \
|
curl -s --noproxy "*" "http://0.0.0.0:5700/open/system/auth/reset?t=$currentTimeStamp" \
|
||||||
-X 'PUT' \
|
-X 'PUT' \
|
||||||
-H "Accept: application/json" \
|
|
||||||
-H "Authorization: Bearer ${__ql_token__}" \
|
-H "Authorization: Bearer ${__ql_token__}" \
|
||||||
-H "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36" \
|
|
||||||
-H "Content-Type: application/json;charset=UTF-8" \
|
-H "Content-Type: application/json;charset=UTF-8" \
|
||||||
-H "Origin: http://0.0.0.0:5700" \
|
|
||||||
-H "Referer: http://0.0.0.0:5700/crontab" \
|
|
||||||
-H "Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7" \
|
|
||||||
--data-raw "{$body}" \
|
--data-raw "{$body}" \
|
||||||
--compressed
|
--compressed
|
||||||
)
|
)
|
||||||
|
|||||||
+3
-20
@@ -20,32 +20,16 @@ copy_dep() {
|
|||||||
echo -e "---> 复制一份 $file_notify_js_sample 为 $file_notify_js\n"
|
echo -e "---> 复制一份 $file_notify_js_sample 为 $file_notify_js\n"
|
||||||
cp -fv $file_notify_js_sample $file_notify_js
|
cp -fv $file_notify_js_sample $file_notify_js
|
||||||
echo -e "---> 通知文件复制完成\n"
|
echo -e "---> 通知文件复制完成\n"
|
||||||
|
|
||||||
echo -e "---> 2. 复制nginx配置文件\n"
|
|
||||||
init_nginx
|
|
||||||
echo -e "---> 配置文件复制完成\n"
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pm2_log() {
|
pm2_log() {
|
||||||
echo -e "---> pm2日志"
|
echo -e "---> pm2日志"
|
||||||
local panelOut="/root/.pm2/logs/panel-out.log"
|
local panelOut="/root/.pm2/logs/qinglong-out.log"
|
||||||
local panelError="/root/.pm2/logs/panel-error.log"
|
local panelError="/root/.pm2/logs/qinglong-error.log"
|
||||||
tail -n 300 "$panelOut"
|
tail -n 300 "$panelOut"
|
||||||
tail -n 300 "$panelError"
|
tail -n 300 "$panelError"
|
||||||
}
|
}
|
||||||
|
|
||||||
check_nginx() {
|
|
||||||
local nginxPid=$(ps -eo pid,command | grep nginx | grep -v grep)
|
|
||||||
echo -e "=====> 检测nginx服务\n$nginxPid"
|
|
||||||
if [[ $nginxPid ]]; then
|
|
||||||
echo -e "\n=====> nginx服务正常\n"
|
|
||||||
nginx -s reload
|
|
||||||
else
|
|
||||||
echo -e "\n=====> nginx服务异常,重新启动nginx\n"
|
|
||||||
nginx -c /etc/nginx/nginx.conf
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
check_ql() {
|
check_ql() {
|
||||||
local api=$(curl -s --noproxy "*" "http://0.0.0.0:5700")
|
local api=$(curl -s --noproxy "*" "http://0.0.0.0:5700")
|
||||||
echo -e "\n=====> 检测面板\n\n$api\n"
|
echo -e "\n=====> 检测面板\n\n$api\n"
|
||||||
@@ -58,7 +42,7 @@ check_pm2() {
|
|||||||
pm2_log
|
pm2_log
|
||||||
local currentTimeStamp=$(date +%s)
|
local currentTimeStamp=$(date +%s)
|
||||||
local api=$(
|
local api=$(
|
||||||
curl -s --noproxy "*" "http://0.0.0.0:5600/api/system?t=$currentTimeStamp" \
|
curl -s --noproxy "*" "http://0.0.0.0:5700/api/system?t=$currentTimeStamp" \
|
||||||
-H 'Accept: */*' \
|
-H 'Accept: */*' \
|
||||||
-H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36' \
|
-H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36' \
|
||||||
-H 'Referer: http://0.0.0.0:5700/crontab' \
|
-H 'Referer: http://0.0.0.0:5700/crontab' \
|
||||||
@@ -78,7 +62,6 @@ main() {
|
|||||||
reset_env
|
reset_env
|
||||||
copy_dep
|
copy_dep
|
||||||
check_ql
|
check_ql
|
||||||
check_nginx
|
|
||||||
check_pm2
|
check_pm2
|
||||||
reload_pm2
|
reload_pm2
|
||||||
echo -e "\n=====> 检测结束\n"
|
echo -e "\n=====> 检测结束\n"
|
||||||
|
|||||||
@@ -87,12 +87,10 @@ function run() {
|
|||||||
console.log('执行前置命令结束\n');
|
console.log('执行前置命令结束\n');
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (!error.message.includes('spawnSync /bin/sh E2BIG')) {
|
if (!error.message.includes('spawnSync /bin/bash E2BIG')) {
|
||||||
console.log(`\ue926 run task before error: `, error);
|
console.log(`\ue926 run task before error: `, error);
|
||||||
} else {
|
} else {
|
||||||
console.log(
|
// environment variable is too large
|
||||||
`\ue926 The environment variable is too large. It is recommended to use task_before.js instead of task_before.sh\n`,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
if (task_before) {
|
if (task_before) {
|
||||||
console.log('执行前置命令结束\n');
|
console.log('执行前置命令结束\n');
|
||||||
|
|||||||
@@ -98,10 +98,8 @@ def run():
|
|||||||
error_message = str(error)
|
error_message = str(error)
|
||||||
if "Argument list too long" not in error_message:
|
if "Argument list too long" not in error_message:
|
||||||
print(f"\ue926 run task before error: {error}")
|
print(f"\ue926 run task before error: {error}")
|
||||||
else:
|
# else:
|
||||||
print(
|
# environment variable is too large
|
||||||
"\ue926 The environment variable is too large. It is recommended to use task_before.py instead of task_before.sh\n"
|
|
||||||
)
|
|
||||||
if task_before:
|
if task_before:
|
||||||
print("执行前置命令结束\n")
|
print("执行前置命令结束\n")
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
|
|||||||
+3
-7
@@ -2,13 +2,9 @@
|
|||||||
echo -e "开始发布"
|
echo -e "开始发布"
|
||||||
|
|
||||||
echo -e "切换master分支"
|
echo -e "切换master分支"
|
||||||
git checkout master
|
git branch -D master
|
||||||
|
git checkout -b master
|
||||||
echo -e "合并develop代码"
|
git push --set-upstream origin master -f
|
||||||
git merge origin/develop
|
|
||||||
|
|
||||||
echo -e "提交master代码"
|
|
||||||
git push
|
|
||||||
|
|
||||||
echo -e "更新cdn文件"
|
echo -e "更新cdn文件"
|
||||||
ts-node-transpile-only sample/tool.ts
|
ts-node-transpile-only sample/tool.ts
|
||||||
|
|||||||
@@ -48,8 +48,6 @@ export file_notify_py=$dir_scripts/notify.py
|
|||||||
export file_notify_js=$dir_scripts/sendNotify.js
|
export file_notify_js=$dir_scripts/sendNotify.js
|
||||||
export file_test_js=$dir_scripts/ql_sample.js
|
export file_test_js=$dir_scripts/ql_sample.js
|
||||||
export file_test_py=$dir_scripts/ql_sample.py
|
export file_test_py=$dir_scripts/ql_sample.py
|
||||||
export nginx_app_conf=$dir_root/docker/front.conf
|
|
||||||
export nginx_conf=$dir_root/docker/nginx.conf
|
|
||||||
export dep_notify_py=$dir_dep/notify.py
|
export dep_notify_py=$dir_dep/notify.py
|
||||||
export dep_notify_js=$dir_dep/sendNotify.js
|
export dep_notify_js=$dir_dep/sendNotify.js
|
||||||
|
|
||||||
@@ -211,10 +209,6 @@ fix_config() {
|
|||||||
cp -f $file_test_py_sample $file_test_py
|
cp -f $file_test_py_sample $file_test_py
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if [[ -s /etc/nginx/conf.d/default.conf ]]; then
|
|
||||||
cat /dev/null >/etc/nginx/conf.d/default.conf
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [[ ! -s $dep_notify_js ]]; then
|
if [[ ! -s $dep_notify_js ]]; then
|
||||||
cp -f $file_notify_js_sample $dep_notify_js
|
cp -f $file_notify_js_sample $dep_notify_js
|
||||||
fi
|
fi
|
||||||
@@ -334,44 +328,6 @@ format_timestamp() {
|
|||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
init_nginx() {
|
|
||||||
cp -f $nginx_conf /etc/nginx/nginx.conf
|
|
||||||
cp -f $nginx_app_conf /etc/nginx/conf.d/front.conf
|
|
||||||
local location_url="/"
|
|
||||||
local aliasStr=""
|
|
||||||
local rootStr=""
|
|
||||||
if [[ $ql_base_url != "/" ]]; then
|
|
||||||
if [[ $ql_base_url != /* ]]; then
|
|
||||||
ql_base_url="/$ql_base_url"
|
|
||||||
fi
|
|
||||||
if [[ $ql_base_url != */ ]]; then
|
|
||||||
ql_base_url="$ql_base_url/"
|
|
||||||
fi
|
|
||||||
location_url="^~${ql_base_url%*/}"
|
|
||||||
aliasStr="alias ${dir_static}/dist;"
|
|
||||||
if ! grep -q "<base href=\"$ql_base_url\">" "${dir_static}/dist/index.html"; then
|
|
||||||
awk -v text="<base href=\"$ql_base_url\">" '/<link/ && !inserted {print text; inserted=1} 1' "${dir_static}/dist/index.html" >temp.html
|
|
||||||
mv temp.html "${dir_static}/dist/index.html"
|
|
||||||
fi
|
|
||||||
else
|
|
||||||
rootStr="root ${dir_static}/dist;"
|
|
||||||
fi
|
|
||||||
sed -i "s,QL_ALIAS_CONFIG,${aliasStr},g" /etc/nginx/conf.d/front.conf
|
|
||||||
sed -i "s,QL_ROOT_CONFIG,${rootStr},g" /etc/nginx/conf.d/front.conf
|
|
||||||
sed -i "s,QL_BASE_URL_LOCATION,${location_url},g" /etc/nginx/conf.d/front.conf
|
|
||||||
sed -i "s,QL_BASE_URL,${ql_base_url},g" /etc/nginx/conf.d/front.conf
|
|
||||||
|
|
||||||
local ipv6=$(ip a | grep inet6)
|
|
||||||
local ipv6Str=""
|
|
||||||
if [[ $ipv6 ]]; then
|
|
||||||
ipv6Str="listen [::]:${ql_port} ipv6only=on;"
|
|
||||||
fi
|
|
||||||
|
|
||||||
local ipv4Str="listen ${ql_port};"
|
|
||||||
sed -i "s,IPV6_CONFIG,${ipv6Str},g" /etc/nginx/conf.d/front.conf
|
|
||||||
sed -i "s,IPV4_CONFIG,${ipv4Str},g" /etc/nginx/conf.d/front.conf
|
|
||||||
}
|
|
||||||
|
|
||||||
get_env_array() {
|
get_env_array() {
|
||||||
exported_variables=()
|
exported_variables=()
|
||||||
while IFS= read -r line; do
|
while IFS= read -r line; do
|
||||||
|
|||||||
+19
-10
@@ -46,18 +46,22 @@ handle_log_path() {
|
|||||||
|
|
||||||
time=$(date "+$mtime_format")
|
time=$(date "+$mtime_format")
|
||||||
log_time=$(format_log_time "$mtime_format" "$time")
|
log_time=$(format_log_time "$mtime_format" "$time")
|
||||||
log_dir_tmp="${file_param##*/}"
|
if [[ -z $log_name ]]; then
|
||||||
if [[ $file_param =~ "/" ]]; then
|
log_dir_tmp="${file_param##*/}"
|
||||||
if [[ $file_param == /* ]]; then
|
if [[ $file_param =~ "/" ]]; then
|
||||||
log_dir_tmp_path="${file_param:1}"
|
if [[ $file_param == /* ]]; then
|
||||||
else
|
log_dir_tmp_path="${file_param:1}"
|
||||||
log_dir_tmp_path="${file_param}"
|
else
|
||||||
|
log_dir_tmp_path="${file_param}"
|
||||||
|
fi
|
||||||
fi
|
fi
|
||||||
|
log_dir_tmp_path="${log_dir_tmp_path%/*}"
|
||||||
|
log_dir_tmp_path="${log_dir_tmp_path##*/}"
|
||||||
|
[[ $log_dir_tmp_path ]] && log_dir_tmp="${log_dir_tmp_path}_${log_dir_tmp}"
|
||||||
|
log_dir="${log_dir_tmp%.*}${suffix}"
|
||||||
|
else
|
||||||
|
log_dir="$log_name"
|
||||||
fi
|
fi
|
||||||
log_dir_tmp_path="${log_dir_tmp_path%/*}"
|
|
||||||
log_dir_tmp_path="${log_dir_tmp_path##*/}"
|
|
||||||
[[ $log_dir_tmp_path ]] && log_dir_tmp="${log_dir_tmp_path}_${log_dir_tmp}"
|
|
||||||
log_dir="${log_dir_tmp%.*}${suffix}"
|
|
||||||
log_path="$log_dir/$log_time.log"
|
log_path="$log_dir/$log_time.log"
|
||||||
|
|
||||||
if [[ ${real_log_path:=} ]]; then
|
if [[ ${real_log_path:=} ]]; then
|
||||||
@@ -73,6 +77,11 @@ handle_log_path() {
|
|||||||
if [[ "${real_time:=}" == "true" ]]; then
|
if [[ "${real_time:=}" == "true" ]]; then
|
||||||
cmd=""
|
cmd=""
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
if [[ "${log_dir:=}" == "/dev/null" ]]; then
|
||||||
|
cmd=">> /dev/null"
|
||||||
|
log_path="/dev/null"
|
||||||
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
format_params() {
|
format_params() {
|
||||||
|
|||||||
+12
-5
@@ -7,11 +7,18 @@ export function rootContainer(container: any) {
|
|||||||
'en': require('./locales/en-US.json'),
|
'en': require('./locales/en-US.json'),
|
||||||
'zh': require('./locales/zh-CN.json'),
|
'zh': require('./locales/zh-CN.json'),
|
||||||
};
|
};
|
||||||
let currentLocale = intl.determineLocale({
|
let currentLocale: string;
|
||||||
urlLocaleKey: 'lang',
|
try {
|
||||||
cookieLocaleKey: 'lang',
|
currentLocale = intl.determineLocale({
|
||||||
localStorageLocaleKey: 'lang',
|
urlLocaleKey: 'lang',
|
||||||
}).slice(0, 2);
|
cookieLocaleKey: 'lang',
|
||||||
|
localStorageLocaleKey: 'lang',
|
||||||
|
}).slice(0, 2);
|
||||||
|
} catch (e: unknown) {
|
||||||
|
// Handle decodeURIComponent errors from malformed cookies
|
||||||
|
console.warn('Failed to determine locale from cookies:', e);
|
||||||
|
currentLocale = '';
|
||||||
|
}
|
||||||
|
|
||||||
if (!currentLocale || !Object.keys(locales).includes(currentLocale)) {
|
if (!currentLocale || !Object.keys(locales).includes(currentLocale)) {
|
||||||
currentLocale = 'zh';
|
currentLocale = 'zh';
|
||||||
|
|||||||
@@ -113,6 +113,8 @@ export default function () {
|
|||||||
const responseStatus = error.response.status;
|
const responseStatus = error.response.status;
|
||||||
if (responseStatus !== 401) {
|
if (responseStatus !== 401) {
|
||||||
history.push('/error');
|
history.push('/error');
|
||||||
|
} else {
|
||||||
|
window.location.reload();
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.finally(() => setInitLoading(false));
|
.finally(() => setInitLoading(false));
|
||||||
|
|||||||
+41
-2
@@ -395,7 +395,11 @@
|
|||||||
"PushMe的Key,https://push.i-i.me/": "PushMe key, https://push.i-i.me/",
|
"PushMe的Key,https://push.i-i.me/": "PushMe key, https://push.i-i.me/",
|
||||||
"自建的PushMeServer消息接口地址,例如:http://127.0.0.1:3010,不填则使用官方消息接口": "The self built PushMeServer message interface address, for example: http://127.0.0.1:3010 If left blank, use the official message interface",
|
"自建的PushMeServer消息接口地址,例如:http://127.0.0.1:3010,不填则使用官方消息接口": "The self built PushMeServer message interface address, for example: http://127.0.0.1:3010 If left blank, use the official message interface",
|
||||||
"ntfy的url地址,例如 https://ntfy.sh": "The URL address of ntfy, for example, https://ntfy.sh.",
|
"ntfy的url地址,例如 https://ntfy.sh": "The URL address of ntfy, for example, https://ntfy.sh.",
|
||||||
"ntfy的消息应用topic": "The topic for ntfy's messaging application.",
|
"ntfy应用topic": "The topic for ntfy's application.",
|
||||||
|
"ntfy应用token": "The token for ntfy's application, see https://docs.ntfy.sh/config/#access-tokens",
|
||||||
|
"ntfy应用用户名": "The username for ntfy's application, see https://docs.ntfy.sh/config/#users-and-roles",
|
||||||
|
"ntfy应用密码": "The password for ntfy's application, see https://docs.ntfy.sh/config/#users-and-roles",
|
||||||
|
"ntfy用户动作": "The user actions for ntfy's application, up to three actions, see https://docs.ntfy.sh/publish/?h=actions#action-buttons",
|
||||||
"wxPusherBot的appToken": "wxPusherBot's appToken, obtain according to docs https://wxpusher.zjiecode.com/docs/",
|
"wxPusherBot的appToken": "wxPusherBot's appToken, obtain according to docs https://wxpusher.zjiecode.com/docs/",
|
||||||
"wxPusherBot的topicIds": "wxPusherBot's topicIds, at least one of topicIds or uids must be configured",
|
"wxPusherBot的topicIds": "wxPusherBot's topicIds, at least one of topicIds or uids must be configured",
|
||||||
"wxPusherBot的uids": "wxPusherBot's uids, at least one of topicIds or uids must be configured",
|
"wxPusherBot的uids": "wxPusherBot's uids, at least one of topicIds or uids must be configured",
|
||||||
@@ -506,5 +510,40 @@
|
|||||||
"强制打开可能会导致编辑器显示异常": "Force opening may cause display issues in the editor",
|
"强制打开可能会导致编辑器显示异常": "Force opening may cause display issues in the editor",
|
||||||
"确认离开": "Confirm Leave",
|
"确认离开": "Confirm Leave",
|
||||||
"当前文件未保存,确认离开吗": "Current file is not saved, are you sure to leave?",
|
"当前文件未保存,确认离开吗": "Current file is not saved, are you sure to leave?",
|
||||||
"收件邮箱地址,多个分号分隔,默认发送给发件邮箱地址": "Receiving email address, multiple semicolon separated, sent to the sending email address by default"
|
"收件邮箱地址,多个分号分隔,默认发送给发件邮箱地址": "Receiving email address, multiple semicolon separated, sent to the sending email address by default",
|
||||||
|
"选择备份模块": "Select backup module",
|
||||||
|
"开始备份": "Start backup",
|
||||||
|
"基础数据": "Basic data",
|
||||||
|
"脚本文件": "Script files",
|
||||||
|
"日志文件": "Log files",
|
||||||
|
"依赖缓存": "Dependency cache",
|
||||||
|
"远程脚本缓存": "Remote script cache",
|
||||||
|
"远程仓库缓存": "Remote repository cache",
|
||||||
|
"SSH 文件缓存": "SSH file cache",
|
||||||
|
"清除依赖缓存": "Clean dependency cache",
|
||||||
|
"清除成功": "Clean successful",
|
||||||
|
"日志名称": "Log Name",
|
||||||
|
"自定义日志文件夹名称,用于区分不同任务的日志,留空则自动生成": "Custom log folder name to distinguish logs from different tasks. Leave blank to auto-generate",
|
||||||
|
"自定义日志文件夹名称,用于区分不同任务的日志,留空则自动生成。支持绝对路径如 /dev/null": "Custom log folder name to distinguish logs from different tasks. Leave blank to auto-generate. Supports absolute paths like /dev/null",
|
||||||
|
"自定义日志文件夹名称,用于区分不同任务的日志,留空则自动生成。支持 /dev/null 丢弃日志,其他绝对路径必须在日志目录内": "Custom log folder name to distinguish logs from different tasks. Leave blank to auto-generate. Supports /dev/null to discard logs, other absolute paths must be within log directory",
|
||||||
|
"请输入自定义日志文件夹名称": "Please enter a custom log folder name",
|
||||||
|
"请输入自定义日志文件夹名称或绝对路径": "Please enter a custom log folder name or absolute path",
|
||||||
|
"请输入自定义日志文件夹名称或 /dev/null": "Please enter a custom log folder name or /dev/null",
|
||||||
|
"日志名称只能包含字母、数字、下划线和连字符": "Log name can only contain letters, numbers, underscores and hyphens",
|
||||||
|
"日志名称不能超过100个字符": "Log name cannot exceed 100 characters",
|
||||||
|
"用户管理": "User Management",
|
||||||
|
"用户名": "Username",
|
||||||
|
"密码": "Password",
|
||||||
|
"角色": "Role",
|
||||||
|
"管理员": "Admin",
|
||||||
|
"普通用户": "User",
|
||||||
|
"启用": "Enabled",
|
||||||
|
"禁用": "Disabled",
|
||||||
|
"创建时间": "Created At",
|
||||||
|
"确认删除选中的用户吗": "Are you sure to delete selected users?",
|
||||||
|
"请输入用户名": "Please enter username",
|
||||||
|
"请输入密码": "Please enter password",
|
||||||
|
"密码长度至少为6位": "Password must be at least 6 characters",
|
||||||
|
"新增用户": "Add User",
|
||||||
|
"编辑用户": "Edit User"
|
||||||
}
|
}
|
||||||
|
|||||||
+41
-3
@@ -395,7 +395,11 @@
|
|||||||
"PushMe的Key,https://push.i-i.me/": "PushMe的Key,https://push.i-i.me/",
|
"PushMe的Key,https://push.i-i.me/": "PushMe的Key,https://push.i-i.me/",
|
||||||
"自建的PushMeServer消息接口地址,例如:http://127.0.0.1:3010,不填则使用官方消息接口": "自建的PushMeServer消息接口地址,例如:http://127.0.0.1:3010,不填则使用官方消息接口",
|
"自建的PushMeServer消息接口地址,例如:http://127.0.0.1:3010,不填则使用官方消息接口": "自建的PushMeServer消息接口地址,例如:http://127.0.0.1:3010,不填则使用官方消息接口",
|
||||||
"ntfy的url地址,例如 https://ntfy.sh": "ntfy的url地址,例如 https://ntfy.sh",
|
"ntfy的url地址,例如 https://ntfy.sh": "ntfy的url地址,例如 https://ntfy.sh",
|
||||||
"ntfy的消息应用topic": "ntfy的消息应用topic",
|
"ntfy应用topic": "ntfy应用topic",
|
||||||
|
"ntfy应用token": "ntfy应用token,参考 https://docs.ntfy.sh/config/#access-tokens",
|
||||||
|
"ntfy应用用户名": "ntfy应用用户名,参考 https://docs.ntfy.sh/config/#users-and-roles",
|
||||||
|
"ntfy应用密码": "ntfy应用密码,参考 https://docs.ntfy.sh/config/#users-and-roles",
|
||||||
|
"ntfy用户动作": "ntfy用户动作,最多三个动作,参考 https://docs.ntfy.sh/publish/?h=actions#action-buttons",
|
||||||
"wxPusherBot的appToken": "wxPusherBot的appToken, 按照文档获取 https://wxpusher.zjiecode.com/docs/",
|
"wxPusherBot的appToken": "wxPusherBot的appToken, 按照文档获取 https://wxpusher.zjiecode.com/docs/",
|
||||||
"wxPusherBot的topicIds": "wxPusherBot的topicIds, topicIds 和 uids 至少配置一个才行",
|
"wxPusherBot的topicIds": "wxPusherBot的topicIds, topicIds 和 uids 至少配置一个才行",
|
||||||
"wxPusherBot的uids": "wxPusherBot的uids, topicIds 和 uids 至少配置一个才行",
|
"wxPusherBot的uids": "wxPusherBot的uids, topicIds 和 uids 至少配置一个才行",
|
||||||
@@ -506,6 +510,40 @@
|
|||||||
"强制打开可能会导致编辑器显示异常": "强制打开可能会导致编辑器显示异常",
|
"强制打开可能会导致编辑器显示异常": "强制打开可能会导致编辑器显示异常",
|
||||||
"确认离开": "确认离开",
|
"确认离开": "确认离开",
|
||||||
"当前文件未保存,确认离开吗": "当前文件未保存,确认离开吗",
|
"当前文件未保存,确认离开吗": "当前文件未保存,确认离开吗",
|
||||||
"收件邮箱地址,多个分号分隔,默认发送给发件邮箱地址": "收件邮箱地址,多个分号分隔,默认发送给发件邮箱地址"
|
"收件邮箱地址,多个分号分隔,默认发送给发件邮箱地址": "收件邮箱地址,多个分号分隔,默认发送给发件邮箱地址",
|
||||||
|
"选择备份模块": "选择备份模块",
|
||||||
|
"开始备份": "开始备份",
|
||||||
|
"基础数据": "基础数据",
|
||||||
|
"脚本文件": "脚本文件",
|
||||||
|
"日志文件": "日志文件",
|
||||||
|
"依赖缓存": "依赖缓存",
|
||||||
|
"远程脚本缓存": "远程脚本缓存",
|
||||||
|
"远程仓库缓存": "远程仓库缓存",
|
||||||
|
"SSH 文件缓存": "SSH 文件缓存",
|
||||||
|
"清除依赖缓存": "清除依赖缓存",
|
||||||
|
"清除成功": "清除成功",
|
||||||
|
"日志名称": "日志名称",
|
||||||
|
"自定义日志文件夹名称,用于区分不同任务的日志,留空则自动生成": "自定义日志文件夹名称,用于区分不同任务的日志,留空则自动生成",
|
||||||
|
"自定义日志文件夹名称,用于区分不同任务的日志,留空则自动生成。支持绝对路径如 /dev/null": "自定义日志文件夹名称,用于区分不同任务的日志,留空则自动生成。支持绝对路径如 /dev/null",
|
||||||
|
"自定义日志文件夹名称,用于区分不同任务的日志,留空则自动生成。支持 /dev/null 丢弃日志,其他绝对路径必须在日志目录内": "自定义日志文件夹名称,用于区分不同任务的日志,留空则自动生成。支持 /dev/null 丢弃日志,其他绝对路径必须在日志目录内",
|
||||||
|
"请输入自定义日志文件夹名称": "请输入自定义日志文件夹名称",
|
||||||
|
"请输入自定义日志文件夹名称或绝对路径": "请输入自定义日志文件夹名称或绝对路径",
|
||||||
|
"请输入自定义日志文件夹名称或 /dev/null": "请输入自定义日志文件夹名称或 /dev/null",
|
||||||
|
"日志名称只能包含字母、数字、下划线和连字符": "日志名称只能包含字母、数字、下划线和连字符",
|
||||||
|
"日志名称不能超过100个字符": "日志名称不能超过100个字符",
|
||||||
|
"用户管理": "用户管理",
|
||||||
|
"用户名": "用户名",
|
||||||
|
"密码": "密码",
|
||||||
|
"角色": "角色",
|
||||||
|
"管理员": "管理员",
|
||||||
|
"普通用户": "普通用户",
|
||||||
|
"启用": "启用",
|
||||||
|
"禁用": "禁用",
|
||||||
|
"创建时间": "创建时间",
|
||||||
|
"确认删除选中的用户吗": "确认删除选中的用户吗",
|
||||||
|
"请输入用户名": "请输入用户名",
|
||||||
|
"请输入密码": "请输入密码",
|
||||||
|
"密码长度至少为6位": "密码长度至少为6位",
|
||||||
|
"新增用户": "新增用户",
|
||||||
|
"编辑用户": "编辑用户"
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -56,12 +56,10 @@ interface LogItem {
|
|||||||
const CronDetailModal = ({
|
const CronDetailModal = ({
|
||||||
cron = {},
|
cron = {},
|
||||||
handleCancel,
|
handleCancel,
|
||||||
visible,
|
|
||||||
theme,
|
theme,
|
||||||
isPhone,
|
isPhone,
|
||||||
}: {
|
}: {
|
||||||
cron?: any;
|
cron?: any;
|
||||||
visible: boolean;
|
|
||||||
handleCancel: (needUpdate?: boolean) => void;
|
handleCancel: (needUpdate?: boolean) => void;
|
||||||
theme: string;
|
theme: string;
|
||||||
isPhone: boolean;
|
isPhone: boolean;
|
||||||
@@ -440,7 +438,7 @@ const CronDetailModal = ({
|
|||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
centered
|
centered
|
||||||
open={visible}
|
open={true}
|
||||||
forceRender
|
forceRender
|
||||||
footer={false}
|
footer={false}
|
||||||
onCancel={() => handleCancel()}
|
onCancel={() => handleCancel()}
|
||||||
@@ -559,15 +557,16 @@ const CronDetailModal = ({
|
|||||||
{contentList[activeTabKey]}
|
{contentList[activeTabKey]}
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
<CronLogModal
|
{isLogModalVisible && (
|
||||||
visible={isLogModalVisible}
|
<CronLogModal
|
||||||
handleCancel={() => {
|
handleCancel={() => {
|
||||||
setIsLogModalVisible(false);
|
setIsLogModalVisible(false);
|
||||||
}}
|
}}
|
||||||
cron={cron}
|
cron={cron}
|
||||||
data={log}
|
data={log}
|
||||||
logUrl={logUrl}
|
logUrl={logUrl}
|
||||||
/>
|
/>
|
||||||
|
)}
|
||||||
</Modal>
|
</Modal>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
+52
-49
@@ -1037,55 +1037,58 @@ const Crontab = () => {
|
|||||||
components={isPhone || pageConf.size < 50 ? undefined : vt}
|
components={isPhone || pageConf.size < 50 ? undefined : vt}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<CronLogModal
|
{isLogModalVisible && (
|
||||||
visible={isLogModalVisible}
|
<CronLogModal
|
||||||
handleCancel={() => {
|
handleCancel={() => {
|
||||||
getCronDetail(logCron);
|
getCronDetail(logCron);
|
||||||
setIsLogModalVisible(false);
|
setIsLogModalVisible(false);
|
||||||
}}
|
}}
|
||||||
cron={logCron}
|
cron={logCron}
|
||||||
/>
|
/>
|
||||||
<CronModal
|
)}
|
||||||
visible={isModalVisible}
|
{isModalVisible && (
|
||||||
handleCancel={handleCancel}
|
<CronModal handleCancel={handleCancel} cron={editedCron} />
|
||||||
cron={editedCron}
|
)}
|
||||||
/>
|
{isLabelModalVisible && (
|
||||||
<CronLabelModal
|
<CronLabelModal
|
||||||
visible={isLabelModalVisible}
|
handleCancel={(needUpdate?: boolean) => {
|
||||||
handleCancel={(needUpdate?: boolean) => {
|
setIsLabelModalVisible(false);
|
||||||
setIsLabelModalVisible(false);
|
if (needUpdate) {
|
||||||
if (needUpdate) {
|
getCrons();
|
||||||
getCrons();
|
}
|
||||||
}
|
}}
|
||||||
}}
|
ids={selectedRowIds}
|
||||||
ids={selectedRowIds}
|
/>
|
||||||
/>
|
)}
|
||||||
<CronDetailModal
|
{isDetailModalVisible && (
|
||||||
visible={isDetailModalVisible}
|
<CronDetailModal
|
||||||
handleCancel={() => {
|
handleCancel={() => {
|
||||||
setIsDetailModalVisible(false);
|
setIsDetailModalVisible(false);
|
||||||
}}
|
}}
|
||||||
cron={detailCron}
|
cron={detailCron}
|
||||||
theme={theme}
|
theme={theme}
|
||||||
isPhone={isPhone}
|
isPhone={isPhone}
|
||||||
/>
|
/>
|
||||||
<ViewCreateModal
|
)}
|
||||||
visible={isCreateViewModalVisible}
|
{isCreateViewModalVisible && (
|
||||||
handleCancel={(data) => {
|
<ViewCreateModal
|
||||||
setIsCreateViewModalVisible(false);
|
handleCancel={(data) => {
|
||||||
getCronViews();
|
setIsCreateViewModalVisible(false);
|
||||||
}}
|
getCronViews();
|
||||||
/>
|
}}
|
||||||
<ViewManageModal
|
/>
|
||||||
cronViews={cronViews}
|
)}
|
||||||
visible={isViewManageModalVisible}
|
{isViewManageModalVisible && (
|
||||||
handleCancel={() => {
|
<ViewManageModal
|
||||||
setIsViewManageModalVisible(false);
|
cronViews={cronViews}
|
||||||
}}
|
handleCancel={() => {
|
||||||
cronViewChange={(data) => {
|
setIsViewManageModalVisible(false);
|
||||||
getCronViews();
|
}}
|
||||||
}}
|
cronViewChange={(data) => {
|
||||||
/>
|
getCronViews();
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
</PageContainer>
|
</PageContainer>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import intl from 'react-intl-universal';
|
import intl from "react-intl-universal";
|
||||||
import React, { useEffect, useRef, useState } from 'react';
|
import React, { useEffect, useRef, useState } from "react";
|
||||||
import {
|
import {
|
||||||
Modal,
|
Modal,
|
||||||
message,
|
message,
|
||||||
@@ -8,34 +8,32 @@ import {
|
|||||||
Statistic,
|
Statistic,
|
||||||
Button,
|
Button,
|
||||||
Typography,
|
Typography,
|
||||||
} from 'antd';
|
} from "antd";
|
||||||
import { request } from '@/utils/http';
|
import { request } from "@/utils/http";
|
||||||
import config from '@/utils/config';
|
import config from "@/utils/config";
|
||||||
import {
|
import {
|
||||||
Loading3QuartersOutlined,
|
Loading3QuartersOutlined,
|
||||||
CheckCircleOutlined,
|
CheckCircleOutlined,
|
||||||
} from '@ant-design/icons';
|
} from "@ant-design/icons";
|
||||||
import { PageLoading } from '@ant-design/pro-layout';
|
import { PageLoading } from "@ant-design/pro-layout";
|
||||||
import { logEnded } from '@/utils';
|
import { logEnded } from "@/utils";
|
||||||
import { CrontabStatus } from './type';
|
import { CrontabStatus } from "./type";
|
||||||
import Ansi from 'ansi-to-react';
|
import Ansi from "ansi-to-react";
|
||||||
|
|
||||||
const { Countdown } = Statistic;
|
const { Countdown } = Statistic;
|
||||||
|
|
||||||
const CronLogModal = ({
|
const CronLogModal = ({
|
||||||
cron,
|
cron,
|
||||||
handleCancel,
|
handleCancel,
|
||||||
visible,
|
|
||||||
data,
|
data,
|
||||||
logUrl,
|
logUrl,
|
||||||
}: {
|
}: {
|
||||||
cron?: any;
|
cron?: any;
|
||||||
visible: boolean;
|
|
||||||
handleCancel: () => void;
|
handleCancel: () => void;
|
||||||
data?: string;
|
data?: string;
|
||||||
logUrl?: string;
|
logUrl?: string;
|
||||||
}) => {
|
}) => {
|
||||||
const [value, setValue] = useState<string>(intl.get('启动中...'));
|
const [value, setValue] = useState<string>(intl.get("启动中..."));
|
||||||
const [loading, setLoading] = useState<any>(true);
|
const [loading, setLoading] = useState<any>(true);
|
||||||
const [executing, setExecuting] = useState<any>(true);
|
const [executing, setExecuting] = useState<any>(true);
|
||||||
const [isPhone, setIsPhone] = useState(false);
|
const [isPhone, setIsPhone] = useState(false);
|
||||||
@@ -51,15 +49,15 @@ const CronLogModal = ({
|
|||||||
.then(({ code, data }) => {
|
.then(({ code, data }) => {
|
||||||
if (
|
if (
|
||||||
code === 200 &&
|
code === 200 &&
|
||||||
localStorage.getItem('logCron') === uniqPath &&
|
localStorage.getItem("logCron") === uniqPath &&
|
||||||
data !== value
|
data !== value
|
||||||
) {
|
) {
|
||||||
const log = data as string;
|
const log = data as string;
|
||||||
setValue(log || intl.get('暂无日志'));
|
setValue(log || intl.get("暂无日志"));
|
||||||
const hasNext = Boolean(
|
const hasNext = Boolean(
|
||||||
log && !logEnded(log) && !log.includes('任务未运行'),
|
log && !logEnded(log) && !log.includes("日志不存在") && !log.includes("日志设置为忽略"),
|
||||||
);
|
);
|
||||||
if (!hasNext && !logEnded(value) && value !== intl.get('启动中...')) {
|
if (!hasNext && !logEnded(value) && value !== intl.get("启动中...")) {
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
autoScroll();
|
autoScroll();
|
||||||
});
|
});
|
||||||
@@ -87,13 +85,13 @@ const CronLogModal = ({
|
|||||||
|
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
document
|
document
|
||||||
.querySelector('#log-flag')!
|
.querySelector("#log-flag")
|
||||||
.scrollIntoView({ behavior: 'smooth' });
|
?.scrollIntoView({ behavior: "smooth" });
|
||||||
}, 600);
|
}, 600);
|
||||||
};
|
};
|
||||||
|
|
||||||
const cancel = () => {
|
const cancel = () => {
|
||||||
localStorage.removeItem('logCron');
|
localStorage.removeItem("logCron");
|
||||||
handleCancel();
|
handleCancel();
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -109,7 +107,7 @@ const CronLogModal = ({
|
|||||||
|
|
||||||
const titleElement = () => {
|
const titleElement = () => {
|
||||||
return (
|
return (
|
||||||
<div style={{ display: 'flex', alignItems: 'center' }}>
|
<div style={{ display: "flex", alignItems: "center" }}>
|
||||||
{(executing || loading) && <Loading3QuartersOutlined spin />}
|
{(executing || loading) && <Loading3QuartersOutlined spin />}
|
||||||
{!executing && !loading && <CheckCircleOutlined />}
|
{!executing && !loading && <CheckCircleOutlined />}
|
||||||
<Typography.Text ellipsis={true} style={{ marginLeft: 5 }}>
|
<Typography.Text ellipsis={true} style={{ marginLeft: 5 }}>
|
||||||
@@ -120,11 +118,10 @@ const CronLogModal = ({
|
|||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (cron && cron.id && visible) {
|
if (cron && cron.id) {
|
||||||
getCronLog(true);
|
getCronLog(true);
|
||||||
scrollInfoRef.current.down = true;
|
|
||||||
}
|
}
|
||||||
}, [cron, visible]);
|
}, [cron]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (data) {
|
if (data) {
|
||||||
@@ -139,7 +136,7 @@ const CronLogModal = ({
|
|||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
title={titleElement()}
|
title={titleElement()}
|
||||||
open={visible}
|
open={true}
|
||||||
centered
|
centered
|
||||||
className="log-modal"
|
className="log-modal"
|
||||||
forceRender
|
forceRender
|
||||||
@@ -147,7 +144,7 @@ const CronLogModal = ({
|
|||||||
onCancel={() => cancel()}
|
onCancel={() => cancel()}
|
||||||
footer={[
|
footer={[
|
||||||
<Button type="primary" onClick={() => cancel()}>
|
<Button type="primary" onClick={() => cancel()}>
|
||||||
{intl.get('知道了')}
|
{intl.get("知道了")}
|
||||||
</Button>,
|
</Button>,
|
||||||
]}
|
]}
|
||||||
>
|
>
|
||||||
@@ -159,9 +156,9 @@ const CronLogModal = ({
|
|||||||
style={
|
style={
|
||||||
isPhone
|
isPhone
|
||||||
? {
|
? {
|
||||||
fontFamily: 'Source Code Pro',
|
fontFamily: "Source Code Pro",
|
||||||
zoom: 0.83,
|
zoom: 0.83,
|
||||||
}
|
}
|
||||||
: {}
|
: {}
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
|
|||||||
+31
-16
@@ -12,10 +12,8 @@ import { ScheduleType } from './type';
|
|||||||
const CronModal = ({
|
const CronModal = ({
|
||||||
cron,
|
cron,
|
||||||
handleCancel,
|
handleCancel,
|
||||||
visible,
|
|
||||||
}: {
|
}: {
|
||||||
cron?: any;
|
cron?: any;
|
||||||
visible: boolean;
|
|
||||||
handleCancel: (needUpdate?: boolean) => void;
|
handleCancel: (needUpdate?: boolean) => void;
|
||||||
}) => {
|
}) => {
|
||||||
const [form] = Form.useForm();
|
const [form] = Form.useForm();
|
||||||
@@ -58,11 +56,6 @@ const CronModal = ({
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
form.resetFields();
|
|
||||||
setScheduleType(getScheduleType(cron?.schedule));
|
|
||||||
}, [cron, visible]);
|
|
||||||
|
|
||||||
const handleScheduleTypeChange = (type: ScheduleType) => {
|
const handleScheduleTypeChange = (type: ScheduleType) => {
|
||||||
setScheduleType(type);
|
setScheduleType(type);
|
||||||
form.setFieldValue('schedule', '');
|
form.setFieldValue('schedule', '');
|
||||||
@@ -146,7 +139,7 @@ const CronModal = ({
|
|||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
title={cron?.id ? intl.get('编辑任务') : intl.get('创建任务')}
|
title={cron?.id ? intl.get('编辑任务') : intl.get('创建任务')}
|
||||||
open={visible}
|
open={true}
|
||||||
forceRender
|
forceRender
|
||||||
centered
|
centered
|
||||||
maskClosable={false}
|
maskClosable={false}
|
||||||
@@ -187,6 +180,35 @@ const CronModal = ({
|
|||||||
<Form.Item name="labels" label={intl.get('标签')}>
|
<Form.Item name="labels" label={intl.get('标签')}>
|
||||||
<EditableTagGroup />
|
<EditableTagGroup />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
|
<Form.Item
|
||||||
|
name="log_name"
|
||||||
|
label={intl.get('日志名称')}
|
||||||
|
tooltip={intl.get(
|
||||||
|
'自定义日志文件夹名称,用于区分不同任务的日志,留空则自动生成。支持 /dev/null 丢弃日志,其他绝对路径必须在日志目录内',
|
||||||
|
)}
|
||||||
|
rules={[
|
||||||
|
{
|
||||||
|
validator: (_, value) => {
|
||||||
|
if (!value) return Promise.resolve();
|
||||||
|
if (value === '/dev/null') return Promise.resolve();
|
||||||
|
if (value.length > 100) {
|
||||||
|
return Promise.reject(intl.get('日志名称不能超过100个字符'));
|
||||||
|
}
|
||||||
|
if (!/^(?!.*(?:^|\/)\.{1,2}(?:\/|$))(?:\/)?(?:[\w.-]+\/)*[\w.-]+\/?$/.test(value)) {
|
||||||
|
return Promise.reject(
|
||||||
|
intl.get('日志名称只能包含字母、数字、下划线和连字符'),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return Promise.resolve();
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
<Input
|
||||||
|
placeholder={intl.get('请输入自定义日志文件夹名称或 /dev/null')}
|
||||||
|
maxLength={200}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
<Form.Item
|
<Form.Item
|
||||||
name="task_before"
|
name="task_before"
|
||||||
label={intl.get('执行前')}
|
label={intl.get('执行前')}
|
||||||
@@ -251,10 +273,8 @@ const CronModal = ({
|
|||||||
const CronLabelModal = ({
|
const CronLabelModal = ({
|
||||||
ids,
|
ids,
|
||||||
handleCancel,
|
handleCancel,
|
||||||
visible,
|
|
||||||
}: {
|
}: {
|
||||||
ids: Array<string>;
|
ids: Array<string>;
|
||||||
visible: boolean;
|
|
||||||
handleCancel: (needUpdate?: boolean) => void;
|
handleCancel: (needUpdate?: boolean) => void;
|
||||||
}) => {
|
}) => {
|
||||||
const [form] = Form.useForm();
|
const [form] = Form.useForm();
|
||||||
@@ -290,10 +310,6 @@ const CronLabelModal = ({
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
form.resetFields();
|
|
||||||
}, [ids, visible]);
|
|
||||||
|
|
||||||
const buttons = [
|
const buttons = [
|
||||||
<Button onClick={() => handleCancel(false)}>{intl.get('取消')}</Button>,
|
<Button onClick={() => handleCancel(false)}>{intl.get('取消')}</Button>,
|
||||||
<Button type="primary" danger onClick={() => update('delete')}>
|
<Button type="primary" danger onClick={() => update('delete')}>
|
||||||
@@ -307,7 +323,7 @@ const CronLabelModal = ({
|
|||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
title={intl.get('批量修改标签')}
|
title={intl.get('批量修改标签')}
|
||||||
open={visible}
|
open={true}
|
||||||
footer={buttons}
|
footer={buttons}
|
||||||
centered
|
centered
|
||||||
maskClosable={false}
|
maskClosable={false}
|
||||||
@@ -325,4 +341,3 @@ const CronLabelModal = ({
|
|||||||
};
|
};
|
||||||
|
|
||||||
export { CronLabelModal, CronModal as default };
|
export { CronLabelModal, CronModal as default };
|
||||||
|
|
||||||
|
|||||||
@@ -56,10 +56,8 @@ enum ViewFilterRelation {
|
|||||||
const ViewCreateModal = ({
|
const ViewCreateModal = ({
|
||||||
view,
|
view,
|
||||||
handleCancel,
|
handleCancel,
|
||||||
visible,
|
|
||||||
}: {
|
}: {
|
||||||
view?: any;
|
view?: any;
|
||||||
visible: boolean;
|
|
||||||
handleCancel: (param?: any) => void;
|
handleCancel: (param?: any) => void;
|
||||||
}) => {
|
}) => {
|
||||||
const [form] = Form.useForm();
|
const [form] = Form.useForm();
|
||||||
@@ -101,17 +99,6 @@ const ViewCreateModal = ({
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!view) {
|
|
||||||
form.resetFields();
|
|
||||||
}
|
|
||||||
form.setFieldsValue(
|
|
||||||
view || {
|
|
||||||
filters: [{ property: 'command' }],
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}, [view, visible]);
|
|
||||||
|
|
||||||
const OperationElement = ({ name, ...others }: { name: number }) => {
|
const OperationElement = ({ name, ...others }: { name: number }) => {
|
||||||
const property = form.getFieldValue(['filters', name, 'property']);
|
const property = form.getFieldValue(['filters', name, 'property']);
|
||||||
return (
|
return (
|
||||||
@@ -172,7 +159,7 @@ const ViewCreateModal = ({
|
|||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
title={view ? intl.get('编辑视图') : intl.get('创建视图')}
|
title={view ? intl.get('编辑视图') : intl.get('创建视图')}
|
||||||
open={visible}
|
open={true}
|
||||||
forceRender
|
forceRender
|
||||||
width={580}
|
width={580}
|
||||||
centered
|
centered
|
||||||
@@ -190,7 +177,16 @@ const ViewCreateModal = ({
|
|||||||
onCancel={() => handleCancel()}
|
onCancel={() => handleCancel()}
|
||||||
confirmLoading={loading}
|
confirmLoading={loading}
|
||||||
>
|
>
|
||||||
<Form form={form} layout="vertical" name="env_modal">
|
<Form
|
||||||
|
form={form}
|
||||||
|
layout="vertical"
|
||||||
|
initialValues={
|
||||||
|
view || {
|
||||||
|
filters: [{ property: 'command' }],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
name="env_modal"
|
||||||
|
>
|
||||||
<Form.Item
|
<Form.Item
|
||||||
name="name"
|
name="name"
|
||||||
label={intl.get('视图名称')}
|
label={intl.get('视图名称')}
|
||||||
|
|||||||
@@ -68,11 +68,9 @@ const DragableBodyRow = ({
|
|||||||
const ViewManageModal = ({
|
const ViewManageModal = ({
|
||||||
cronViews,
|
cronViews,
|
||||||
handleCancel,
|
handleCancel,
|
||||||
visible,
|
|
||||||
cronViewChange,
|
cronViewChange,
|
||||||
}: {
|
}: {
|
||||||
cronViews: any[];
|
cronViews: any[];
|
||||||
visible: boolean;
|
|
||||||
handleCancel: () => void;
|
handleCancel: () => void;
|
||||||
cronViewChange: (data?: any) => void;
|
cronViewChange: (data?: any) => void;
|
||||||
}) => {
|
}) => {
|
||||||
@@ -218,7 +216,7 @@ const ViewManageModal = ({
|
|||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
title={intl.get('视图管理')}
|
title={intl.get('视图管理')}
|
||||||
open={visible}
|
open={true}
|
||||||
centered
|
centered
|
||||||
width={620}
|
width={620}
|
||||||
onCancel={() => handleCancel()}
|
onCancel={() => handleCancel()}
|
||||||
@@ -263,14 +261,15 @@ const ViewManageModal = ({
|
|||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
</DndProvider>
|
</DndProvider>
|
||||||
<ViewCreateModal
|
{isCreateViewModalVisible && (
|
||||||
view={editedView}
|
<ViewCreateModal
|
||||||
visible={isCreateViewModalVisible}
|
view={editedView}
|
||||||
handleCancel={(data) => {
|
handleCancel={(data) => {
|
||||||
setIsCreateViewModalVisible(false);
|
setIsCreateViewModalVisible(false);
|
||||||
cronViewChange(data);
|
cronViewChange(data);
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
)}
|
||||||
</Modal>
|
</Modal>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -618,15 +618,15 @@ const Dependence = () => {
|
|||||||
]}
|
]}
|
||||||
/>
|
/>
|
||||||
{children}
|
{children}
|
||||||
<DependenceModal
|
{isModalVisible && (
|
||||||
visible={isModalVisible}
|
<DependenceModal
|
||||||
handleCancel={handleCancel}
|
handleCancel={handleCancel}
|
||||||
dependence={editedDependence}
|
dependence={editedDependence}
|
||||||
defaultType={type}
|
defaultType={type}
|
||||||
/>
|
/>
|
||||||
{logDependence && (
|
)}
|
||||||
|
{logDependence && isLogModalVisible && (
|
||||||
<DependenceLogModal
|
<DependenceLogModal
|
||||||
visible={isLogModalVisible}
|
|
||||||
handleCancel={(needRemove?: boolean) => {
|
handleCancel={(needRemove?: boolean) => {
|
||||||
setIsLogModalVisible(false);
|
setIsLogModalVisible(false);
|
||||||
if (needRemove) {
|
if (needRemove) {
|
||||||
|
|||||||
@@ -15,10 +15,8 @@ import { Status } from './type';
|
|||||||
const DependenceLogModal = ({
|
const DependenceLogModal = ({
|
||||||
dependence,
|
dependence,
|
||||||
handleCancel,
|
handleCancel,
|
||||||
visible,
|
|
||||||
}: {
|
}: {
|
||||||
dependence?: any;
|
dependence?: any;
|
||||||
visible: boolean;
|
|
||||||
handleCancel: (needRemove?: boolean) => void;
|
handleCancel: (needRemove?: boolean) => void;
|
||||||
}) => {
|
}) => {
|
||||||
const [value, setValue] = useState<string>('');
|
const [value, setValue] = useState<string>('');
|
||||||
@@ -128,7 +126,7 @@ const DependenceLogModal = ({
|
|||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
title={titleElement()}
|
title={titleElement()}
|
||||||
open={visible}
|
open={true}
|
||||||
centered
|
centered
|
||||||
className="log-modal"
|
className="log-modal"
|
||||||
forceRender
|
forceRender
|
||||||
|
|||||||
@@ -14,11 +14,9 @@ enum DependenceTypes {
|
|||||||
const DependenceModal = ({
|
const DependenceModal = ({
|
||||||
dependence,
|
dependence,
|
||||||
handleCancel,
|
handleCancel,
|
||||||
visible,
|
|
||||||
defaultType,
|
defaultType,
|
||||||
}: {
|
}: {
|
||||||
dependence?: any;
|
dependence?: any;
|
||||||
visible: boolean;
|
|
||||||
handleCancel: (cks?: any[]) => void;
|
handleCancel: (cks?: any[]) => void;
|
||||||
defaultType: string;
|
defaultType: string;
|
||||||
}) => {
|
}) => {
|
||||||
@@ -61,14 +59,10 @@ const DependenceModal = ({
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
form.resetFields();
|
|
||||||
}, [dependence, visible]);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
title={dependence ? intl.get('编辑依赖') : intl.get('创建依赖')}
|
title={dependence ? intl.get('编辑依赖') : intl.get('创建依赖')}
|
||||||
open={visible}
|
open={true}
|
||||||
forceRender
|
forceRender
|
||||||
centered
|
centered
|
||||||
maskClosable={false}
|
maskClosable={false}
|
||||||
|
|||||||
Vendored
+1
-7
@@ -7,10 +7,8 @@ import config from '@/utils/config';
|
|||||||
const EditNameModal = ({
|
const EditNameModal = ({
|
||||||
ids,
|
ids,
|
||||||
handleCancel,
|
handleCancel,
|
||||||
visible,
|
|
||||||
}: {
|
}: {
|
||||||
ids?: string[];
|
ids?: string[];
|
||||||
visible: boolean;
|
|
||||||
handleCancel: () => void;
|
handleCancel: () => void;
|
||||||
}) => {
|
}) => {
|
||||||
const [form] = Form.useForm();
|
const [form] = Form.useForm();
|
||||||
@@ -34,14 +32,10 @@ const EditNameModal = ({
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
form.resetFields();
|
|
||||||
}, [ids, visible]);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
title={intl.get('修改环境变量名称')}
|
title={intl.get('修改环境变量名称')}
|
||||||
open={visible}
|
open={true}
|
||||||
forceRender
|
forceRender
|
||||||
centered
|
centered
|
||||||
maskClosable={false}
|
maskClosable={false}
|
||||||
|
|||||||
Vendored
+120
-46
@@ -1,47 +1,42 @@
|
|||||||
import intl from 'react-intl-universal';
|
import useTableScrollHeight from '@/hooks/useTableScrollHeight';
|
||||||
import React, {
|
import { SharedContext } from '@/layouts';
|
||||||
useCallback,
|
import config from '@/utils/config';
|
||||||
useRef,
|
import { request } from '@/utils/http';
|
||||||
useState,
|
import { exportJson } from '@/utils/index';
|
||||||
useEffect,
|
|
||||||
useMemo,
|
|
||||||
} from 'react';
|
|
||||||
import {
|
import {
|
||||||
Button,
|
|
||||||
message,
|
|
||||||
Modal,
|
|
||||||
Table,
|
|
||||||
Tag,
|
|
||||||
Space,
|
|
||||||
Typography,
|
|
||||||
Tooltip,
|
|
||||||
Input,
|
|
||||||
UploadProps,
|
|
||||||
Upload,
|
|
||||||
} from 'antd';
|
|
||||||
import {
|
|
||||||
EditOutlined,
|
|
||||||
DeleteOutlined,
|
|
||||||
SyncOutlined,
|
|
||||||
CheckCircleOutlined,
|
CheckCircleOutlined,
|
||||||
|
DeleteOutlined,
|
||||||
|
EditOutlined,
|
||||||
|
PushpinFilled,
|
||||||
|
PushpinOutlined,
|
||||||
StopOutlined,
|
StopOutlined,
|
||||||
UploadOutlined,
|
UploadOutlined,
|
||||||
} from '@ant-design/icons';
|
} from '@ant-design/icons';
|
||||||
import config from '@/utils/config';
|
|
||||||
import { PageContainer } from '@ant-design/pro-layout';
|
import { PageContainer } from '@ant-design/pro-layout';
|
||||||
import { request } from '@/utils/http';
|
import { useOutletContext } from '@umijs/max';
|
||||||
import EnvModal from './modal';
|
import {
|
||||||
import EditNameModal from './editNameModal';
|
Button,
|
||||||
|
Input,
|
||||||
|
Modal,
|
||||||
|
Space,
|
||||||
|
Table,
|
||||||
|
Tag,
|
||||||
|
Tooltip,
|
||||||
|
Typography,
|
||||||
|
Upload,
|
||||||
|
UploadProps,
|
||||||
|
message,
|
||||||
|
} from 'antd';
|
||||||
|
import dayjs from 'dayjs';
|
||||||
|
import React, { useCallback, useEffect, useRef, useState } from 'react';
|
||||||
import { DndProvider, useDrag, useDrop } from 'react-dnd';
|
import { DndProvider, useDrag, useDrop } from 'react-dnd';
|
||||||
import { HTML5Backend } from 'react-dnd-html5-backend';
|
import { HTML5Backend } from 'react-dnd-html5-backend';
|
||||||
import './index.less';
|
import intl from 'react-intl-universal';
|
||||||
import { exportJson } from '@/utils/index';
|
|
||||||
import { useOutletContext } from '@umijs/max';
|
|
||||||
import { SharedContext } from '@/layouts';
|
|
||||||
import useTableScrollHeight from '@/hooks/useTableScrollHeight';
|
|
||||||
import Copy from '../../components/copy';
|
|
||||||
import { useVT } from 'virtualizedtableforantd4';
|
import { useVT } from 'virtualizedtableforantd4';
|
||||||
import dayjs from 'dayjs';
|
import Copy from '../../components/copy';
|
||||||
|
import EditNameModal from './editNameModal';
|
||||||
|
import './index.less';
|
||||||
|
import EnvModal from './modal';
|
||||||
|
|
||||||
const { Paragraph } = Typography;
|
const { Paragraph } = Typography;
|
||||||
const { Search } = Input;
|
const { Search } = Input;
|
||||||
@@ -59,11 +54,15 @@ enum StatusColor {
|
|||||||
enum OperationName {
|
enum OperationName {
|
||||||
'启用',
|
'启用',
|
||||||
'禁用',
|
'禁用',
|
||||||
|
'置顶',
|
||||||
|
'取消置顶',
|
||||||
}
|
}
|
||||||
|
|
||||||
enum OperationPath {
|
enum OperationPath {
|
||||||
'enable',
|
'enable',
|
||||||
'disable',
|
'disable',
|
||||||
|
'pin',
|
||||||
|
'unpin',
|
||||||
}
|
}
|
||||||
|
|
||||||
const type = 'DragableBodyRow';
|
const type = 'DragableBodyRow';
|
||||||
@@ -181,7 +180,7 @@ const Env = () => {
|
|||||||
{
|
{
|
||||||
title: intl.get('操作'),
|
title: intl.get('操作'),
|
||||||
key: 'action',
|
key: 'action',
|
||||||
width: 120,
|
width: 160,
|
||||||
render: (text: string, record: any, index: number) => {
|
render: (text: string, record: any, index: number) => {
|
||||||
const isPc = !isPhone;
|
const isPc = !isPhone;
|
||||||
return (
|
return (
|
||||||
@@ -208,6 +207,23 @@ const Env = () => {
|
|||||||
)}
|
)}
|
||||||
</a>
|
</a>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
|
<Tooltip
|
||||||
|
title={
|
||||||
|
isPc
|
||||||
|
? record.isPinned === 1
|
||||||
|
? intl.get('取消置顶')
|
||||||
|
: intl.get('置顶')
|
||||||
|
: ''
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<a onClick={() => pinOrUnpinEnv(record, index)}>
|
||||||
|
{record.isPinned === 1 ? (
|
||||||
|
<PushpinFilled />
|
||||||
|
) : (
|
||||||
|
<PushpinOutlined />
|
||||||
|
)}
|
||||||
|
</a>
|
||||||
|
</Tooltip>
|
||||||
<Tooltip title={isPc ? intl.get('删除') : ''}>
|
<Tooltip title={isPc ? intl.get('删除') : ''}>
|
||||||
<a onClick={() => deleteEnv(record, index)}>
|
<a onClick={() => deleteEnv(record, index)}>
|
||||||
<DeleteOutlined />
|
<DeleteOutlined />
|
||||||
@@ -305,6 +321,51 @@ const Env = () => {
|
|||||||
setIsModalVisible(true);
|
setIsModalVisible(true);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const pinOrUnpinEnv = (record: any, index: number) => {
|
||||||
|
Modal.confirm({
|
||||||
|
title: `确认${
|
||||||
|
record.isPinned === 1 ? intl.get('取消置顶') : intl.get('置顶')
|
||||||
|
}`,
|
||||||
|
content: (
|
||||||
|
<>
|
||||||
|
{intl.get('确认')}
|
||||||
|
{record.isPinned === 1 ? intl.get('取消置顶') : intl.get('置顶')}
|
||||||
|
Env{' '}
|
||||||
|
<Paragraph
|
||||||
|
style={{ wordBreak: 'break-all', display: 'inline' }}
|
||||||
|
ellipsis={{ rows: 6, expandable: true }}
|
||||||
|
type="warning"
|
||||||
|
copyable
|
||||||
|
>
|
||||||
|
{record.name}: {record.value}
|
||||||
|
</Paragraph>{' '}
|
||||||
|
{intl.get('吗')}
|
||||||
|
</>
|
||||||
|
),
|
||||||
|
onOk() {
|
||||||
|
request
|
||||||
|
.put(
|
||||||
|
`${config.apiPrefix}envs/${
|
||||||
|
record.isPinned === 1 ? 'unpin' : 'pin'
|
||||||
|
}`,
|
||||||
|
[record.id],
|
||||||
|
)
|
||||||
|
.then(({ code, data }) => {
|
||||||
|
if (code === 200) {
|
||||||
|
message.success(
|
||||||
|
`${
|
||||||
|
record.isPinned === 1
|
||||||
|
? intl.get('取消置顶')
|
||||||
|
: intl.get('置顶')
|
||||||
|
}${intl.get('成功')}`,
|
||||||
|
);
|
||||||
|
getEnvs();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
},
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
const deleteEnv = (record: any, index: number) => {
|
const deleteEnv = (record: any, index: number) => {
|
||||||
Modal.confirm({
|
Modal.confirm({
|
||||||
title: intl.get('确认删除'),
|
title: intl.get('确认删除'),
|
||||||
@@ -589,6 +650,20 @@ const Env = () => {
|
|||||||
>
|
>
|
||||||
{intl.get('批量禁用')}
|
{intl.get('批量禁用')}
|
||||||
</Button>
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="primary"
|
||||||
|
onClick={() => operateEnvs(2)}
|
||||||
|
style={{ marginLeft: 8, marginBottom: 5 }}
|
||||||
|
>
|
||||||
|
{intl.get('批量置顶')}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="primary"
|
||||||
|
onClick={() => operateEnvs(3)}
|
||||||
|
style={{ marginLeft: 8, marginRight: 8 }}
|
||||||
|
>
|
||||||
|
{intl.get('批量取消置顶')}
|
||||||
|
</Button>
|
||||||
<span style={{ marginLeft: 8 }}>
|
<span style={{ marginLeft: 8 }}>
|
||||||
{intl.get('已选择')}
|
{intl.get('已选择')}
|
||||||
<a>{selectedRowIds?.length}</a>
|
<a>{selectedRowIds?.length}</a>
|
||||||
@@ -616,16 +691,15 @@ const Env = () => {
|
|||||||
/>
|
/>
|
||||||
</DndProvider>
|
</DndProvider>
|
||||||
</div>
|
</div>
|
||||||
<EnvModal
|
{isModalVisible && (
|
||||||
visible={isModalVisible}
|
<EnvModal handleCancel={handleCancel} env={editedEnv} />
|
||||||
handleCancel={handleCancel}
|
)}
|
||||||
env={editedEnv}
|
{isEditNameModalVisible && (
|
||||||
/>
|
<EditNameModal
|
||||||
<EditNameModal
|
handleCancel={handleEditNameCancel}
|
||||||
visible={isEditNameModalVisible}
|
ids={selectedRowIds}
|
||||||
handleCancel={handleEditNameCancel}
|
/>
|
||||||
ids={selectedRowIds}
|
)}
|
||||||
/>
|
|
||||||
</PageContainer>
|
</PageContainer>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
Vendored
+1
-7
@@ -7,10 +7,8 @@ import config from '@/utils/config';
|
|||||||
const EnvModal = ({
|
const EnvModal = ({
|
||||||
env,
|
env,
|
||||||
handleCancel,
|
handleCancel,
|
||||||
visible,
|
|
||||||
}: {
|
}: {
|
||||||
env?: any;
|
env?: any;
|
||||||
visible: boolean;
|
|
||||||
handleCancel: (cks?: any[]) => void;
|
handleCancel: (cks?: any[]) => void;
|
||||||
}) => {
|
}) => {
|
||||||
const [form] = Form.useForm();
|
const [form] = Form.useForm();
|
||||||
@@ -55,14 +53,10 @@ const EnvModal = ({
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
form.resetFields();
|
|
||||||
}, [env, visible]);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
title={env ? intl.get('编辑变量') : intl.get('创建变量')}
|
title={env ? intl.get('编辑变量') : intl.get('创建变量')}
|
||||||
open={visible}
|
open={true}
|
||||||
forceRender
|
forceRender
|
||||||
centered
|
centered
|
||||||
maskClosable={false}
|
maskClosable={false}
|
||||||
|
|||||||
@@ -14,6 +14,17 @@ const Error = () => {
|
|||||||
const [data, setData] = useState(intl.get('暂无日志'));
|
const [data, setData] = useState(intl.get('暂无日志'));
|
||||||
const retryTimes = useRef(1);
|
const retryTimes = useRef(1);
|
||||||
|
|
||||||
|
const loopStatus = (message: string) => {
|
||||||
|
if (retryTimes.current > 3) {
|
||||||
|
setData(message);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
retryTimes.current += 1;
|
||||||
|
setTimeout(() => {
|
||||||
|
getHealthStatus(false);
|
||||||
|
}, 3000);
|
||||||
|
};
|
||||||
|
|
||||||
const getHealthStatus = (needLoading: boolean = true) => {
|
const getHealthStatus = (needLoading: boolean = true) => {
|
||||||
needLoading && setLoading(true);
|
needLoading && setLoading(true);
|
||||||
request
|
request
|
||||||
@@ -27,19 +38,15 @@ const Error = () => {
|
|||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (retryTimes.current > 3) {
|
|
||||||
setData(error?.details);
|
loopStatus(error?.details);
|
||||||
return;
|
|
||||||
}
|
|
||||||
retryTimes.current += 1;
|
|
||||||
setTimeout(() => {
|
|
||||||
getHealthStatus(false);
|
|
||||||
}, 3000);
|
|
||||||
})
|
})
|
||||||
.catch((error) => {
|
.catch((error) => {
|
||||||
const responseStatus = error.response.status;
|
const responseStatus = error.response.status;
|
||||||
if (responseStatus === 401) {
|
if (responseStatus === 401) {
|
||||||
history.push('/login');
|
history.push('/login');
|
||||||
|
} else {
|
||||||
|
loopStatus(error.response?.message || error?.message);
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.finally(() => needLoading && setLoading(false));
|
.finally(() => needLoading && setLoading(false));
|
||||||
|
|||||||
@@ -25,11 +25,9 @@ const EditModal = ({
|
|||||||
currentNode,
|
currentNode,
|
||||||
content,
|
content,
|
||||||
handleCancel,
|
handleCancel,
|
||||||
visible,
|
|
||||||
}: {
|
}: {
|
||||||
treeData?: any;
|
treeData?: any;
|
||||||
content?: string;
|
content?: string;
|
||||||
visible: boolean;
|
|
||||||
currentNode: any;
|
currentNode: any;
|
||||||
handleCancel: () => void;
|
handleCancel: () => void;
|
||||||
}) => {
|
}) => {
|
||||||
@@ -223,7 +221,7 @@ const EditModal = ({
|
|||||||
width={'100%'}
|
width={'100%'}
|
||||||
headerStyle={{ padding: '11px 24px' }}
|
headerStyle={{ padding: '11px 24px' }}
|
||||||
onClose={cancel}
|
onClose={cancel}
|
||||||
open={visible}
|
open={true}
|
||||||
>
|
>
|
||||||
{/* @ts-ignore */}
|
{/* @ts-ignore */}
|
||||||
<SplitPane
|
<SplitPane
|
||||||
@@ -256,24 +254,26 @@ const EditModal = ({
|
|||||||
<Ansi>{log}</Ansi>
|
<Ansi>{log}</Ansi>
|
||||||
</pre>
|
</pre>
|
||||||
</SplitPane>
|
</SplitPane>
|
||||||
<SaveModal
|
{saveModalVisible && (
|
||||||
visible={saveModalVisible}
|
<SaveModal
|
||||||
handleCancel={() => {
|
handleCancel={() => {
|
||||||
setSaveModalVisible(false);
|
setSaveModalVisible(false);
|
||||||
}}
|
}}
|
||||||
file={{
|
file={{
|
||||||
content:
|
content:
|
||||||
editorRef.current &&
|
editorRef.current &&
|
||||||
editorRef.current.getValue().replace(/\r\n/g, '\n'),
|
editorRef.current.getValue().replace(/\r\n/g, '\n'),
|
||||||
...cNode,
|
...cNode,
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<SettingModal
|
)}
|
||||||
visible={settingModalVisible}
|
{settingModalVisible && (
|
||||||
handleCancel={() => {
|
<SettingModal
|
||||||
setSettingModalVisible(false);
|
handleCancel={() => {
|
||||||
}}
|
setSettingModalVisible(false);
|
||||||
/>
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
</Drawer>
|
</Drawer>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -19,9 +19,7 @@ const { Option } = Select;
|
|||||||
const EditScriptNameModal = ({
|
const EditScriptNameModal = ({
|
||||||
handleCancel,
|
handleCancel,
|
||||||
treeData,
|
treeData,
|
||||||
visible,
|
|
||||||
}: {
|
}: {
|
||||||
visible: boolean;
|
|
||||||
treeData: any[];
|
treeData: any[];
|
||||||
handleCancel: (file?: {
|
handleCancel: (file?: {
|
||||||
filename: string;
|
filename: string;
|
||||||
@@ -53,7 +51,7 @@ const EditScriptNameModal = ({
|
|||||||
directory ? intl.get('创建文件夹成功') : intl.get('创建文件成功'),
|
directory ? intl.get('创建文件夹成功') : intl.get('创建文件成功'),
|
||||||
);
|
);
|
||||||
const key = path ? `${path}/` : '';
|
const key = path ? `${path}/` : '';
|
||||||
const filename = file ? file.name : (directory || inputFilename);
|
const filename = file ? file.name : directory || inputFilename;
|
||||||
handleCancel({
|
handleCancel({
|
||||||
filename,
|
filename,
|
||||||
path,
|
path,
|
||||||
@@ -95,14 +93,10 @@ const EditScriptNameModal = ({
|
|||||||
setDirs(dirs);
|
setDirs(dirs);
|
||||||
}, [treeData]);
|
}, [treeData]);
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
form.resetFields();
|
|
||||||
}, [visible]);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
title={intl.get('创建')}
|
title={intl.get('创建')}
|
||||||
open={visible}
|
open={true}
|
||||||
forceRender
|
forceRender
|
||||||
centered
|
centered
|
||||||
maskClosable={false}
|
maskClosable={false}
|
||||||
|
|||||||
+13
-12
@@ -710,9 +710,8 @@ const Script = () => {
|
|||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
{isLogModalVisible && (
|
{isLogModalVisible && isLogModalVisible && (
|
||||||
<EditModal
|
<EditModal
|
||||||
visible={isLogModalVisible}
|
|
||||||
treeData={data}
|
treeData={data}
|
||||||
currentNode={currentNode}
|
currentNode={currentNode}
|
||||||
content={value}
|
content={value}
|
||||||
@@ -721,16 +720,18 @@ const Script = () => {
|
|||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
<EditScriptNameModal
|
{isAddFileModalVisible && (
|
||||||
visible={isAddFileModalVisible}
|
<EditScriptNameModal
|
||||||
treeData={data}
|
treeData={data}
|
||||||
handleCancel={addFileModalClose}
|
handleCancel={addFileModalClose}
|
||||||
/>
|
/>
|
||||||
<RenameModal
|
)}
|
||||||
visible={isRenameFileModalVisible}
|
{isRenameFileModalVisible && (
|
||||||
handleCancel={handleRenameFileCancel}
|
<RenameModal
|
||||||
currentNode={currentNode}
|
handleCancel={handleRenameFileCancel}
|
||||||
/>
|
currentNode={currentNode}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</PageContainer>
|
</PageContainer>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -7,10 +7,8 @@ import config from '@/utils/config';
|
|||||||
const RenameModal = ({
|
const RenameModal = ({
|
||||||
currentNode,
|
currentNode,
|
||||||
handleCancel,
|
handleCancel,
|
||||||
visible,
|
|
||||||
}: {
|
}: {
|
||||||
currentNode?: any;
|
currentNode?: any;
|
||||||
visible: boolean;
|
|
||||||
handleCancel: () => void;
|
handleCancel: () => void;
|
||||||
}) => {
|
}) => {
|
||||||
const [form] = Form.useForm();
|
const [form] = Form.useForm();
|
||||||
@@ -38,14 +36,10 @@ const RenameModal = ({
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
form.resetFields();
|
|
||||||
}, [currentNode, visible]);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
title={intl.get('重命名')}
|
title={intl.get('重命名')}
|
||||||
open={visible}
|
open={true}
|
||||||
forceRender
|
forceRender
|
||||||
centered
|
centered
|
||||||
maskClosable={false}
|
maskClosable={false}
|
||||||
|
|||||||
@@ -7,10 +7,8 @@ import config from '@/utils/config';
|
|||||||
const SaveModal = ({
|
const SaveModal = ({
|
||||||
file,
|
file,
|
||||||
handleCancel,
|
handleCancel,
|
||||||
visible,
|
|
||||||
}: {
|
}: {
|
||||||
file?: any;
|
file?: any;
|
||||||
visible: boolean;
|
|
||||||
handleCancel: (cks?: any[]) => void;
|
handleCancel: (cks?: any[]) => void;
|
||||||
}) => {
|
}) => {
|
||||||
const [form] = Form.useForm();
|
const [form] = Form.useForm();
|
||||||
@@ -32,15 +30,10 @@ const SaveModal = ({
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
form.resetFields();
|
|
||||||
setLoading(false);
|
|
||||||
}, [file, visible]);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
title={intl.get('保存文件')}
|
title={intl.get('保存文件')}
|
||||||
open={visible}
|
open={true}
|
||||||
forceRender
|
forceRender
|
||||||
centered
|
centered
|
||||||
maskClosable={false}
|
maskClosable={false}
|
||||||
|
|||||||
@@ -7,10 +7,8 @@ import config from '@/utils/config';
|
|||||||
const SettingModal = ({
|
const SettingModal = ({
|
||||||
file,
|
file,
|
||||||
handleCancel,
|
handleCancel,
|
||||||
visible,
|
|
||||||
}: {
|
}: {
|
||||||
file?: any;
|
file?: any;
|
||||||
visible: boolean;
|
|
||||||
handleCancel: (cks?: any[]) => void;
|
handleCancel: (cks?: any[]) => void;
|
||||||
}) => {
|
}) => {
|
||||||
const [form] = Form.useForm();
|
const [form] = Form.useForm();
|
||||||
@@ -30,15 +28,10 @@ const SettingModal = ({
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
form.resetFields();
|
|
||||||
setLoading(false);
|
|
||||||
}, [file, visible]);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
title={intl.get('运行设置')}
|
title={intl.get('运行设置')}
|
||||||
open={visible}
|
open={true}
|
||||||
forceRender
|
forceRender
|
||||||
centered
|
centered
|
||||||
onCancel={() => handleCancel()}
|
onCancel={() => handleCancel()}
|
||||||
|
|||||||
@@ -7,10 +7,8 @@ import config from '@/utils/config';
|
|||||||
const AppModal = ({
|
const AppModal = ({
|
||||||
app,
|
app,
|
||||||
handleCancel,
|
handleCancel,
|
||||||
visible,
|
|
||||||
}: {
|
}: {
|
||||||
app?: any;
|
app?: any;
|
||||||
visible: boolean;
|
|
||||||
handleCancel: (needUpdate?: boolean) => void;
|
handleCancel: (needUpdate?: boolean) => void;
|
||||||
}) => {
|
}) => {
|
||||||
const [form] = Form.useForm();
|
const [form] = Form.useForm();
|
||||||
@@ -41,14 +39,10 @@ const AppModal = ({
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
form.resetFields();
|
|
||||||
}, [app, visible]);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
title={app ? intl.get('编辑应用') : intl.get('创建应用')}
|
title={app ? intl.get('编辑应用') : intl.get('创建应用')}
|
||||||
open={visible}
|
open={true}
|
||||||
forceRender
|
forceRender
|
||||||
centered
|
centered
|
||||||
maskClosable={false}
|
maskClosable={false}
|
||||||
|
|||||||
@@ -1,23 +1,23 @@
|
|||||||
import { disableBody } from '@/utils';
|
import { disableBody } from "@/utils";
|
||||||
import config from '@/utils/config';
|
import config from "@/utils/config";
|
||||||
import { request } from '@/utils/http';
|
import { request } from "@/utils/http";
|
||||||
import WebSocketManager from '@/utils/websocket';
|
import WebSocketManager from "@/utils/websocket";
|
||||||
import Ansi from 'ansi-to-react';
|
import Ansi from "ansi-to-react";
|
||||||
import { Button, Modal, Statistic, message } from 'antd';
|
import { Button, Modal, Statistic, message } from "antd";
|
||||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
import { useCallback, useEffect, useRef, useState } from "react";
|
||||||
import intl from 'react-intl-universal';
|
import intl from "react-intl-universal";
|
||||||
|
|
||||||
const { Countdown } = Statistic;
|
const { Countdown } = Statistic;
|
||||||
|
|
||||||
const CheckUpdate = ({ systemInfo }: any) => {
|
const CheckUpdate = ({ systemInfo }: any) => {
|
||||||
const [updateLoading, setUpdateLoading] = useState(false);
|
const [updateLoading, setUpdateLoading] = useState(false);
|
||||||
const [value, setValue] = useState('');
|
const [value, setValue] = useState("");
|
||||||
const modalRef = useRef<any>();
|
const modalRef = useRef<any>();
|
||||||
|
|
||||||
const checkUpgrade = () => {
|
const checkUpgrade = () => {
|
||||||
if (updateLoading) return;
|
if (updateLoading) return;
|
||||||
setUpdateLoading(true);
|
setUpdateLoading(true);
|
||||||
message.loading(intl.get('检查更新中...'), 0);
|
message.loading(intl.get("检查更新中..."), 0);
|
||||||
request
|
request
|
||||||
.put(`${config.apiPrefix}system/update-check`)
|
.put(`${config.apiPrefix}system/update-check`)
|
||||||
.then(({ code, data }) => {
|
.then(({ code, data }) => {
|
||||||
@@ -42,22 +42,22 @@ const CheckUpdate = ({ systemInfo }: any) => {
|
|||||||
const showForceUpdateModal = (data: any) => {
|
const showForceUpdateModal = (data: any) => {
|
||||||
Modal.confirm({
|
Modal.confirm({
|
||||||
width: 500,
|
width: 500,
|
||||||
title: intl.get('更新'),
|
title: intl.get("更新"),
|
||||||
content: (
|
content: (
|
||||||
<>
|
<>
|
||||||
<div>{intl.get('已经是最新版了!')}</div>
|
<div>{intl.get("已经是最新版了!")}</div>
|
||||||
<div style={{ fontSize: 12, fontWeight: 400, marginTop: 5 }}>
|
<div style={{ fontSize: 12, fontWeight: 400, marginTop: 5 }}>
|
||||||
{intl.get('青龙')} {data.lastVersion}{' '}
|
{intl.get("青龙")} {data.lastVersion}{" "}
|
||||||
{intl.get('是目前检测到的最新可用版本了。')}
|
{intl.get("是目前检测到的最新可用版本了。")}
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
),
|
),
|
||||||
okText: intl.get('重新下载'),
|
okText: intl.get("重新下载"),
|
||||||
onOk() {
|
onOk() {
|
||||||
showUpdatingModal();
|
showUpdatingModal();
|
||||||
request
|
request
|
||||||
.put(`${config.apiPrefix}system/update`)
|
.put(`${config.apiPrefix}system/update`)
|
||||||
.then((_data: any) => {})
|
.then((_data: any) => { })
|
||||||
.catch((error: any) => {
|
.catch((error: any) => {
|
||||||
console.log(error);
|
console.log(error);
|
||||||
});
|
});
|
||||||
@@ -71,10 +71,10 @@ const CheckUpdate = ({ systemInfo }: any) => {
|
|||||||
width: 500,
|
width: 500,
|
||||||
title: (
|
title: (
|
||||||
<>
|
<>
|
||||||
<div>{intl.get('更新可用')}</div>
|
<div>{intl.get("更新可用")}</div>
|
||||||
<div style={{ fontSize: 12, fontWeight: 400, marginTop: 5 }}>
|
<div style={{ fontSize: 12, fontWeight: 400, marginTop: 5 }}>
|
||||||
{intl.get('新版本')} {lastVersion}{' '}
|
{intl.get("新版本")} {lastVersion}{" "}
|
||||||
{intl.get('可用,你使用的版本为')} {systemInfo.version}。
|
{intl.get("可用,你使用的版本为")} {systemInfo.version}。
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
),
|
),
|
||||||
@@ -83,13 +83,13 @@ const CheckUpdate = ({ systemInfo }: any) => {
|
|||||||
<Ansi>{lastLog}</Ansi>
|
<Ansi>{lastLog}</Ansi>
|
||||||
</pre>
|
</pre>
|
||||||
),
|
),
|
||||||
okText: intl.get('下载更新'),
|
okText: intl.get("下载更新"),
|
||||||
cancelText: intl.get('以后再说'),
|
cancelText: intl.get("以后再说"),
|
||||||
onOk() {
|
onOk() {
|
||||||
showUpdatingModal();
|
showUpdatingModal();
|
||||||
request
|
request
|
||||||
.put(`${config.apiPrefix}system/update`)
|
.put(`${config.apiPrefix}system/update`)
|
||||||
.then((_data: any) => {})
|
.then((_data: any) => { })
|
||||||
.catch((error: any) => {
|
.catch((error: any) => {
|
||||||
console.log(error);
|
console.log(error);
|
||||||
});
|
});
|
||||||
@@ -98,14 +98,14 @@ const CheckUpdate = ({ systemInfo }: any) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const showUpdatingModal = () => {
|
const showUpdatingModal = () => {
|
||||||
setValue('');
|
setValue("");
|
||||||
modalRef.current = Modal.info({
|
modalRef.current = Modal.info({
|
||||||
width: 600,
|
width: 600,
|
||||||
maskClosable: false,
|
maskClosable: false,
|
||||||
closable: false,
|
closable: false,
|
||||||
keyboard: false,
|
keyboard: false,
|
||||||
okButtonProps: { disabled: true },
|
okButtonProps: { disabled: true },
|
||||||
title: intl.get('下载更新中...'),
|
title: intl.get("下载更新中..."),
|
||||||
centered: true,
|
centered: true,
|
||||||
content: (
|
content: (
|
||||||
<pre>
|
<pre>
|
||||||
@@ -122,13 +122,13 @@ const CheckUpdate = ({ systemInfo }: any) => {
|
|||||||
message.success({
|
message.success({
|
||||||
content: (
|
content: (
|
||||||
<span>
|
<span>
|
||||||
{intl.get('系统将在')}
|
{intl.get("系统将在")}
|
||||||
<Countdown
|
<Countdown
|
||||||
className="inline-countdown"
|
className="inline-countdown"
|
||||||
format="ss"
|
format="ss"
|
||||||
value={Date.now() + 1000 * 30}
|
value={Date.now() + 1000 * 30}
|
||||||
/>
|
/>
|
||||||
{intl.get('秒后自动刷新')}
|
{intl.get("秒后自动刷新")}
|
||||||
</span>
|
</span>
|
||||||
),
|
),
|
||||||
duration: 30,
|
duration: 30,
|
||||||
@@ -147,12 +147,12 @@ const CheckUpdate = ({ systemInfo }: any) => {
|
|||||||
Modal.confirm({
|
Modal.confirm({
|
||||||
width: 600,
|
width: 600,
|
||||||
maskClosable: false,
|
maskClosable: false,
|
||||||
title: intl.get('确认重启'),
|
title: intl.get("确认重启"),
|
||||||
centered: true,
|
centered: true,
|
||||||
content: intl.get('系统安装包下载成功,确认重启'),
|
content: intl.get("系统安装包下载成功,确认重启"),
|
||||||
okText: intl.get('重启'),
|
okText: intl.get("重启"),
|
||||||
onOk() {
|
onOk() {
|
||||||
reloadSystem('system');
|
reloadSystem("system");
|
||||||
},
|
},
|
||||||
onCancel() {
|
onCancel() {
|
||||||
modalRef.current.update({
|
modalRef.current.update({
|
||||||
@@ -166,7 +166,7 @@ const CheckUpdate = ({ systemInfo }: any) => {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!value) return;
|
if (!value) return;
|
||||||
const updateFailed = value.includes('失败,请检查');
|
const updateFailed = value.includes("失败,请检查");
|
||||||
|
|
||||||
modalRef.current.update({
|
modalRef.current.update({
|
||||||
maskClosable: updateFailed,
|
maskClosable: updateFailed,
|
||||||
@@ -185,19 +185,19 @@ const CheckUpdate = ({ systemInfo }: any) => {
|
|||||||
|
|
||||||
const handleMessage = useCallback((payload: any) => {
|
const handleMessage = useCallback((payload: any) => {
|
||||||
let { message: _message } = payload;
|
let { message: _message } = payload;
|
||||||
const updateFailed = _message.includes('失败,请检查');
|
const updateFailed = _message.includes("失败,请检查");
|
||||||
|
|
||||||
if (updateFailed) {
|
if (updateFailed) {
|
||||||
message.error(intl.get('更新失败,请检查网络及日志或稍后再试'));
|
message.error(intl.get("更新失败,请检查网络及日志或稍后再试"));
|
||||||
}
|
}
|
||||||
|
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
document
|
document
|
||||||
.querySelector('#log-identifier')!
|
.querySelector("#log-identifier")
|
||||||
.scrollIntoView({ behavior: 'smooth' });
|
?.scrollIntoView({ behavior: "smooth" });
|
||||||
}, 600);
|
}, 600);
|
||||||
|
|
||||||
if (_message.includes('更新包下载成功')) {
|
if (_message.includes("更新包下载成功")) {
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
showReloadModal();
|
showReloadModal();
|
||||||
}, 1000);
|
}, 1000);
|
||||||
@@ -208,24 +208,24 @@ const CheckUpdate = ({ systemInfo }: any) => {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const ws = WebSocketManager.getInstance();
|
const ws = WebSocketManager.getInstance();
|
||||||
ws.subscribe('updateSystemVersion', handleMessage);
|
ws.subscribe("updateSystemVersion", handleMessage);
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
ws.unsubscribe('updateSystemVersion', handleMessage);
|
ws.unsubscribe("updateSystemVersion", handleMessage);
|
||||||
};
|
};
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Button type="primary" onClick={checkUpgrade}>
|
<Button type="primary" onClick={checkUpgrade}>
|
||||||
{intl.get('检查更新')}
|
{intl.get("检查更新")}
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
type="primary"
|
type="primary"
|
||||||
onClick={() => reloadSystem('reload')}
|
onClick={() => reloadSystem("reload")}
|
||||||
style={{ marginLeft: 8 }}
|
style={{ marginLeft: 8 }}
|
||||||
>
|
>
|
||||||
{intl.get('重新启动')}
|
{intl.get("重新启动")}
|
||||||
</Button>
|
</Button>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import intl from 'react-intl-universal';
|
import intl from 'react-intl-universal';
|
||||||
import React, { useState, useEffect, useRef } from 'react';
|
import React, { useState, useEffect, useRef } from 'react';
|
||||||
import { Button, InputNumber, Form, message, Input, Alert } from 'antd';
|
import { Button, InputNumber, Form, message, Input, Alert, Select } from 'antd';
|
||||||
import config from '@/utils/config';
|
import config from '@/utils/config';
|
||||||
import { request } from '@/utils/http';
|
import { request } from '@/utils/http';
|
||||||
import './index.less';
|
import './index.less';
|
||||||
@@ -25,6 +25,7 @@ const Dependence = () => {
|
|||||||
const [form] = Form.useForm();
|
const [form] = Form.useForm();
|
||||||
const [log, setLog] = useState<string>('');
|
const [log, setLog] = useState<string>('');
|
||||||
const [loading, setLoading] = useState<boolean>(false);
|
const [loading, setLoading] = useState<boolean>(false);
|
||||||
|
const [cleanType, setCleanType] = useState<string>('node');
|
||||||
|
|
||||||
const getSystemConfig = () => {
|
const getSystemConfig = () => {
|
||||||
request
|
request
|
||||||
@@ -84,6 +85,24 @@ const Dependence = () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const cleanDependenceCache = (type: string) => {
|
||||||
|
setLoading(true);
|
||||||
|
setLog('');
|
||||||
|
request
|
||||||
|
.put(`${config.apiPrefix}system/config/dependence-clean`, {
|
||||||
|
type,
|
||||||
|
})
|
||||||
|
.then(({ code, data }) => {
|
||||||
|
if (code === 200) {
|
||||||
|
message.success(intl.get('清除成功'));
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch((error: any) => {
|
||||||
|
console.log(error);
|
||||||
|
})
|
||||||
|
.finally(() => setLoading(false));
|
||||||
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const ws = WebSocketManager.getInstance();
|
const ws = WebSocketManager.getInstance();
|
||||||
ws.subscribe('updateNodeMirror', handleMessage);
|
ws.subscribe('updateNodeMirror', handleMessage);
|
||||||
@@ -222,6 +241,38 @@ const Dependence = () => {
|
|||||||
</Button>
|
</Button>
|
||||||
</Input.Group>
|
</Input.Group>
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
|
<Form.Item
|
||||||
|
label={intl.get('清除依赖缓存')}
|
||||||
|
name="clean"
|
||||||
|
tooltip={{
|
||||||
|
title: intl.get('清除依赖缓存'),
|
||||||
|
placement: 'topLeft',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Input.Group compact>
|
||||||
|
<Select
|
||||||
|
defaultValue={'node'}
|
||||||
|
style={{ width: 100 }}
|
||||||
|
onChange={(value) => {
|
||||||
|
setCleanType(value);
|
||||||
|
}}
|
||||||
|
options={[
|
||||||
|
{ label: 'node', value: 'node' },
|
||||||
|
{ label: 'python3', value: 'python3' },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
type="primary"
|
||||||
|
loading={loading}
|
||||||
|
onClick={() => {
|
||||||
|
cleanDependenceCache(cleanType);
|
||||||
|
}}
|
||||||
|
style={{ width: 100 }}
|
||||||
|
>
|
||||||
|
{intl.get('确认')}
|
||||||
|
</Button>
|
||||||
|
</Input.Group>
|
||||||
|
</Form.Item>
|
||||||
</Form>
|
</Form>
|
||||||
<pre
|
<pre
|
||||||
style={{
|
style={{
|
||||||
|
|||||||
+27
-15
@@ -35,6 +35,7 @@ import './index.less';
|
|||||||
import useResizeObserver from '@react-hook/resize-observer';
|
import useResizeObserver from '@react-hook/resize-observer';
|
||||||
import SystemLog from './systemLog';
|
import SystemLog from './systemLog';
|
||||||
import Dependence from './dependence';
|
import Dependence from './dependence';
|
||||||
|
import UserManagement from './userManagement';
|
||||||
|
|
||||||
const { Text } = Typography;
|
const { Text } = Typography;
|
||||||
const isDemoEnv = window.__ENV__DeployEnv === 'demo';
|
const isDemoEnv = window.__ENV__DeployEnv === 'demo';
|
||||||
@@ -333,16 +334,29 @@ const Setting = () => {
|
|||||||
label: intl.get('通知设置'),
|
label: intl.get('通知设置'),
|
||||||
children: <NotificationSetting data={notificationInfo} />,
|
children: <NotificationSetting data={notificationInfo} />,
|
||||||
},
|
},
|
||||||
{
|
...(user?.role === 0
|
||||||
key: 'syslog',
|
? [
|
||||||
label: intl.get('系统日志'),
|
{
|
||||||
children: <SystemLog height={height} theme={theme} />,
|
key: 'syslog',
|
||||||
},
|
label: intl.get('系统日志'),
|
||||||
{
|
children: <SystemLog height={height} theme={theme} />,
|
||||||
key: 'login',
|
},
|
||||||
label: intl.get('登录日志'),
|
{
|
||||||
children: <LoginLog height={height} data={loginLogData} />,
|
key: 'login',
|
||||||
},
|
label: intl.get('登录日志'),
|
||||||
|
children: <LoginLog height={height} data={loginLogData} />,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: []),
|
||||||
|
...(user?.role === 0 && !isDemoEnv
|
||||||
|
? [
|
||||||
|
{
|
||||||
|
key: 'user-management',
|
||||||
|
label: intl.get('用户管理'),
|
||||||
|
children: <UserManagement height={height} />,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: []),
|
||||||
{
|
{
|
||||||
key: 'dependence',
|
key: 'dependence',
|
||||||
label: intl.get('依赖设置'),
|
label: intl.get('依赖设置'),
|
||||||
@@ -363,11 +377,9 @@ const Setting = () => {
|
|||||||
]}
|
]}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<AppModal
|
{isModalVisible && (
|
||||||
visible={isModalVisible}
|
<AppModal handleCancel={handleCancel} app={editedApp} />
|
||||||
handleCancel={handleCancel}
|
)}
|
||||||
app={editedApp}
|
|
||||||
/>
|
|
||||||
</PageContainer>
|
</PageContainer>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
+207
-143
@@ -10,6 +10,7 @@ import {
|
|||||||
Upload,
|
Upload,
|
||||||
Modal,
|
Modal,
|
||||||
Select,
|
Select,
|
||||||
|
Checkbox,
|
||||||
} from 'antd';
|
} from 'antd';
|
||||||
import * as DarkReader from '@umijs/ssr-darkreader';
|
import * as DarkReader from '@umijs/ssr-darkreader';
|
||||||
import config from '@/utils/config';
|
import config from '@/utils/config';
|
||||||
@@ -31,6 +32,19 @@ const dataMap = {
|
|||||||
timezone: 'timezone',
|
timezone: 'timezone',
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const exportModules = [
|
||||||
|
{ value: 'base', label: intl.get('基础数据'), disabled: true },
|
||||||
|
{ value: 'config', label: intl.get('配置文件') },
|
||||||
|
{ value: 'scripts', label: intl.get('脚本文件') },
|
||||||
|
{ value: 'log', label: intl.get('日志文件') },
|
||||||
|
{ value: 'deps', label: intl.get('依赖文件') },
|
||||||
|
{ value: 'syslog', label: intl.get('系统日志') },
|
||||||
|
{ value: 'dep_cache', label: intl.get('依赖缓存') },
|
||||||
|
{ value: 'raw', label: intl.get('远程脚本缓存') },
|
||||||
|
{ value: 'repo', label: intl.get('远程仓库缓存') },
|
||||||
|
{ value: 'ssh.d', label: intl.get('SSH 文件缓存') },
|
||||||
|
];
|
||||||
|
|
||||||
const Other = ({
|
const Other = ({
|
||||||
systemInfo,
|
systemInfo,
|
||||||
reloadTheme,
|
reloadTheme,
|
||||||
@@ -45,6 +59,8 @@ const Other = ({
|
|||||||
const [exportLoading, setExportLoading] = useState(false);
|
const [exportLoading, setExportLoading] = useState(false);
|
||||||
const showUploadProgress = useProgress(intl.get('上传'));
|
const showUploadProgress = useProgress(intl.get('上传'));
|
||||||
const showDownloadProgress = useProgress(intl.get('下载'));
|
const showDownloadProgress = useProgress(intl.get('下载'));
|
||||||
|
const [visible, setVisible] = useState(false);
|
||||||
|
const [selectedModules, setSelectedModules] = useState<string[]>(['base']);
|
||||||
|
|
||||||
const {
|
const {
|
||||||
enable: enableDarkMode,
|
enable: enableDarkMode,
|
||||||
@@ -110,7 +126,7 @@ const Other = ({
|
|||||||
request
|
request
|
||||||
.put<Blob>(
|
.put<Blob>(
|
||||||
`${config.apiPrefix}system/data/export`,
|
`${config.apiPrefix}system/data/export`,
|
||||||
{},
|
{ type: selectedModules },
|
||||||
{
|
{
|
||||||
responseType: 'blob',
|
responseType: 'blob',
|
||||||
timeout: 86400000,
|
timeout: 86400000,
|
||||||
@@ -127,7 +143,10 @@ const Other = ({
|
|||||||
.catch((error: any) => {
|
.catch((error: any) => {
|
||||||
console.log(error);
|
console.log(error);
|
||||||
})
|
})
|
||||||
.finally(() => setExportLoading(false));
|
.finally(() => {
|
||||||
|
setExportLoading(false);
|
||||||
|
setVisible(false);
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const showReloadModal = () => {
|
const showReloadModal = () => {
|
||||||
@@ -178,160 +197,205 @@ const Other = ({
|
|||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Form layout="vertical" form={form}>
|
<>
|
||||||
<Form.Item
|
<Form layout="vertical" form={form}>
|
||||||
label={intl.get('主题')}
|
<Form.Item
|
||||||
name="theme"
|
label={intl.get('主题')}
|
||||||
initialValue={defaultTheme}
|
name="theme"
|
||||||
>
|
initialValue={defaultTheme}
|
||||||
<Radio.Group
|
|
||||||
onChange={themeChange}
|
|
||||||
value={defaultTheme}
|
|
||||||
optionType="button"
|
|
||||||
buttonStyle="solid"
|
|
||||||
>
|
>
|
||||||
<Radio.Button
|
<Radio.Group
|
||||||
value="light"
|
onChange={themeChange}
|
||||||
style={{ width: 70, textAlign: 'center' }}
|
value={defaultTheme}
|
||||||
|
optionType="button"
|
||||||
|
buttonStyle="solid"
|
||||||
>
|
>
|
||||||
{intl.get('亮色')}
|
<Radio.Button
|
||||||
</Radio.Button>
|
value="light"
|
||||||
<Radio.Button value="dark" style={{ width: 66, textAlign: 'center' }}>
|
style={{ width: 70, textAlign: 'center' }}
|
||||||
{intl.get('暗色')}
|
>
|
||||||
</Radio.Button>
|
{intl.get('亮色')}
|
||||||
<Radio.Button
|
</Radio.Button>
|
||||||
value="auto"
|
<Radio.Button
|
||||||
style={{ width: 129, textAlign: 'center' }}
|
value="dark"
|
||||||
>
|
style={{ width: 66, textAlign: 'center' }}
|
||||||
{intl.get('跟随系统')}
|
>
|
||||||
</Radio.Button>
|
{intl.get('暗色')}
|
||||||
</Radio.Group>
|
</Radio.Button>
|
||||||
</Form.Item>
|
<Radio.Button
|
||||||
<Form.Item
|
value="auto"
|
||||||
label={intl.get('日志删除频率')}
|
style={{ width: 129, textAlign: 'center' }}
|
||||||
name="frequency"
|
>
|
||||||
tooltip={intl.get('每x天自动删除x天以前的日志')}
|
{intl.get('跟随系统')}
|
||||||
>
|
</Radio.Button>
|
||||||
<Input.Group compact>
|
</Radio.Group>
|
||||||
<InputNumber
|
</Form.Item>
|
||||||
addonBefore={intl.get('每')}
|
<Form.Item
|
||||||
addonAfter={intl.get('天')}
|
label={intl.get('日志删除频率')}
|
||||||
style={{ width: 180 }}
|
name="frequency"
|
||||||
min={0}
|
tooltip={intl.get('每x天自动删除x天以前的日志')}
|
||||||
value={systemConfig?.logRemoveFrequency}
|
>
|
||||||
onChange={(value) => {
|
<Input.Group compact>
|
||||||
setSystemConfig({ ...systemConfig, logRemoveFrequency: value });
|
<InputNumber
|
||||||
}}
|
addonBefore={intl.get('每')}
|
||||||
/>
|
addonAfter={intl.get('天')}
|
||||||
<Button
|
style={{ width: 180 }}
|
||||||
type="primary"
|
min={0}
|
||||||
onClick={() => {
|
value={systemConfig?.logRemoveFrequency}
|
||||||
updateSystemConfig('log-remove-frequency');
|
onChange={(value) => {
|
||||||
}}
|
setSystemConfig({ ...systemConfig, logRemoveFrequency: value });
|
||||||
style={{ width: 84 }}
|
}}
|
||||||
>
|
/>
|
||||||
{intl.get('确认')}
|
<Button
|
||||||
</Button>
|
type="primary"
|
||||||
</Input.Group>
|
onClick={() => {
|
||||||
</Form.Item>
|
updateSystemConfig('log-remove-frequency');
|
||||||
<Form.Item label={intl.get('定时任务并发数')} name="frequency">
|
}}
|
||||||
<Input.Group compact>
|
style={{ width: 84 }}
|
||||||
<InputNumber
|
>
|
||||||
style={{ width: 180 }}
|
{intl.get('确认')}
|
||||||
min={1}
|
</Button>
|
||||||
value={systemConfig?.cronConcurrency}
|
</Input.Group>
|
||||||
onChange={(value) => {
|
</Form.Item>
|
||||||
setSystemConfig({ ...systemConfig, cronConcurrency: value });
|
<Form.Item label={intl.get('定时任务并发数')} name="frequency">
|
||||||
}}
|
<Input.Group compact>
|
||||||
/>
|
<InputNumber
|
||||||
<Button
|
style={{ width: 180 }}
|
||||||
type="primary"
|
min={1}
|
||||||
onClick={() => {
|
value={systemConfig?.cronConcurrency}
|
||||||
updateSystemConfig('cron-concurrency');
|
onChange={(value) => {
|
||||||
}}
|
setSystemConfig({ ...systemConfig, cronConcurrency: value });
|
||||||
style={{ width: 84 }}
|
}}
|
||||||
>
|
/>
|
||||||
{intl.get('确认')}
|
<Button
|
||||||
</Button>
|
type="primary"
|
||||||
</Input.Group>
|
onClick={() => {
|
||||||
</Form.Item>
|
updateSystemConfig('cron-concurrency');
|
||||||
<Form.Item label={intl.get('时区')} name="timezone">
|
}}
|
||||||
<Input.Group compact>
|
style={{ width: 84 }}
|
||||||
|
>
|
||||||
|
{intl.get('确认')}
|
||||||
|
</Button>
|
||||||
|
</Input.Group>
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item label={intl.get('时区')} name="timezone">
|
||||||
|
<Input.Group compact>
|
||||||
|
<Select
|
||||||
|
value={systemConfig?.timezone}
|
||||||
|
style={{ width: 180 }}
|
||||||
|
onChange={(value) => {
|
||||||
|
setSystemConfig({ ...systemConfig, timezone: value });
|
||||||
|
}}
|
||||||
|
options={TIMEZONES.map((timezone) => ({
|
||||||
|
value: timezone,
|
||||||
|
label: timezone,
|
||||||
|
}))}
|
||||||
|
showSearch
|
||||||
|
filterOption={(input, option) =>
|
||||||
|
option?.value?.toLowerCase().indexOf(input.toLowerCase()) >= 0
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
type="primary"
|
||||||
|
onClick={() => {
|
||||||
|
updateSystemConfig('timezone');
|
||||||
|
}}
|
||||||
|
style={{ width: 84 }}
|
||||||
|
>
|
||||||
|
{intl.get('确认')}
|
||||||
|
</Button>
|
||||||
|
</Input.Group>
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item label={intl.get('语言')} name="lang">
|
||||||
<Select
|
<Select
|
||||||
value={systemConfig?.timezone}
|
defaultValue={localStorage.getItem('lang') || ''}
|
||||||
style={{ width: 180 }}
|
style={{ width: 264 }}
|
||||||
onChange={(value) => {
|
onChange={handleLangChange}
|
||||||
setSystemConfig({ ...systemConfig, timezone: value });
|
options={[
|
||||||
}}
|
{ value: '', label: intl.get('跟随系统') },
|
||||||
options={TIMEZONES.map((timezone) => ({
|
{ value: 'zh', label: '简体中文' },
|
||||||
value: timezone,
|
{ value: 'en', label: 'English' },
|
||||||
label: timezone,
|
]}
|
||||||
}))}
|
|
||||||
showSearch
|
|
||||||
filterOption={(input, option) =>
|
|
||||||
option?.value?.toLowerCase().indexOf(input.toLowerCase()) >= 0
|
|
||||||
}
|
|
||||||
/>
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item label={intl.get('数据备份还原')} name="frequency">
|
||||||
<Button
|
<Button
|
||||||
type="primary"
|
type="primary"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
updateSystemConfig('timezone');
|
setSelectedModules(['base']);
|
||||||
|
setVisible(true);
|
||||||
}}
|
}}
|
||||||
style={{ width: 84 }}
|
loading={exportLoading}
|
||||||
>
|
>
|
||||||
{intl.get('确认')}
|
{exportLoading ? intl.get('生成数据中...') : intl.get('备份')}
|
||||||
</Button>
|
</Button>
|
||||||
</Input.Group>
|
<Upload
|
||||||
</Form.Item>
|
method="put"
|
||||||
<Form.Item label={intl.get('语言')} name="lang">
|
showUploadList={false}
|
||||||
<Select
|
maxCount={1}
|
||||||
defaultValue={localStorage.getItem('lang') || ''}
|
action={`${config.apiPrefix}system/data/import`}
|
||||||
style={{ width: 264 }}
|
onChange={({ file, event }) => {
|
||||||
onChange={handleLangChange}
|
if (event?.percent) {
|
||||||
options={[
|
showUploadProgress(
|
||||||
{ value: '', label: intl.get('跟随系统') },
|
Math.min(parseFloat(event?.percent.toFixed(1)), 99),
|
||||||
{ value: 'zh', label: '简体中文' },
|
);
|
||||||
{ value: 'en', label: 'English' },
|
}
|
||||||
]}
|
if (file.status === 'done') {
|
||||||
/>
|
showUploadProgress(100);
|
||||||
</Form.Item>
|
showReloadModal();
|
||||||
<Form.Item label={intl.get('数据备份还原')} name="frequency">
|
}
|
||||||
<Button type="primary" onClick={exportData} loading={exportLoading}>
|
if (file.status === 'error') {
|
||||||
{exportLoading ? intl.get('生成数据中...') : intl.get('备份')}
|
message.error('上传失败');
|
||||||
</Button>
|
}
|
||||||
<Upload
|
}}
|
||||||
method="put"
|
name="data"
|
||||||
showUploadList={false}
|
headers={{
|
||||||
maxCount={1}
|
Authorization: `Bearer ${localStorage.getItem(config.authKey)}`,
|
||||||
action={`${config.apiPrefix}system/data/import`}
|
}}
|
||||||
onChange={({ file, event }) => {
|
>
|
||||||
if (event?.percent) {
|
<Button icon={<UploadOutlined />} style={{ marginLeft: 8 }}>
|
||||||
showUploadProgress(
|
{intl.get('还原数据')}
|
||||||
Math.min(parseFloat(event?.percent.toFixed(1)), 99),
|
</Button>
|
||||||
);
|
</Upload>
|
||||||
}
|
</Form.Item>
|
||||||
if (file.status === 'done') {
|
<Form.Item label={intl.get('检查更新')} name="update">
|
||||||
showUploadProgress(100);
|
<CheckUpdate systemInfo={systemInfo} />
|
||||||
showReloadModal();
|
</Form.Item>
|
||||||
}
|
</Form>
|
||||||
if (file.status === 'error') {
|
<Modal
|
||||||
message.error('上传失败');
|
title={intl.get('选择备份模块')}
|
||||||
}
|
open={visible}
|
||||||
|
onOk={exportData}
|
||||||
|
onCancel={() => setVisible(false)}
|
||||||
|
okText={intl.get('开始备份')}
|
||||||
|
cancelText={intl.get('取消')}
|
||||||
|
okButtonProps={{ loading: exportLoading }} // 绑定加载状态到按钮
|
||||||
|
>
|
||||||
|
<Checkbox.Group
|
||||||
|
value={selectedModules}
|
||||||
|
onChange={(v) => {
|
||||||
|
setSelectedModules(v as string[]);
|
||||||
}}
|
}}
|
||||||
name="data"
|
style={{
|
||||||
headers={{
|
width: '100%',
|
||||||
Authorization: `Bearer ${localStorage.getItem(config.authKey)}`,
|
display: 'flex',
|
||||||
|
flexWrap: 'wrap',
|
||||||
|
gap: '8px 16px',
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Button icon={<UploadOutlined />} style={{ marginLeft: 8 }}>
|
{exportModules.map((module) => (
|
||||||
{intl.get('还原数据')}
|
<Checkbox
|
||||||
</Button>
|
key={module.value}
|
||||||
</Upload>
|
value={module.value}
|
||||||
</Form.Item>
|
disabled={module.disabled}
|
||||||
<Form.Item label={intl.get('检查更新')} name="update">
|
style={{ marginLeft: 0 }}
|
||||||
<CheckUpdate systemInfo={systemInfo} />
|
>
|
||||||
</Form.Item>
|
{module.label}
|
||||||
</Form>
|
</Checkbox>
|
||||||
|
))}
|
||||||
|
</Checkbox.Group>
|
||||||
|
</Modal>
|
||||||
|
</>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,264 @@
|
|||||||
|
import intl from 'react-intl-universal';
|
||||||
|
import React, { useState, useEffect } from 'react';
|
||||||
|
import {
|
||||||
|
Button,
|
||||||
|
Table,
|
||||||
|
Space,
|
||||||
|
Modal,
|
||||||
|
Form,
|
||||||
|
Input,
|
||||||
|
Select,
|
||||||
|
message,
|
||||||
|
Tag,
|
||||||
|
} from 'antd';
|
||||||
|
import {
|
||||||
|
EditOutlined,
|
||||||
|
DeleteOutlined,
|
||||||
|
PlusOutlined,
|
||||||
|
} from '@ant-design/icons';
|
||||||
|
import { request } from '@/utils/http';
|
||||||
|
import config from '@/utils/config';
|
||||||
|
|
||||||
|
const { Option } = Select;
|
||||||
|
|
||||||
|
interface User {
|
||||||
|
id: number;
|
||||||
|
username: string;
|
||||||
|
password?: string;
|
||||||
|
role: number;
|
||||||
|
status: number;
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const UserManagement: React.FC<{ height: number }> = ({ height }) => {
|
||||||
|
const [users, setUsers] = useState<User[]>([]);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [isModalVisible, setIsModalVisible] = useState(false);
|
||||||
|
const [editingUser, setEditingUser] = useState<User | null>(null);
|
||||||
|
const [form] = Form.useForm();
|
||||||
|
|
||||||
|
const columns = [
|
||||||
|
{
|
||||||
|
title: intl.get('用户名'),
|
||||||
|
dataIndex: 'username',
|
||||||
|
key: 'username',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: intl.get('角色'),
|
||||||
|
dataIndex: 'role',
|
||||||
|
key: 'role',
|
||||||
|
render: (role: number) => (
|
||||||
|
<Tag color={role === 0 ? 'red' : 'blue'}>
|
||||||
|
{role === 0 ? intl.get('管理员') : intl.get('普通用户')}
|
||||||
|
</Tag>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: intl.get('状态'),
|
||||||
|
dataIndex: 'status',
|
||||||
|
key: 'status',
|
||||||
|
render: (status: number) => (
|
||||||
|
<Tag color={status === 0 ? 'green' : 'default'}>
|
||||||
|
{status === 0 ? intl.get('启用') : intl.get('禁用')}
|
||||||
|
</Tag>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: intl.get('创建时间'),
|
||||||
|
dataIndex: 'createdAt',
|
||||||
|
key: 'createdAt',
|
||||||
|
render: (text: string) => text ? new Date(text).toLocaleString() : '-',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: intl.get('操作'),
|
||||||
|
key: 'action',
|
||||||
|
render: (_: any, record: User) => (
|
||||||
|
<Space size="middle">
|
||||||
|
<Button
|
||||||
|
type="link"
|
||||||
|
icon={<EditOutlined />}
|
||||||
|
onClick={() => handleEdit(record)}
|
||||||
|
>
|
||||||
|
{intl.get('编辑')}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="link"
|
||||||
|
danger
|
||||||
|
icon={<DeleteOutlined />}
|
||||||
|
onClick={() => handleDelete([record.id])}
|
||||||
|
>
|
||||||
|
{intl.get('删除')}
|
||||||
|
</Button>
|
||||||
|
</Space>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const fetchUsers = async () => {
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
const { code, data } = await request.get(
|
||||||
|
`${config.apiPrefix}user-management`
|
||||||
|
);
|
||||||
|
if (code === 200) {
|
||||||
|
setUsers(data);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
message.error('Failed to fetch users');
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchUsers();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleAdd = () => {
|
||||||
|
setEditingUser(null);
|
||||||
|
form.resetFields();
|
||||||
|
setIsModalVisible(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleEdit = (record: User) => {
|
||||||
|
setEditingUser(record);
|
||||||
|
form.setFieldsValue({
|
||||||
|
username: record.username,
|
||||||
|
role: record.role,
|
||||||
|
status: record.status,
|
||||||
|
});
|
||||||
|
setIsModalVisible(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDelete = (ids: number[]) => {
|
||||||
|
Modal.confirm({
|
||||||
|
title: intl.get('确认删除'),
|
||||||
|
content: intl.get('确认删除选中的用户吗'),
|
||||||
|
onOk: async () => {
|
||||||
|
try {
|
||||||
|
const { code, message: msg } = await request.delete(
|
||||||
|
`${config.apiPrefix}user-management`,
|
||||||
|
{ data: ids }
|
||||||
|
);
|
||||||
|
if (code === 200) {
|
||||||
|
message.success(msg || intl.get('删除成功'));
|
||||||
|
fetchUsers();
|
||||||
|
} else {
|
||||||
|
message.error(msg || intl.get('删除失败'));
|
||||||
|
}
|
||||||
|
} catch (error: any) {
|
||||||
|
message.error(error.message || intl.get('删除失败'));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSubmit = async () => {
|
||||||
|
try {
|
||||||
|
const values = await form.validateFields();
|
||||||
|
|
||||||
|
if (editingUser) {
|
||||||
|
// Update user
|
||||||
|
const { code, message: msg } = await request.put(
|
||||||
|
`${config.apiPrefix}user-management`,
|
||||||
|
{ ...values, id: editingUser.id }
|
||||||
|
);
|
||||||
|
if (code === 200) {
|
||||||
|
message.success(msg || intl.get('更新成功'));
|
||||||
|
setIsModalVisible(false);
|
||||||
|
fetchUsers();
|
||||||
|
} else {
|
||||||
|
message.error(msg || intl.get('更新失败'));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Create user
|
||||||
|
const { code, message: msg } = await request.post(
|
||||||
|
`${config.apiPrefix}user-management`,
|
||||||
|
values
|
||||||
|
);
|
||||||
|
if (code === 200) {
|
||||||
|
message.success(msg || intl.get('创建成功'));
|
||||||
|
setIsModalVisible(false);
|
||||||
|
fetchUsers();
|
||||||
|
} else {
|
||||||
|
message.error(msg || intl.get('创建失败'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error: any) {
|
||||||
|
message.error(error.message || intl.get('操作失败'));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<div style={{ marginBottom: 16 }}>
|
||||||
|
<Button
|
||||||
|
type="primary"
|
||||||
|
icon={<PlusOutlined />}
|
||||||
|
onClick={handleAdd}
|
||||||
|
>
|
||||||
|
{intl.get('新增用户')}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
<Table
|
||||||
|
columns={columns}
|
||||||
|
dataSource={users}
|
||||||
|
rowKey="id"
|
||||||
|
loading={loading}
|
||||||
|
scroll={{ y: height - 120 }}
|
||||||
|
pagination={false}
|
||||||
|
/>
|
||||||
|
<Modal
|
||||||
|
title={editingUser ? intl.get('编辑用户') : intl.get('新增用户')}
|
||||||
|
open={isModalVisible}
|
||||||
|
onOk={handleSubmit}
|
||||||
|
onCancel={() => setIsModalVisible(false)}
|
||||||
|
>
|
||||||
|
<Form form={form} layout="vertical">
|
||||||
|
<Form.Item
|
||||||
|
name="username"
|
||||||
|
label={intl.get('用户名')}
|
||||||
|
rules={[{ required: true, message: intl.get('请输入用户名') }]}
|
||||||
|
>
|
||||||
|
<Input placeholder={intl.get('请输入用户名')} />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item
|
||||||
|
name="password"
|
||||||
|
label={intl.get('密码')}
|
||||||
|
rules={[
|
||||||
|
{ required: !editingUser, message: intl.get('请输入密码') },
|
||||||
|
{ min: 6, message: intl.get('密码长度至少为6位') },
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
<Input.Password placeholder={intl.get('请输入密码')} />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item
|
||||||
|
name="role"
|
||||||
|
label={intl.get('角色')}
|
||||||
|
rules={[{ required: true, message: intl.get('请选择角色') }]}
|
||||||
|
initialValue={1}
|
||||||
|
>
|
||||||
|
<Select>
|
||||||
|
<Option value={0}>{intl.get('管理员')}</Option>
|
||||||
|
<Option value={1}>{intl.get('普通用户')}</Option>
|
||||||
|
</Select>
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item
|
||||||
|
name="status"
|
||||||
|
label={intl.get('状态')}
|
||||||
|
rules={[{ required: true, message: intl.get('请选择状态') }]}
|
||||||
|
initialValue={0}
|
||||||
|
>
|
||||||
|
<Select>
|
||||||
|
<Option value={0}>{intl.get('启用')}</Option>
|
||||||
|
<Option value={1}>{intl.get('禁用')}</Option>
|
||||||
|
</Select>
|
||||||
|
</Form.Item>
|
||||||
|
</Form>
|
||||||
|
</Modal>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default UserManagement;
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user