Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| af7fcc4cb4 | |||
| c206a0863e | |||
| b068e178da | |||
| 02737ef743 | |||
| 74a1134cf1 | |||
| b6f777f997 | |||
| 2dc233631e | |||
| 0c60eb5ae4 |
+3
-3
@@ -29,10 +29,10 @@ url = "redis://:jhkdjhkjdhsIUTYURTU_pEGmFP@database.out:56379"
|
||||
smtpHost = "smtp-mail.outlook.com"
|
||||
smtpPort = 587
|
||||
# 发件人邮箱和密码(需要使用授权码,不是登录密码)
|
||||
smtpUsername = "demo@likedream.xyz"
|
||||
smtpUsername = "reply@likedream.xyz"
|
||||
smtpPassword = "baca122..."
|
||||
# 发件人邮箱和显示名称
|
||||
fromEmail = "demo@likedream.xyz"
|
||||
fromEmail = "reply@likedream.xyz"
|
||||
fromName = "若梦系统"
|
||||
|
||||
|
||||
@@ -55,4 +55,4 @@ cpdailyTask = "0.5"
|
||||
cpdailyLeave = "4"
|
||||
cpdailyPhone = "0.25"
|
||||
[task]
|
||||
concurrency = 20
|
||||
concurrency = 80
|
||||
@@ -1,403 +0,0 @@
|
||||
# 刷课接口文档
|
||||
|
||||
## 接口列表
|
||||
|
||||
### 1. 获取刷课列表
|
||||
|
||||
**接口地址**: `GET /course`
|
||||
|
||||
**请求参数**:
|
||||
|
||||
| 参数名 | 类型 | 必填 | 说明 |
|
||||
|--------|------|------|------|
|
||||
| type | string | 否 | 类型,可选值:`xxt`(学习通) |
|
||||
| username | string | 否 | 账号(模糊搜索) |
|
||||
| status | string | 否 | 状态,可选值:`not_start`(未开始)、`waiting`(等待中)、`doing`(进行中)、`done`(已完成)、`fail`(失败)、`pause`(暂停) |
|
||||
| page | int | 否 | 页码,默认 1 |
|
||||
| size | int | 否 | 每页数量,默认 10 |
|
||||
|
||||
**返回示例**:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"message": "success",
|
||||
"data": [
|
||||
{
|
||||
"id": 1,
|
||||
"user_id": 1,
|
||||
"username": "学习通账号",
|
||||
"password": "",
|
||||
"type": "xxt",
|
||||
"course_name": "大学英语",
|
||||
"course_id": "123456",
|
||||
"need": "task",
|
||||
"status": "waiting",
|
||||
"task_count": 10,
|
||||
"success_count": 5,
|
||||
"exam_state": "not_start",
|
||||
"violence": "no",
|
||||
"desc": "备注信息",
|
||||
"create_time": "2024-01-01T00:00:00Z",
|
||||
"update_time": "2024-01-01T00:00:00Z"
|
||||
}
|
||||
],
|
||||
"total": 100
|
||||
}
|
||||
```
|
||||
|
||||
**字段说明**:
|
||||
|
||||
- `type`: 类型 - `xxt`(学习通)
|
||||
- `need`: 需要刷的内容 - `task`(任务点)、`exam`(考试)、`all`(全部)
|
||||
- `status`: 状态 - `not_start`(未开始)、`waiting`(等待中)、`doing`(进行中)、`done`(已完成)、`fail`(失败)、`pause`(暂停)
|
||||
- `exam_state`: 考试状态 - `not_start`(未开始)、`waiting`(等待中)、`doing`(进行中)、`done`(已完成)、`fail`(失败)
|
||||
- `violence`: 是否暴力刷课 - `no`(否)、`yes`(是)
|
||||
|
||||
---
|
||||
|
||||
### 2. 查询课程列表
|
||||
|
||||
**接口地址**: `POST /course/query`
|
||||
|
||||
**说明**: 通过学习通账号密码查询当前可选的课程列表,用于在添加刷课前选择课程。
|
||||
|
||||
**请求参数**:
|
||||
|
||||
| 参数名 | 类型 | 必填 | 说明 |
|
||||
|--------|------|------|------|
|
||||
| username | string | 是 | 学习通账号 |
|
||||
| password | string | 是 | 学习通密码 |
|
||||
|
||||
**请求示例**:
|
||||
|
||||
```json
|
||||
{
|
||||
"username": "学习通账号",
|
||||
"password": "学习通密码"
|
||||
}
|
||||
```
|
||||
|
||||
**返回示例**:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"message": "success",
|
||||
"data": [
|
||||
{
|
||||
"cpi": 123456,
|
||||
"key": "234567",
|
||||
"courseId": "345678",
|
||||
"chatId": "456789",
|
||||
"courseTeacher": "张老师",
|
||||
"courseName": "大学英语",
|
||||
"courseImage": "https://example.com/image.jpg",
|
||||
"courseImageBase64": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAA...",
|
||||
"courseDataId": 567890,
|
||||
"ContentID": 678901,
|
||||
"isstart": true,
|
||||
"state": 0
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**字段说明**:
|
||||
|
||||
- `cpi`: 用户唯一标识
|
||||
- `key`: 课程班级ID(classId)
|
||||
- `courseId`: 课程ID(**添加刷课时需要使用**)
|
||||
- `chatId`: 聊天ID
|
||||
- `courseTeacher`: 授课教师
|
||||
- `courseName`: 课程名称(**添加刷课时需要使用**)
|
||||
- `courseImage`: 课程封面图片URL
|
||||
- `courseImageBase64`: 课程封面图片Base64编码(包含Data URL前缀,可直接用于img标签的src属性)
|
||||
- `courseDataId`: 课程数据ID
|
||||
- `ContentID`: 内容ID
|
||||
- `isstart`: 是否已开课(true:已开课,false:未开课)
|
||||
- `state`: 课程状态(0:正常,1:已结束)
|
||||
|
||||
**注意事项**:
|
||||
|
||||
- `courseImageBase64` 字段已经包含了 Data URL 前缀(如 `data:image/jpeg;base64,`),可以直接设置到 `<img>` 标签的 `src` 属性
|
||||
- 如果图片下载失败,`courseImageBase64` 字段将为空字符串,此时可以使用 `courseImage` URL 作为备用
|
||||
|
||||
**错误示例**:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 400,
|
||||
"message": "登录失败,请检查账号密码",
|
||||
"data": null
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 3. 添加刷课
|
||||
|
||||
**接口地址**: `POST /course`
|
||||
|
||||
**请求参数**:
|
||||
|
||||
| 参数名 | 类型 | 必填 | 说明 |
|
||||
|--------|------|------|------|
|
||||
| username | string | 是 | 学习通账号 |
|
||||
| password | string | 是 | 学习通密码 |
|
||||
| type | string | 是 | 类型,目前只支持 `xxt`(学习通) |
|
||||
| course_name | string | 是 | 课程名称 |
|
||||
| course_id | string | 是 | 课程ID |
|
||||
| need | string | 是 | 需要刷的内容,可选值:`task`(任务点)、`exam`(考试)、`all`(全部) |
|
||||
| violence | string | 否 | 是否暴力刷课,可选值:`no`(否,默认)、`yes`(是) |
|
||||
| desc | string | 否 | 备注信息 |
|
||||
|
||||
**请求示例**:
|
||||
|
||||
```json
|
||||
{
|
||||
"username": "学习通账号",
|
||||
"password": "学习通密码",
|
||||
"type": "xxt",
|
||||
"course_name": "大学英语",
|
||||
"course_id": "123456",
|
||||
"need": "task",
|
||||
"violence": "no",
|
||||
"desc": "备注信息"
|
||||
}
|
||||
```
|
||||
|
||||
**返回示例**:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"message": "添加成功",
|
||||
"data": null
|
||||
}
|
||||
```
|
||||
|
||||
**错误示例**:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 400,
|
||||
"message": "该课程已存在刷课任务",
|
||||
"data": null
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 4. 修改刷课密码
|
||||
|
||||
**接口地址**: `PUT /course/password/{id}`
|
||||
|
||||
**路径参数**:
|
||||
|
||||
| 参数名 | 类型 | 必填 | 说明 |
|
||||
|--------|------|------|------|
|
||||
| id | int64 | 是 | 刷课任务ID |
|
||||
|
||||
**请求参数**:
|
||||
|
||||
| 参数名 | 类型 | 必填 | 说明 |
|
||||
|--------|------|------|------|
|
||||
| password | string | 是 | 新密码 |
|
||||
|
||||
**请求示例**:
|
||||
|
||||
```json
|
||||
{
|
||||
"password": "新密码"
|
||||
}
|
||||
```
|
||||
|
||||
**返回示例**:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"message": "密码修改成功",
|
||||
"data": null
|
||||
}
|
||||
```
|
||||
|
||||
**错误示例**:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 400,
|
||||
"message": "课程不存在或无权限操作",
|
||||
"data": null
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 5. 重刷课程
|
||||
|
||||
**接口地址**: `POST /course/restart/{id}`
|
||||
|
||||
**路径参数**:
|
||||
|
||||
| 参数名 | 类型 | 必填 | 说明 |
|
||||
|--------|------|------|------|
|
||||
| id | int64 | 是 | 刷课任务ID |
|
||||
|
||||
**说明**: 只有状态为 `done`(已完成)的课程才能重刷,重刷后会重置课程状态、任务数量、成功数量和考试状态。
|
||||
|
||||
**返回示例**:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"message": "重刷成功",
|
||||
"data": null
|
||||
}
|
||||
```
|
||||
|
||||
**错误示例**:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 400,
|
||||
"message": "只有已完成的课程才能重刷",
|
||||
"data": null
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 6. 暂停/恢复刷课
|
||||
|
||||
**接口地址**: `POST /course/pause/{id}`
|
||||
|
||||
**路径参数**:
|
||||
|
||||
| 参数名 | 类型 | 必填 | 说明 |
|
||||
|--------|------|------|------|
|
||||
| id | int64 | 是 | 刷课任务ID |
|
||||
|
||||
**说明**: 该接口会在暂停和恢复之间切换:
|
||||
- 如果当前状态是 `pause`(暂停),则恢复为 `waiting`(等待中)
|
||||
- 如果当前状态不是暂停,则设置为 `pause`(暂停)
|
||||
|
||||
**返回示例(暂停)**:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"message": "已暂停刷课",
|
||||
"data": null
|
||||
}
|
||||
```
|
||||
|
||||
**返回示例(恢复)**:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"message": "已恢复刷课",
|
||||
"data": null
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 7. 删除刷课
|
||||
|
||||
**接口地址**: `DELETE /course/{id}`
|
||||
|
||||
**路径参数**:
|
||||
|
||||
| 参数名 | 类型 | 必填 | 说明 |
|
||||
|--------|------|------|------|
|
||||
| id | int64 | 是 | 刷课任务ID |
|
||||
|
||||
**返回示例**:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"message": "删除成功",
|
||||
"data": null
|
||||
}
|
||||
```
|
||||
|
||||
**错误示例**:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 400,
|
||||
"message": "课程不存在或无权限操作",
|
||||
"data": null
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 枚举值说明
|
||||
|
||||
### 类型 (type)
|
||||
|
||||
| 值 | 说明 |
|
||||
|-----|------|
|
||||
| xxt | 学习通 |
|
||||
|
||||
### 需要刷的内容 (need)
|
||||
|
||||
| 值 | 说明 |
|
||||
|-----|------|
|
||||
| task | 任务点 |
|
||||
| exam | 考试 |
|
||||
| all | 全部 |
|
||||
|
||||
### 状态 (status)
|
||||
|
||||
| 值 | 说明 |
|
||||
|-----|------|
|
||||
| not_start | 未开始 |
|
||||
| waiting | 等待中 |
|
||||
| doing | 进行中 |
|
||||
| done | 已完成 |
|
||||
| fail | 失败 |
|
||||
| pause | 暂停 |
|
||||
|
||||
### 考试状态 (exam_state)
|
||||
|
||||
| 值 | 说明 |
|
||||
|-----|------|
|
||||
| not_start | 未开始 |
|
||||
| waiting | 等待中 |
|
||||
| doing | 进行中 |
|
||||
| done | 已完成 |
|
||||
| fail | 失败 |
|
||||
|
||||
### 是否暴力刷课 (violence)
|
||||
|
||||
| 值 | 说明 |
|
||||
|-----|------|
|
||||
| no | 否 |
|
||||
| yes | 是 |
|
||||
|
||||
---
|
||||
|
||||
## 通用说明
|
||||
|
||||
### 认证
|
||||
|
||||
所有接口都需要用户认证,需要在请求头中携带认证信息(具体认证方式根据项目配置)。
|
||||
|
||||
### 权限
|
||||
|
||||
用户只能操作自己创建的刷课任务,无法访问或修改其他用户的数据。
|
||||
|
||||
### 错误码
|
||||
|
||||
| 错误码 | 说明 |
|
||||
|--------|------|
|
||||
| 200 | 成功 |
|
||||
| 400 | 业务错误(如参数错误、权限不足等) |
|
||||
| 401 | 未认证 |
|
||||
| 500 | 服务器错误 |
|
||||
@@ -24,6 +24,6 @@ type ConfigListReq struct {
|
||||
}
|
||||
|
||||
type ConfigPublicGetReq struct {
|
||||
g.Meta `path:"/config/public/{key}" method:"get" tags:"Config" summary:"获取公开配置(无需认证)"`
|
||||
g.Meta `path:"/config/public/{key}" method:"get" tags:"Config" summary:"获取公开配置(无需认证)" auth:"false"`
|
||||
Key string `json:"key" v:"required#配置键不能为空"`
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package v1
|
||||
|
||||
import (
|
||||
"github.com/gogf/gf/v2/frame/g"
|
||||
"github.com/gogf/gf/v2/net/ghttp"
|
||||
)
|
||||
|
||||
type CpLeaveListReq struct {
|
||||
@@ -19,8 +20,18 @@ type GetLeaveListFromSystemReq struct {
|
||||
}
|
||||
|
||||
type CpLeaveReportReq struct {
|
||||
g.Meta `path:"/leave/report" method:"post" tags:"CpLeave" summary:"执行销假"`
|
||||
CpUserId int64 `json:"cpUserId" v:"required#今日校园账号ID不能为空"`
|
||||
LeaveId string `json:"leaveId" v:"required#请假记录ID不能为空"`
|
||||
Title string `json:"title" v:"required#请假记录标题不能为空"`
|
||||
g.Meta `path:"/leave/report" method:"post" tags:"CpLeave" summary:"执行销假"`
|
||||
CpUserId int64 `json:"cpUserId" v:"required#今日校园账号ID不能为空"`
|
||||
LeaveId string `json:"leaveId" v:"required#请假记录ID不能为空"`
|
||||
Title string `json:"title" v:"required#请假记录标题不能为空"`
|
||||
Longitude string `json:"longitude"` // 经度(可选,不传则使用系统默认)
|
||||
Latitude string `json:"latitude"` // 纬度(可选,不传则使用系统默认)
|
||||
Address string `json:"address"` // 地址(可选,不传则使用系统默认)
|
||||
ImageUrl string `json:"imageUrl"`
|
||||
}
|
||||
|
||||
type CpLeaveUploadReq struct {
|
||||
g.Meta `path:"/leave/upload" method:"post" tags:"CpLeave" summary:"上传销假图片"`
|
||||
File *ghttp.UploadFile `json:"file"`
|
||||
CpUserId int64 `json:"cpUserId"`
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
)
|
||||
|
||||
func TestAesDecrypt(t *testing.T) {
|
||||
str := "457xXTd3ZBTY0017ueFiMR0gFff7W2NuXH39lkT/kvTTCKqhXA1vjJwgtmzRgZOC+qEpA3O9GmAroR+A1lORFVqe+q7o3alKOKj4rxPUUSwcyqGUF2LMNbxFXrmWUEPzeedbdUtlI+ufR8SLXNHbZSs0ECPy864bwUAuSDhFcD235c/3AbiTNacXIZZ+paK0T6GWxS291XbffgNCpGFa+5jCaP7/t9erCUjId9Zm4hmoaHkhqGRKAgZrLwuICa4lTFNOQqLA1N/Dljd/ZPVbZGVZaJQ0oV3zEaQQDCWuSTcWF4JVVeaCw9s/8mqkarg+RIz3/OA8dCvc8Wo6auMGzXT6IlisCX+S5TuPlhKKo1ttAW1KrWNg2nkZMxyD+kTKtNijvZRsdQnA8znVp0q2p0byyvzevaB6qSYUM9NBcaxyxkes5Bd1lKCTUHPaG93Jz4SQ+B8MQ1rLm13eWY8uME/WBTOraG7Rgmba32zBccC6BWwV3ncNGhu7hLL0dIhdgIpuxnrFmXDw4HX/IM+cnCxAFo7+EfzKb4l3yDMyr2d+0tDlVl4UbUR2uRTGz5r/7vVI1WtLgM0fiRTk56JU5BwRrutS7KonsLzugbEp/E8="
|
||||
str := "gTIjjNBTwN0Vdv2o5ZlTZ6gHbFcIA0MV0caRqvv/50tptfoSO+VASLxpQZWy Xa86lY21QtmXhwlvTsfd3XR819O0IUi2FynPOM6s0pDsSndM2JhhqoRNXBTK 4WqfMgt0RCQJ38KP8XtM5O+Ktkj1YHHM/OVEGqOxRcUh2M++JJCheJbSs+aQ 2T3va13/GWJH7PEd8JVEJgBiO3wXLOb9+CvvWuU/Frc9nNNxQL7LrgZTdQAv C9Yt+5/a2n41reOeOs7Bu5C4FFlHQSs71Rom/HtIhL67x1ecIre1rbgK9xxz 1AhTEHY6nhdZmktPGJD5CfxvLVWIeLv09CjKqdSaNodkP4e9YTScNEZ2s8TK y8Xhv8L0r6gllC9B3nla4GRe+lqMvhDPDZx7PFu7kxFspf9yoM4eOpgWfCr9 xbDwxO9cXphiktfWsQiX28W4g2jCFFEazh01WBtpjM9LsLfbBgZA+z3jgfYa AXZuOvFQMJuUnLyOIGPtsaSTwXFDlJwNRgEw+Ctl22JSJbbu1yOoM9S6Ge27 rUVMhbAS5snVbNbLhgAymQLQQVLRwfsMLbtUfLTZuCC8zO8d16eOYw56+DqR QWNG1EXQz3CLeFDs2hFqcNWrAt773qANQ3zLPA65"
|
||||
str = strings.ReplaceAll(str, " ", "")
|
||||
decodeString, _ := base64.StdEncoding.DecodeString(str)
|
||||
decrypt := AesDecryptForCat(decodeString)
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"likedream-goframe/internal/utils"
|
||||
|
||||
"github.com/bytedance/sonic"
|
||||
"github.com/gogf/gf/v2/net/ghttp"
|
||||
"github.com/google/uuid"
|
||||
"github.com/samber/oops"
|
||||
"resty.dev/v3"
|
||||
@@ -80,11 +81,54 @@ func UploadImageFromStorage(ctx context.Context, host string, imageId uuid.UUID,
|
||||
return previewUrl
|
||||
}
|
||||
|
||||
func UploadImageFromFile(ctx context.Context, host string, file *ghttp.UploadFile, taskType types.TaskType, client *resty.Client) string {
|
||||
|
||||
imageUploadPolicy := GetUploadPolicyAsync(ctx, host, taskType, client)
|
||||
open, _ := file.Open()
|
||||
resp, e := client.R().
|
||||
SetMultipartFields(&resty.MultipartField{
|
||||
Name: "x-obs-acl",
|
||||
Values: []string{"public-read"},
|
||||
}, &resty.MultipartField{
|
||||
Name: "AccessKeyId",
|
||||
Values: []string{imageUploadPolicy.AccessId},
|
||||
}, &resty.MultipartField{
|
||||
Name: "key",
|
||||
Values: []string{imageUploadPolicy.FileName},
|
||||
}, &resty.MultipartField{
|
||||
Name: "signature",
|
||||
Values: []string{imageUploadPolicy.Signature},
|
||||
}, &resty.MultipartField{
|
||||
Name: "policy",
|
||||
Values: []string{imageUploadPolicy.Policy},
|
||||
}, &resty.MultipartField{
|
||||
Name: "content-type",
|
||||
Values: []string{file.Header.Get("Content-Type")},
|
||||
}, &resty.MultipartField{
|
||||
Name: "file",
|
||||
FileName: "file",
|
||||
Reader: open,
|
||||
}).
|
||||
Post(imageUploadPolicy.Host)
|
||||
|
||||
utils.OkOrPanic(e, oops.WithContext(ctx).Wrap)
|
||||
|
||||
if resp.StatusCode() > 299 {
|
||||
utils.OkOrPanic(errors.NewBusinessError(503, "上传图片失败: "+utils.ReadString(resp.Body)), oops.WithContext(ctx).With("response", utils.ReadString(resp.Body)).Wrap)
|
||||
}
|
||||
|
||||
previewUrl := GetPreviewUrlAsync(ctx, host, imageUploadPolicy.FileName, taskType, client)
|
||||
|
||||
return previewUrl
|
||||
}
|
||||
|
||||
// GetPreviewUrlAsync 用于获取图片预览地址
|
||||
func GetPreviewUrlAsync(ctx context.Context, host string, fileKey string, taskType types.TaskType, client *resty.Client) string {
|
||||
var apiPath string
|
||||
if taskType == types.TaskTypeSleepCheck {
|
||||
apiPath = "/previewAttachment"
|
||||
} else if taskType == types.TaskTypeLeave {
|
||||
apiPath = "/obs/previewAttachment"
|
||||
} else {
|
||||
apiPath = "/sign/previewAttachment"
|
||||
}
|
||||
@@ -164,6 +208,8 @@ func GetImageUploadUrlPrefix(ctx context.Context, taskType types.TaskType) strin
|
||||
return "/wec-counselor-sign-apps/stu"
|
||||
case types.TaskTypeCollection:
|
||||
return "/wec-counselor-collector-apps/student/collector"
|
||||
case types.TaskTypeLeave:
|
||||
return "/wec-counselor-leave-apps/leave"
|
||||
default:
|
||||
utils.OkOrPanic(errors.NewBusinessError(503, "未知的任务类型"), oops.WithContext(ctx).Wrap)
|
||||
panic("unreachable")
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
package model
|
||||
|
||||
type Attach struct {
|
||||
Type int `json:"type"`
|
||||
Url string `json:"url"`
|
||||
}
|
||||
@@ -3,14 +3,19 @@ package leave
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
v1 "likedream-goframe/internal/api/v1"
|
||||
"likedream-goframe/internal/application/cpdaily"
|
||||
"likedream-goframe/internal/application/cpdaily/cryptoutil"
|
||||
"likedream-goframe/internal/application/cpdaily/imageuploader"
|
||||
"likedream-goframe/internal/application/cpdaily/leave/model"
|
||||
"likedream-goframe/internal/application/cpdaily/task/leavetype"
|
||||
"likedream-goframe/internal/application/cpdaily/taskhelper"
|
||||
"likedream-goframe/internal/application/cpdaily/types"
|
||||
"likedream-goframe/internal/common/errors"
|
||||
"likedream-goframe/internal/utils"
|
||||
|
||||
"github.com/gogf/gf/v2/container/gvar"
|
||||
"github.com/gogf/gf/v2/net/ghttp"
|
||||
"github.com/google/uuid"
|
||||
"github.com/samber/oops"
|
||||
"github.com/tidwall/gjson"
|
||||
@@ -66,14 +71,25 @@ func (c *CpdailyReportApp) GetLeaveList() []leavetype.LeaveListOne {
|
||||
if row.Get("status").String() == "4" {
|
||||
continue
|
||||
}
|
||||
id := row.Get("id").String()
|
||||
detail := c.LeaveDetail(id)
|
||||
leaveOne := leavetype.LeaveListOne{
|
||||
Id: row.Get("id").String(),
|
||||
LeaveType: row.Get("leaveType").String(),
|
||||
CreateTime: row.Get("createTime").String(),
|
||||
Reason: row.Get("leaveReason").String(),
|
||||
AceEndTime: row.Get("actEndTime").String(),
|
||||
Status: row.Get("status").String(),
|
||||
Id: row.Get("id").String(),
|
||||
LeaveType: row.Get("leaveType").String(),
|
||||
CreateTime: row.Get("createTime").String(),
|
||||
Reason: row.Get("leaveReason").String(),
|
||||
AceEndTime: row.Get("actEndTime").String(),
|
||||
Status: row.Get("status").String(),
|
||||
ChooseAttendance: detail.Get("leaveType.chooseAttendance").Int(),
|
||||
//Longitude: detail.Get("detail.applyLocation.longitude").String(),
|
||||
//Latitude: detail.Get("detail.applyLocation.latitude").String(),
|
||||
//Address: detail.Get("detail.applyLocation.address").String(),
|
||||
|
||||
Longitude: detail.Get("leaveExtends.0.longitude").String(),
|
||||
Latitude: detail.Get("leaveExtends.0.latitude").String(),
|
||||
Address: detail.Get("leaveExtends.0.address").String(),
|
||||
}
|
||||
|
||||
listList = append(listList, leaveOne)
|
||||
}
|
||||
return listList
|
||||
@@ -104,17 +120,33 @@ func (c *CpdailyReportApp) LeaveDetail(leaveId string) gjson.Result {
|
||||
return datas
|
||||
}
|
||||
|
||||
func (c *CpdailyReportApp) FillReportForm(detail gjson.Result) map[string]*gvar.Var {
|
||||
func (c *CpdailyReportApp) UploadImage(ctx context.Context, file *ghttp.UploadFile) string {
|
||||
return imageuploader.UploadImageFromFile(ctx, c.host, file, types.TaskTypeLeave, c.client)
|
||||
}
|
||||
|
||||
func (c *CpdailyReportApp) FillReportForm(detail gjson.Result, req *v1.CpLeaveReportReq) map[string]*gvar.Var {
|
||||
resultForm := make(map[string]*gvar.Var)
|
||||
resultForm["id"] = gvar.New(detail.Get("detail.id").String())
|
||||
resultForm["needApproval"] = gvar.New(1)
|
||||
resultForm["leaveType"] = gvar.New(detail.Get("leaveType.code").String())
|
||||
resultForm["reportLocation"] = gvar.New(detail.Get("detail.applyLocation.address").String())
|
||||
if req.Address == "" {
|
||||
resultForm["reportLocation"] = gvar.New(detail.Get("leaveExtends.0.address").String())
|
||||
} else {
|
||||
resultForm["reportLocation"] = gvar.New(req.Address)
|
||||
}
|
||||
resultForm["approverWid"] = gvar.New("")
|
||||
resultForm["reportApplyExplain"] = gvar.New(nil)
|
||||
//resultForm["reportAttach"] = gvar.New(detail.Get("detail.applyAttach").Array())
|
||||
resultForm["reportAttach"] = gvar.New([]string{})
|
||||
resultForm["uaIsCpadaily"] = gvar.New(true)
|
||||
if req.ImageUrl != "" {
|
||||
var attach []model.Attach
|
||||
attach = append(attach, model.Attach{
|
||||
Type: 1,
|
||||
Url: req.ImageUrl,
|
||||
})
|
||||
resultForm["reportAttach"] = gvar.New(attach)
|
||||
} else {
|
||||
resultForm["reportAttach"] = gvar.New([]string{})
|
||||
}
|
||||
return resultForm
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -7,4 +7,9 @@ type LeaveListOne struct {
|
||||
AceEndTime string `json:"aceEndTime"`
|
||||
Reason string `json:"reason"`
|
||||
Status string `json:"status"`
|
||||
// 销假时填充的位置信息
|
||||
Longitude string `json:"longitude"` // 经度
|
||||
Latitude string `json:"latitude"` // 纬度
|
||||
Address string `json:"address"` // 地址
|
||||
ChooseAttendance int64 `json:"chooseAttendance"` // 是否需要图片 1需要 0 不需要
|
||||
}
|
||||
|
||||
@@ -6,4 +6,5 @@ const (
|
||||
TaskTypeCollection = TaskType(iota)
|
||||
TaskTypeSign
|
||||
TaskTypeSleepCheck
|
||||
TaskTypeLeave
|
||||
)
|
||||
|
||||
@@ -50,10 +50,14 @@ var ErrTimeRestriction = errors2.NewBusinessError(499, "当前时间不在允许
|
||||
// TimeCheckFunc 时间检查回调函数类型,返回 true 表示可以继续执行
|
||||
type TimeCheckFunc func() bool
|
||||
|
||||
// TaskCompleteCallback 任务点完成回调函数类型
|
||||
type TaskCompleteCallback func()
|
||||
|
||||
type XuexitongCourse struct {
|
||||
client *resty.Client
|
||||
userID string
|
||||
timeCheckFunc TimeCheckFunc // 时间检查回调,每个任务点完成后调用
|
||||
client *resty.Client
|
||||
userID string
|
||||
timeCheckFunc TimeCheckFunc // 时间检查回调,每个任务点完成后调用
|
||||
taskCompleteCallback TaskCompleteCallback // 任务点完成回调
|
||||
}
|
||||
|
||||
func NewXuexitongCourse(client *resty.Client) *XuexitongCourse {
|
||||
@@ -67,6 +71,18 @@ func (c *XuexitongCourse) SetTimeCheckFunc(fn TimeCheckFunc) {
|
||||
c.timeCheckFunc = fn
|
||||
}
|
||||
|
||||
// SetTaskCompleteCallback 设置任务点完成回调函数
|
||||
func (c *XuexitongCourse) SetTaskCompleteCallback(fn TaskCompleteCallback) {
|
||||
c.taskCompleteCallback = fn
|
||||
}
|
||||
|
||||
// onTaskComplete 任务点完成时调用
|
||||
func (c *XuexitongCourse) onTaskComplete() {
|
||||
if c.taskCompleteCallback != nil {
|
||||
c.taskCompleteCallback()
|
||||
}
|
||||
}
|
||||
|
||||
// checkTimeRestriction 检查时间限制,如果设置了回调且返回 false,则返回时间限制错误
|
||||
func (c *XuexitongCourse) checkTimeRestriction() error {
|
||||
if c.timeCheckFunc != nil && !c.timeCheckFunc() {
|
||||
@@ -138,7 +154,13 @@ func (c *XuexitongCourse) PullCourseList(ctx context.Context) []entity.XueXiTCou
|
||||
courseID = strings.Split(strings.Split(sqUrl, "courseId=")[1], "&")[0]
|
||||
}
|
||||
if strings.Contains(sqUrl, "userId=") {
|
||||
c.userID = strings.Split(sqUrl, "userId=")[1]
|
||||
userIDPart := strings.Split(sqUrl, "userId=")[1]
|
||||
// 处理 userId 后面可能还有其他参数的情况
|
||||
if idx := strings.Index(userIDPart, "&"); idx != -1 {
|
||||
c.userID = userIDPart[:idx]
|
||||
} else {
|
||||
c.userID = userIDPart
|
||||
}
|
||||
}
|
||||
|
||||
course := entity.XueXiTCourse{
|
||||
@@ -315,6 +337,13 @@ func (c *XuexitongCourse) FetchChapterPointStatus(ctx context.Context, course en
|
||||
"courseid": {strconv.Itoa(courseID)},
|
||||
}
|
||||
|
||||
logger.Logger.Debug("FetchChapterPointStatus 请求参数",
|
||||
zap.String("userID", c.userID),
|
||||
zap.Int("classID", classID),
|
||||
zap.Int("courseID", courseID),
|
||||
zap.Int("cpi", course.Cpi),
|
||||
zap.Int("nodesCount", len(nodes)))
|
||||
|
||||
var body string
|
||||
err := retry.Do(func() error {
|
||||
resp, err := c.client.R().SetHeaders(map[string]string{
|
||||
@@ -332,12 +361,24 @@ func (c *XuexitongCourse) FetchChapterPointStatus(ctx context.Context, course en
|
||||
return nil, err
|
||||
}
|
||||
|
||||
logger.Logger.Debug("FetchChapterPointStatus 响应", zap.String("body", body))
|
||||
|
||||
var status entity.ChapterPointStatus
|
||||
err = json.Unmarshal([]byte(body), &status)
|
||||
if err != nil {
|
||||
logger.Logger.Error("FetchChapterPointStatus 解析失败", zap.Error(err), zap.String("body", body))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 更新章节的 PointTotal 和 PointFinish 字段
|
||||
for i := range chapters {
|
||||
chapterIDStr := strconv.Itoa(chapters[i].ID)
|
||||
if pointData, exists := status[chapterIDStr]; exists {
|
||||
chapters[i].PointTotal = pointData.UnFinishCount + pointData.FinishCount
|
||||
chapters[i].PointFinish = pointData.FinishCount
|
||||
}
|
||||
}
|
||||
|
||||
return status, nil
|
||||
}
|
||||
|
||||
@@ -432,6 +473,8 @@ func (c *XuexitongCourse) FetchChapterCards(ctx context.Context, course entity.X
|
||||
continue
|
||||
}
|
||||
pointType, ok := iframe.Other["module"]
|
||||
// 调试日志:打印每个 iframe 的 module 类型
|
||||
logger.Logger.Debug("解析到任务点", zap.String("module", pointType), zap.Bool("hasModule", ok), zap.Any("data", iframe.Data))
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
@@ -485,7 +528,7 @@ func (c *XuexitongCourse) FetchChapterCards(ctx context.Context, course entity.X
|
||||
Type: "insertbook",
|
||||
})
|
||||
|
||||
case "insertwork":
|
||||
case "work", "insertwork":
|
||||
workID, _ := iframe.Data["workid"].(string)
|
||||
schoolID, _ := iframe.Data["schoolid"].(string)
|
||||
jobID, _ := iframe.Data["_jobid"].(string)
|
||||
@@ -506,7 +549,7 @@ func (c *XuexitongCourse) FetchChapterCards(ctx context.Context, course entity.X
|
||||
JobID: jobID,
|
||||
})
|
||||
|
||||
case "insertlink":
|
||||
case "hyperlink", "insertlink":
|
||||
jobID, _ := iframe.Data["_jobid"].(string)
|
||||
if jobID == "" {
|
||||
continue
|
||||
@@ -1009,6 +1052,7 @@ func (c *XuexitongCourse) AutoPlayVideo(ctx context.Context, course entity.XueXi
|
||||
if err := json.Unmarshal([]byte(playReport), &result); err == nil {
|
||||
if isPassed, ok := result["isPassed"].(bool); ok && isPassed {
|
||||
logger.Logger.Info("视频播放完成", zap.String("jobID", p.JobID))
|
||||
c.onTaskComplete() // 任务点完成回调
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -1025,6 +1069,7 @@ func (c *XuexitongCourse) AutoPlayVideo(ctx context.Context, course entity.XueXi
|
||||
if err := json.Unmarshal([]byte(playReport), &result); err == nil {
|
||||
if isPassed, ok := result["isPassed"].(bool); ok && isPassed {
|
||||
logger.Logger.Info("视频播放完成", zap.String("jobID", p.JobID))
|
||||
c.onTaskComplete() // 任务点完成回调
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -1055,6 +1100,7 @@ func (c *XuexitongCourse) AutoReadDocument(ctx context.Context, course entity.Xu
|
||||
if err := json.Unmarshal([]byte(report), &result); err == nil {
|
||||
if status, ok := result["status"].(bool); ok && status {
|
||||
logger.Logger.Info("文档刷课完成", zap.String("jobID", p.JobID), zap.String("title", p.Title))
|
||||
c.onTaskComplete() // 任务点完成回调
|
||||
return nil
|
||||
}
|
||||
if msg, ok := result["msg"].(string); ok {
|
||||
@@ -1149,22 +1195,10 @@ func (c *XuexitongCourse) AutoStudyCourse(ctx context.Context, course entity.Xue
|
||||
|
||||
logger.Logger.Info(fmt.Sprintf("课程 %s 共有 %d 个章节", course.CourseName, len(chapters)))
|
||||
|
||||
// 获取章节任务点状态
|
||||
status, err := c.FetchChapterPointStatus(ctx, course, chapters)
|
||||
// 获取章节任务点状态(会自动更新 chapters 中每个章节的 PointTotal 和 PointFinish)
|
||||
_, err := c.FetchChapterPointStatus(ctx, course, chapters)
|
||||
if err != nil {
|
||||
logger.Logger.Warn("获取章节状态失败", zap.Error(err))
|
||||
} else {
|
||||
// 更新章节状态
|
||||
for i := range chapters {
|
||||
if pointData, exists := status[strconv.Itoa(chapters[i].ID)]; exists {
|
||||
if pointData.UnFinishCount != 0 && pointData.TotalCount == 0 {
|
||||
chapters[i].PointTotal = pointData.UnFinishCount
|
||||
} else {
|
||||
chapters[i].PointTotal = pointData.TotalCount
|
||||
}
|
||||
chapters[i].PointFinish = pointData.FinishCount
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 遍历所有章节
|
||||
@@ -1501,6 +1535,7 @@ func (c *XuexitongCourse) AutoCompleteHyperlink(ctx context.Context, course enti
|
||||
if err := json.Unmarshal([]byte(report), &result); err == nil {
|
||||
if status, ok := result["status"].(bool); ok && status {
|
||||
logger.Logger.Info("外链刷课完成", zap.String("jobID", p.JobID), zap.String("title", p.Title))
|
||||
c.onTaskComplete() // 任务点完成回调
|
||||
return nil
|
||||
}
|
||||
if msg, ok := result["msg"].(string); ok {
|
||||
@@ -1592,6 +1627,7 @@ func (c *XuexitongCourse) AutoWatchLive(ctx context.Context, course entity.XueXi
|
||||
|
||||
if p.VideoCompletePercent >= 90 {
|
||||
logger.Logger.Info("直播刷课完成", zap.String("title", p.Title))
|
||||
c.onTaskComplete() // 任务点完成回调
|
||||
break
|
||||
}
|
||||
|
||||
|
||||
@@ -40,6 +40,9 @@ const (
|
||||
ConfigBasePointCpdailyTask = "basePoint.cpdailyTask"
|
||||
ConfigBasePointCpdailyLeave = "basePoint.cpdailyLeave"
|
||||
ConfigBasePointCpdailyPhone = "basePoint.cpdailyPhone"
|
||||
|
||||
// 系统配置
|
||||
ConfigSystemAllowRegister = "system.allowRegister" // 是否允许注册
|
||||
)
|
||||
|
||||
const (
|
||||
|
||||
@@ -26,6 +26,11 @@ func (c CpLeaveCtrlV1) Report(ctx context.Context, req *v1.CpLeaveReportReq) (re
|
||||
return service.Global.CpLeave.Report(ctx, req), nil
|
||||
}
|
||||
|
||||
func (c CpLeaveCtrlV1) Upload(ctx context.Context, req *v1.CpLeaveUploadReq) (res *utils.Response[string], err error) {
|
||||
defer utils.Pass(&err)
|
||||
return service.Global.CpLeave.Upload(ctx, req), nil
|
||||
}
|
||||
|
||||
func NewCpLeaveCtrlV1() ICpLeaveCtrlV1 {
|
||||
return &CpLeaveCtrlV1{}
|
||||
}
|
||||
|
||||
@@ -11,4 +11,5 @@ type ICpLeaveCtrlV1 interface {
|
||||
GetLeaveListFromSystem(ctx context.Context, req *v1.GetLeaveListFromSystemReq) (*utils.Response[any], error)
|
||||
List(ctx context.Context, req *v1.CpLeaveListReq) (*utils.Response[[]*ent.CpLeave], error)
|
||||
Report(ctx context.Context, req *v1.CpLeaveReportReq) (*utils.Response[any], error)
|
||||
Upload(ctx context.Context, req *v1.CpLeaveUploadReq) (*utils.Response[string], error)
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"encoding/json"
|
||||
"likedream-goframe/internal/api/v1"
|
||||
"likedream-goframe/internal/framework/captcha"
|
||||
"likedream-goframe/internal/framework/errors"
|
||||
"likedream-goframe/internal/framework/redis"
|
||||
"likedream-goframe/internal/service"
|
||||
"likedream-goframe/internal/utils"
|
||||
@@ -64,7 +63,6 @@ func (c *UserLoginV1) Register(ctx context.Context, req *v1.UserRegisterReq) (re
|
||||
if !captcha.VerifyCaptcha(dots, req.Dots) {
|
||||
return utils.Fail(10003, "验证码错误"), nil
|
||||
}
|
||||
utils.OkOrPanic(errors.NewBusinessError(400, "注册功能暂时关闭,请等待重新开放"))
|
||||
return service.Global.UserLogin.Register(ctx, req), nil
|
||||
}
|
||||
|
||||
|
||||
@@ -47,9 +47,9 @@ type CourseEntity struct {
|
||||
// Violence holds the value of the "violence" field.
|
||||
Violence courseentity.Violence `json:"violence,omitempty"`
|
||||
// Nodes holds the value of the "nodes" field.
|
||||
Nodes string `json:"nodes,omitempty"`
|
||||
Nodes string `json:"-"`
|
||||
// CompletedNodes holds the value of the "completed_nodes" field.
|
||||
CompletedNodes string `json:"completed_nodes,omitempty"`
|
||||
CompletedNodes string `json:"-"`
|
||||
// Desc holds the value of the "desc" field.
|
||||
Desc string `json:"desc,omitempty"`
|
||||
// Edges holds the relations/edges for other nodes in the graph.
|
||||
@@ -294,11 +294,9 @@ func (_m *CourseEntity) String() string {
|
||||
builder.WriteString("violence=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.Violence))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("nodes=")
|
||||
builder.WriteString(_m.Nodes)
|
||||
builder.WriteString("nodes=<sensitive>")
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("completed_nodes=")
|
||||
builder.WriteString(_m.CompletedNodes)
|
||||
builder.WriteString("completed_nodes=<sensitive>")
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("desc=")
|
||||
builder.WriteString(_m.Desc)
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -29,8 +29,8 @@ func (CourseEntity) Fields() []ent.Field {
|
||||
field.Int("success_count").Default(0), // 成功数量
|
||||
field.Enum("exam_state").Values("not_start", "waiting", "doing", "done", "fail").Default("not_start"), // 考试状态
|
||||
field.Enum("violence").Values("no", "yes").Default("no"), // 是否暴力刷课
|
||||
field.Text("nodes").Optional(), // 所有节点信息(JSON格式)
|
||||
field.Text("completed_nodes").Optional(), // 已完成的节点ID列表(JSON格式)
|
||||
field.Text("nodes").Optional().Sensitive(), // 所有节点信息(JSON格式)
|
||||
field.Text("completed_nodes").Optional().Sensitive(), // 已完成的节点ID列表(JSON格式)
|
||||
field.String("desc").Optional(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,175 +0,0 @@
|
||||
// ENT数据库文件,请勿编辑。
|
||||
|
||||
package sysannouncement
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"likedream-goframe/internal/framework/ent2"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
)
|
||||
|
||||
const (
|
||||
// Label holds the string label denoting the sysannouncement type in the database.
|
||||
Label = "sys_announcement"
|
||||
// FieldID holds the string denoting the id field in the database.
|
||||
FieldID = "id"
|
||||
// FieldCreateTime holds the string denoting the create_time field in the database.
|
||||
FieldCreateTime = "create_time"
|
||||
// FieldUpdateTime holds the string denoting the update_time field in the database.
|
||||
FieldUpdateTime = "update_time"
|
||||
// FieldTitle holds the string denoting the title field in the database.
|
||||
FieldTitle = "title"
|
||||
// FieldContent holds the string denoting the content field in the database.
|
||||
FieldContent = "content"
|
||||
// FieldStatus holds the string denoting the status field in the database.
|
||||
FieldStatus = "status"
|
||||
// FieldPinned holds the string denoting the pinned field in the database.
|
||||
FieldPinned = "pinned"
|
||||
// FieldOrder holds the string denoting the order field in the database.
|
||||
FieldOrder = "order"
|
||||
// FieldCreatorID holds the string denoting the creator_id field in the database.
|
||||
FieldCreatorID = "creator_id"
|
||||
// EdgeCreator holds the string denoting the creator edge name in mutations.
|
||||
EdgeCreator = "creator"
|
||||
// Table holds the table name of the sysannouncement in the database.
|
||||
Table = "sys_announcement"
|
||||
// CreatorTable is the table that holds the creator relation/edge.
|
||||
CreatorTable = "sys_announcement"
|
||||
// CreatorInverseTable is the table name for the SysUser entity.
|
||||
// It exists in this package in order to avoid circular dependency with the "sysuser" package.
|
||||
CreatorInverseTable = "sys_user"
|
||||
// CreatorColumn is the table column denoting the creator relation/edge.
|
||||
CreatorColumn = "creator_id"
|
||||
)
|
||||
|
||||
// Columns holds all SQL columns for sysannouncement fields.
|
||||
var Columns = []string{
|
||||
FieldID,
|
||||
FieldCreateTime,
|
||||
FieldUpdateTime,
|
||||
FieldTitle,
|
||||
FieldContent,
|
||||
FieldStatus,
|
||||
FieldPinned,
|
||||
FieldOrder,
|
||||
FieldCreatorID,
|
||||
}
|
||||
|
||||
// ValidColumn reports if the column name is valid (part of the table columns).
|
||||
func ValidColumn(column string) bool {
|
||||
for i := range Columns {
|
||||
if column == Columns[i] {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Note that the variables below are initialized by the runtime
|
||||
// package on the initialization of the application. Therefore,
|
||||
// it should be imported in the main as follows:
|
||||
//
|
||||
// import _ "likedream-goframe/internal/ent/runtime"
|
||||
var (
|
||||
Hooks [1]ent.Hook
|
||||
// DefaultCreateTime holds the default value on creation for the "create_time" field.
|
||||
DefaultCreateTime func() *ent2.CustomTime
|
||||
// DefaultUpdateTime holds the default value on creation for the "update_time" field.
|
||||
DefaultUpdateTime func() *ent2.CustomTime
|
||||
// DefaultPinned holds the default value on creation for the "pinned" field.
|
||||
DefaultPinned bool
|
||||
// DefaultOrder holds the default value on creation for the "order" field.
|
||||
DefaultOrder uint
|
||||
)
|
||||
|
||||
// Status defines the type for the "status" enum field.
|
||||
type Status string
|
||||
|
||||
// StatusDraft is the default value of the Status enum.
|
||||
const DefaultStatus = StatusDraft
|
||||
|
||||
// Status values.
|
||||
const (
|
||||
StatusDraft Status = "draft"
|
||||
StatusPublished Status = "published"
|
||||
StatusArchived Status = "archived"
|
||||
)
|
||||
|
||||
func (s Status) String() string {
|
||||
return string(s)
|
||||
}
|
||||
|
||||
// StatusValidator is a validator for the "status" field enum values. It is called by the builders before save.
|
||||
func StatusValidator(s Status) error {
|
||||
switch s {
|
||||
case StatusDraft, StatusPublished, StatusArchived:
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("sysannouncement: invalid enum value for status field: %q", s)
|
||||
}
|
||||
}
|
||||
|
||||
// OrderOption defines the ordering options for the SysAnnouncement queries.
|
||||
type OrderOption func(*sql.Selector)
|
||||
|
||||
// ByID orders the results by the id field.
|
||||
func ByID(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldID, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByCreateTime orders the results by the create_time field.
|
||||
func ByCreateTime(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldCreateTime, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByUpdateTime orders the results by the update_time field.
|
||||
func ByUpdateTime(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldUpdateTime, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByTitle orders the results by the title field.
|
||||
func ByTitle(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldTitle, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByContent orders the results by the content field.
|
||||
func ByContent(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldContent, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByStatus orders the results by the status field.
|
||||
func ByStatus(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldStatus, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByPinned orders the results by the pinned field.
|
||||
func ByPinned(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldPinned, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByOrder orders the results by the order field.
|
||||
func ByOrder(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldOrder, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByCreatorID orders the results by the creator_id field.
|
||||
func ByCreatorID(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldCreatorID, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByCreatorField orders the results by creator field.
|
||||
func ByCreatorField(field string, opts ...sql.OrderTermOption) OrderOption {
|
||||
return func(s *sql.Selector) {
|
||||
sqlgraph.OrderByNeighborTerms(s, newCreatorStep(), sql.OrderByField(field, opts...))
|
||||
}
|
||||
}
|
||||
func newCreatorStep() *sqlgraph.Step {
|
||||
return sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.To(CreatorInverseTable, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.M2O, true, CreatorTable, CreatorColumn),
|
||||
)
|
||||
}
|
||||
@@ -1,496 +0,0 @@
|
||||
// ENT数据库文件,请勿编辑。
|
||||
|
||||
package sysannouncement
|
||||
|
||||
import (
|
||||
"likedream-goframe/internal/ent/internal"
|
||||
"likedream-goframe/internal/ent/predicate"
|
||||
"likedream-goframe/internal/framework/ent2"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
)
|
||||
|
||||
// ID filters vertices based on their ID field.
|
||||
func ID(id int64) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDEQ applies the EQ predicate on the ID field.
|
||||
func IDEQ(id int64) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDNEQ applies the NEQ predicate on the ID field.
|
||||
func IDNEQ(id int64) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldNEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDIn applies the In predicate on the ID field.
|
||||
func IDIn(ids ...int64) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldIn(FieldID, ids...))
|
||||
}
|
||||
|
||||
// IDNotIn applies the NotIn predicate on the ID field.
|
||||
func IDNotIn(ids ...int64) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldNotIn(FieldID, ids...))
|
||||
}
|
||||
|
||||
// IDGT applies the GT predicate on the ID field.
|
||||
func IDGT(id int64) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldGT(FieldID, id))
|
||||
}
|
||||
|
||||
// IDGTE applies the GTE predicate on the ID field.
|
||||
func IDGTE(id int64) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldGTE(FieldID, id))
|
||||
}
|
||||
|
||||
// IDLT applies the LT predicate on the ID field.
|
||||
func IDLT(id int64) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldLT(FieldID, id))
|
||||
}
|
||||
|
||||
// IDLTE applies the LTE predicate on the ID field.
|
||||
func IDLTE(id int64) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldLTE(FieldID, id))
|
||||
}
|
||||
|
||||
// CreateTime applies equality check predicate on the "create_time" field. It's identical to CreateTimeEQ.
|
||||
func CreateTime(v *ent2.CustomTime) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldEQ(FieldCreateTime, v))
|
||||
}
|
||||
|
||||
// UpdateTime applies equality check predicate on the "update_time" field. It's identical to UpdateTimeEQ.
|
||||
func UpdateTime(v *ent2.CustomTime) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldEQ(FieldUpdateTime, v))
|
||||
}
|
||||
|
||||
// Title applies equality check predicate on the "title" field. It's identical to TitleEQ.
|
||||
func Title(v string) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldEQ(FieldTitle, v))
|
||||
}
|
||||
|
||||
// Content applies equality check predicate on the "content" field. It's identical to ContentEQ.
|
||||
func Content(v string) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldEQ(FieldContent, v))
|
||||
}
|
||||
|
||||
// Pinned applies equality check predicate on the "pinned" field. It's identical to PinnedEQ.
|
||||
func Pinned(v bool) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldEQ(FieldPinned, v))
|
||||
}
|
||||
|
||||
// Order applies equality check predicate on the "order" field. It's identical to OrderEQ.
|
||||
func Order(v uint) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldEQ(FieldOrder, v))
|
||||
}
|
||||
|
||||
// CreatorID applies equality check predicate on the "creator_id" field. It's identical to CreatorIDEQ.
|
||||
func CreatorID(v int64) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldEQ(FieldCreatorID, v))
|
||||
}
|
||||
|
||||
// CreateTimeEQ applies the EQ predicate on the "create_time" field.
|
||||
func CreateTimeEQ(v *ent2.CustomTime) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldEQ(FieldCreateTime, v))
|
||||
}
|
||||
|
||||
// CreateTimeNEQ applies the NEQ predicate on the "create_time" field.
|
||||
func CreateTimeNEQ(v *ent2.CustomTime) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldNEQ(FieldCreateTime, v))
|
||||
}
|
||||
|
||||
// CreateTimeIn applies the In predicate on the "create_time" field.
|
||||
func CreateTimeIn(vs ...*ent2.CustomTime) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldIn(FieldCreateTime, vs...))
|
||||
}
|
||||
|
||||
// CreateTimeNotIn applies the NotIn predicate on the "create_time" field.
|
||||
func CreateTimeNotIn(vs ...*ent2.CustomTime) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldNotIn(FieldCreateTime, vs...))
|
||||
}
|
||||
|
||||
// CreateTimeGT applies the GT predicate on the "create_time" field.
|
||||
func CreateTimeGT(v *ent2.CustomTime) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldGT(FieldCreateTime, v))
|
||||
}
|
||||
|
||||
// CreateTimeGTE applies the GTE predicate on the "create_time" field.
|
||||
func CreateTimeGTE(v *ent2.CustomTime) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldGTE(FieldCreateTime, v))
|
||||
}
|
||||
|
||||
// CreateTimeLT applies the LT predicate on the "create_time" field.
|
||||
func CreateTimeLT(v *ent2.CustomTime) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldLT(FieldCreateTime, v))
|
||||
}
|
||||
|
||||
// CreateTimeLTE applies the LTE predicate on the "create_time" field.
|
||||
func CreateTimeLTE(v *ent2.CustomTime) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldLTE(FieldCreateTime, v))
|
||||
}
|
||||
|
||||
// CreateTimeContains applies the Contains predicate on the "create_time" field.
|
||||
func CreateTimeContains(v *ent2.CustomTime) predicate.SysAnnouncement {
|
||||
vc := v.String()
|
||||
return predicate.SysAnnouncement(sql.FieldContains(FieldCreateTime, vc))
|
||||
}
|
||||
|
||||
// CreateTimeHasPrefix applies the HasPrefix predicate on the "create_time" field.
|
||||
func CreateTimeHasPrefix(v *ent2.CustomTime) predicate.SysAnnouncement {
|
||||
vc := v.String()
|
||||
return predicate.SysAnnouncement(sql.FieldHasPrefix(FieldCreateTime, vc))
|
||||
}
|
||||
|
||||
// CreateTimeHasSuffix applies the HasSuffix predicate on the "create_time" field.
|
||||
func CreateTimeHasSuffix(v *ent2.CustomTime) predicate.SysAnnouncement {
|
||||
vc := v.String()
|
||||
return predicate.SysAnnouncement(sql.FieldHasSuffix(FieldCreateTime, vc))
|
||||
}
|
||||
|
||||
// CreateTimeEqualFold applies the EqualFold predicate on the "create_time" field.
|
||||
func CreateTimeEqualFold(v *ent2.CustomTime) predicate.SysAnnouncement {
|
||||
vc := v.String()
|
||||
return predicate.SysAnnouncement(sql.FieldEqualFold(FieldCreateTime, vc))
|
||||
}
|
||||
|
||||
// CreateTimeContainsFold applies the ContainsFold predicate on the "create_time" field.
|
||||
func CreateTimeContainsFold(v *ent2.CustomTime) predicate.SysAnnouncement {
|
||||
vc := v.String()
|
||||
return predicate.SysAnnouncement(sql.FieldContainsFold(FieldCreateTime, vc))
|
||||
}
|
||||
|
||||
// UpdateTimeEQ applies the EQ predicate on the "update_time" field.
|
||||
func UpdateTimeEQ(v *ent2.CustomTime) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldEQ(FieldUpdateTime, v))
|
||||
}
|
||||
|
||||
// UpdateTimeNEQ applies the NEQ predicate on the "update_time" field.
|
||||
func UpdateTimeNEQ(v *ent2.CustomTime) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldNEQ(FieldUpdateTime, v))
|
||||
}
|
||||
|
||||
// UpdateTimeIn applies the In predicate on the "update_time" field.
|
||||
func UpdateTimeIn(vs ...*ent2.CustomTime) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldIn(FieldUpdateTime, vs...))
|
||||
}
|
||||
|
||||
// UpdateTimeNotIn applies the NotIn predicate on the "update_time" field.
|
||||
func UpdateTimeNotIn(vs ...*ent2.CustomTime) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldNotIn(FieldUpdateTime, vs...))
|
||||
}
|
||||
|
||||
// UpdateTimeGT applies the GT predicate on the "update_time" field.
|
||||
func UpdateTimeGT(v *ent2.CustomTime) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldGT(FieldUpdateTime, v))
|
||||
}
|
||||
|
||||
// UpdateTimeGTE applies the GTE predicate on the "update_time" field.
|
||||
func UpdateTimeGTE(v *ent2.CustomTime) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldGTE(FieldUpdateTime, v))
|
||||
}
|
||||
|
||||
// UpdateTimeLT applies the LT predicate on the "update_time" field.
|
||||
func UpdateTimeLT(v *ent2.CustomTime) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldLT(FieldUpdateTime, v))
|
||||
}
|
||||
|
||||
// UpdateTimeLTE applies the LTE predicate on the "update_time" field.
|
||||
func UpdateTimeLTE(v *ent2.CustomTime) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldLTE(FieldUpdateTime, v))
|
||||
}
|
||||
|
||||
// UpdateTimeContains applies the Contains predicate on the "update_time" field.
|
||||
func UpdateTimeContains(v *ent2.CustomTime) predicate.SysAnnouncement {
|
||||
vc := v.String()
|
||||
return predicate.SysAnnouncement(sql.FieldContains(FieldUpdateTime, vc))
|
||||
}
|
||||
|
||||
// UpdateTimeHasPrefix applies the HasPrefix predicate on the "update_time" field.
|
||||
func UpdateTimeHasPrefix(v *ent2.CustomTime) predicate.SysAnnouncement {
|
||||
vc := v.String()
|
||||
return predicate.SysAnnouncement(sql.FieldHasPrefix(FieldUpdateTime, vc))
|
||||
}
|
||||
|
||||
// UpdateTimeHasSuffix applies the HasSuffix predicate on the "update_time" field.
|
||||
func UpdateTimeHasSuffix(v *ent2.CustomTime) predicate.SysAnnouncement {
|
||||
vc := v.String()
|
||||
return predicate.SysAnnouncement(sql.FieldHasSuffix(FieldUpdateTime, vc))
|
||||
}
|
||||
|
||||
// UpdateTimeEqualFold applies the EqualFold predicate on the "update_time" field.
|
||||
func UpdateTimeEqualFold(v *ent2.CustomTime) predicate.SysAnnouncement {
|
||||
vc := v.String()
|
||||
return predicate.SysAnnouncement(sql.FieldEqualFold(FieldUpdateTime, vc))
|
||||
}
|
||||
|
||||
// UpdateTimeContainsFold applies the ContainsFold predicate on the "update_time" field.
|
||||
func UpdateTimeContainsFold(v *ent2.CustomTime) predicate.SysAnnouncement {
|
||||
vc := v.String()
|
||||
return predicate.SysAnnouncement(sql.FieldContainsFold(FieldUpdateTime, vc))
|
||||
}
|
||||
|
||||
// TitleEQ applies the EQ predicate on the "title" field.
|
||||
func TitleEQ(v string) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldEQ(FieldTitle, v))
|
||||
}
|
||||
|
||||
// TitleNEQ applies the NEQ predicate on the "title" field.
|
||||
func TitleNEQ(v string) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldNEQ(FieldTitle, v))
|
||||
}
|
||||
|
||||
// TitleIn applies the In predicate on the "title" field.
|
||||
func TitleIn(vs ...string) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldIn(FieldTitle, vs...))
|
||||
}
|
||||
|
||||
// TitleNotIn applies the NotIn predicate on the "title" field.
|
||||
func TitleNotIn(vs ...string) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldNotIn(FieldTitle, vs...))
|
||||
}
|
||||
|
||||
// TitleGT applies the GT predicate on the "title" field.
|
||||
func TitleGT(v string) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldGT(FieldTitle, v))
|
||||
}
|
||||
|
||||
// TitleGTE applies the GTE predicate on the "title" field.
|
||||
func TitleGTE(v string) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldGTE(FieldTitle, v))
|
||||
}
|
||||
|
||||
// TitleLT applies the LT predicate on the "title" field.
|
||||
func TitleLT(v string) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldLT(FieldTitle, v))
|
||||
}
|
||||
|
||||
// TitleLTE applies the LTE predicate on the "title" field.
|
||||
func TitleLTE(v string) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldLTE(FieldTitle, v))
|
||||
}
|
||||
|
||||
// TitleContains applies the Contains predicate on the "title" field.
|
||||
func TitleContains(v string) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldContains(FieldTitle, v))
|
||||
}
|
||||
|
||||
// TitleHasPrefix applies the HasPrefix predicate on the "title" field.
|
||||
func TitleHasPrefix(v string) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldHasPrefix(FieldTitle, v))
|
||||
}
|
||||
|
||||
// TitleHasSuffix applies the HasSuffix predicate on the "title" field.
|
||||
func TitleHasSuffix(v string) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldHasSuffix(FieldTitle, v))
|
||||
}
|
||||
|
||||
// TitleEqualFold applies the EqualFold predicate on the "title" field.
|
||||
func TitleEqualFold(v string) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldEqualFold(FieldTitle, v))
|
||||
}
|
||||
|
||||
// TitleContainsFold applies the ContainsFold predicate on the "title" field.
|
||||
func TitleContainsFold(v string) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldContainsFold(FieldTitle, v))
|
||||
}
|
||||
|
||||
// ContentEQ applies the EQ predicate on the "content" field.
|
||||
func ContentEQ(v string) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldEQ(FieldContent, v))
|
||||
}
|
||||
|
||||
// ContentNEQ applies the NEQ predicate on the "content" field.
|
||||
func ContentNEQ(v string) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldNEQ(FieldContent, v))
|
||||
}
|
||||
|
||||
// ContentIn applies the In predicate on the "content" field.
|
||||
func ContentIn(vs ...string) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldIn(FieldContent, vs...))
|
||||
}
|
||||
|
||||
// ContentNotIn applies the NotIn predicate on the "content" field.
|
||||
func ContentNotIn(vs ...string) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldNotIn(FieldContent, vs...))
|
||||
}
|
||||
|
||||
// ContentGT applies the GT predicate on the "content" field.
|
||||
func ContentGT(v string) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldGT(FieldContent, v))
|
||||
}
|
||||
|
||||
// ContentGTE applies the GTE predicate on the "content" field.
|
||||
func ContentGTE(v string) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldGTE(FieldContent, v))
|
||||
}
|
||||
|
||||
// ContentLT applies the LT predicate on the "content" field.
|
||||
func ContentLT(v string) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldLT(FieldContent, v))
|
||||
}
|
||||
|
||||
// ContentLTE applies the LTE predicate on the "content" field.
|
||||
func ContentLTE(v string) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldLTE(FieldContent, v))
|
||||
}
|
||||
|
||||
// ContentContains applies the Contains predicate on the "content" field.
|
||||
func ContentContains(v string) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldContains(FieldContent, v))
|
||||
}
|
||||
|
||||
// ContentHasPrefix applies the HasPrefix predicate on the "content" field.
|
||||
func ContentHasPrefix(v string) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldHasPrefix(FieldContent, v))
|
||||
}
|
||||
|
||||
// ContentHasSuffix applies the HasSuffix predicate on the "content" field.
|
||||
func ContentHasSuffix(v string) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldHasSuffix(FieldContent, v))
|
||||
}
|
||||
|
||||
// ContentEqualFold applies the EqualFold predicate on the "content" field.
|
||||
func ContentEqualFold(v string) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldEqualFold(FieldContent, v))
|
||||
}
|
||||
|
||||
// ContentContainsFold applies the ContainsFold predicate on the "content" field.
|
||||
func ContentContainsFold(v string) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldContainsFold(FieldContent, v))
|
||||
}
|
||||
|
||||
// StatusEQ applies the EQ predicate on the "status" field.
|
||||
func StatusEQ(v Status) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldEQ(FieldStatus, v))
|
||||
}
|
||||
|
||||
// StatusNEQ applies the NEQ predicate on the "status" field.
|
||||
func StatusNEQ(v Status) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldNEQ(FieldStatus, v))
|
||||
}
|
||||
|
||||
// StatusIn applies the In predicate on the "status" field.
|
||||
func StatusIn(vs ...Status) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldIn(FieldStatus, vs...))
|
||||
}
|
||||
|
||||
// StatusNotIn applies the NotIn predicate on the "status" field.
|
||||
func StatusNotIn(vs ...Status) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldNotIn(FieldStatus, vs...))
|
||||
}
|
||||
|
||||
// PinnedEQ applies the EQ predicate on the "pinned" field.
|
||||
func PinnedEQ(v bool) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldEQ(FieldPinned, v))
|
||||
}
|
||||
|
||||
// PinnedNEQ applies the NEQ predicate on the "pinned" field.
|
||||
func PinnedNEQ(v bool) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldNEQ(FieldPinned, v))
|
||||
}
|
||||
|
||||
// OrderEQ applies the EQ predicate on the "order" field.
|
||||
func OrderEQ(v uint) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldEQ(FieldOrder, v))
|
||||
}
|
||||
|
||||
// OrderNEQ applies the NEQ predicate on the "order" field.
|
||||
func OrderNEQ(v uint) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldNEQ(FieldOrder, v))
|
||||
}
|
||||
|
||||
// OrderIn applies the In predicate on the "order" field.
|
||||
func OrderIn(vs ...uint) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldIn(FieldOrder, vs...))
|
||||
}
|
||||
|
||||
// OrderNotIn applies the NotIn predicate on the "order" field.
|
||||
func OrderNotIn(vs ...uint) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldNotIn(FieldOrder, vs...))
|
||||
}
|
||||
|
||||
// OrderGT applies the GT predicate on the "order" field.
|
||||
func OrderGT(v uint) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldGT(FieldOrder, v))
|
||||
}
|
||||
|
||||
// OrderGTE applies the GTE predicate on the "order" field.
|
||||
func OrderGTE(v uint) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldGTE(FieldOrder, v))
|
||||
}
|
||||
|
||||
// OrderLT applies the LT predicate on the "order" field.
|
||||
func OrderLT(v uint) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldLT(FieldOrder, v))
|
||||
}
|
||||
|
||||
// OrderLTE applies the LTE predicate on the "order" field.
|
||||
func OrderLTE(v uint) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldLTE(FieldOrder, v))
|
||||
}
|
||||
|
||||
// CreatorIDEQ applies the EQ predicate on the "creator_id" field.
|
||||
func CreatorIDEQ(v int64) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldEQ(FieldCreatorID, v))
|
||||
}
|
||||
|
||||
// CreatorIDNEQ applies the NEQ predicate on the "creator_id" field.
|
||||
func CreatorIDNEQ(v int64) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldNEQ(FieldCreatorID, v))
|
||||
}
|
||||
|
||||
// CreatorIDIn applies the In predicate on the "creator_id" field.
|
||||
func CreatorIDIn(vs ...int64) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldIn(FieldCreatorID, vs...))
|
||||
}
|
||||
|
||||
// CreatorIDNotIn applies the NotIn predicate on the "creator_id" field.
|
||||
func CreatorIDNotIn(vs ...int64) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.FieldNotIn(FieldCreatorID, vs...))
|
||||
}
|
||||
|
||||
// HasCreator applies the HasEdge predicate on the "creator" edge.
|
||||
func HasCreator() predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(func(s *sql.Selector) {
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.M2O, true, CreatorTable, CreatorColumn),
|
||||
)
|
||||
schemaConfig := internal.SchemaConfigFromContext(s.Context())
|
||||
step.To.Schema = schemaConfig.SysUser
|
||||
step.Edge.Schema = schemaConfig.SysAnnouncement
|
||||
sqlgraph.HasNeighbors(s, step)
|
||||
})
|
||||
}
|
||||
|
||||
// HasCreatorWith applies the HasEdge predicate on the "creator" edge with a given conditions (other predicates).
|
||||
func HasCreatorWith(preds ...predicate.SysUser) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(func(s *sql.Selector) {
|
||||
step := newCreatorStep()
|
||||
schemaConfig := internal.SchemaConfigFromContext(s.Context())
|
||||
step.To.Schema = schemaConfig.SysUser
|
||||
step.Edge.Schema = schemaConfig.SysAnnouncement
|
||||
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
|
||||
for _, p := range preds {
|
||||
p(s)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// And groups predicates with the AND operator between them.
|
||||
func And(predicates ...predicate.SysAnnouncement) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.AndPredicates(predicates...))
|
||||
}
|
||||
|
||||
// Or groups predicates with the OR operator between them.
|
||||
func Or(predicates ...predicate.SysAnnouncement) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.OrPredicates(predicates...))
|
||||
}
|
||||
|
||||
// Not applies the not operator on the given predicate.
|
||||
func Not(p predicate.SysAnnouncement) predicate.SysAnnouncement {
|
||||
return predicate.SysAnnouncement(sql.NotPredicates(p))
|
||||
}
|
||||
@@ -40,19 +40,15 @@ func (c *CpdailyTaskHandler) ProcessTask(ctx context.Context, task *asynq.Task)
|
||||
e := gob.NewDecoder(bytes.NewReader(task.Payload())).Decode(&taskPayload)
|
||||
utils.OkOrPanic(e, oops.WithContext(ctx).With("payload", task.Payload(), "type", task.Type()).In("CpdailyTask.DecodePayload").Wrap)
|
||||
|
||||
// 查询指定的任务和关联今日校园用户
|
||||
targetTask, e := db.Global.CpTask.Query().Where(cptask.ID(taskPayload.CpTaskID)).
|
||||
WithCpUser().
|
||||
WithSysUser().
|
||||
First(ctx)
|
||||
if ent.IsNotFound(e) {
|
||||
utils.OkOrPanic(oops.WithContext(ctx).With("task_id", taskPayload.CpTaskID).In("CpdailyTask.ProcessTask").Wrap(e))
|
||||
}
|
||||
utils.OkOrPanic(e, oops.WithContext(ctx).With("task_id", taskPayload.CpTaskID).In("CpdailyTask.ProcessTask").Wrap)
|
||||
|
||||
db.Global.CpTask.UpdateOneID(taskPayload.CpTaskID).SetTaskStatus(cptask.TaskStatusDoing).ExecX(ctx)
|
||||
|
||||
// 先注册错误处理,确保任何阶段的错误都能被捕获并重置状态
|
||||
var targetTask *ent.CpTask
|
||||
defer utils.HandleError(func(err error) {
|
||||
// 如果 targetTask 还没查询到,只能重置状态为 not_start,让任务重新入队
|
||||
if targetTask == nil {
|
||||
db.Global.CpTask.UpdateOneID(taskPayload.CpTaskID).SetTaskStatus(cptask.TaskStatusNotStart).Exec(ctx)
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// 执行失败应该更新下次执行时间
|
||||
executeTime := utils.GetCpdailyNextExecuteTime(targetTask)
|
||||
e := db.Global.CpTask.UpdateOneID(taskPayload.CpTaskID).SetNextExecuteTime(executeTime).SetTaskStatus(cptask.TaskStatusFail).Exec(ctx)
|
||||
@@ -90,6 +86,15 @@ func (c *CpdailyTaskHandler) ProcessTask(ctx context.Context, task *asynq.Task)
|
||||
panic(err)
|
||||
})
|
||||
|
||||
// 查询指定的任务和关联今日校园用户
|
||||
targetTask, e = db.Global.CpTask.Query().Where(cptask.ID(taskPayload.CpTaskID)).
|
||||
WithCpUser().
|
||||
WithSysUser().
|
||||
First(ctx)
|
||||
utils.OkOrPanic(e, oops.WithContext(ctx).With("task_id", taskPayload.CpTaskID).In("CpdailyTask.ProcessTask").Wrap)
|
||||
|
||||
db.Global.CpTask.UpdateOneID(taskPayload.CpTaskID).SetTaskStatus(cptask.TaskStatusDoing).ExecX(ctx)
|
||||
|
||||
// 查询学校详情
|
||||
schoolDetail := school.GetSchoolDetail(ctx, targetTask.Edges.CpUser.SchoolID)
|
||||
cookie := targetTask.Edges.CpUser.Cookie
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"likedream-goframe/internal/framework/logger"
|
||||
"likedream-goframe/internal/framework/model/email"
|
||||
"likedream-goframe/internal/utils"
|
||||
"time"
|
||||
|
||||
"github.com/hibiken/asynq"
|
||||
"github.com/samber/oops"
|
||||
@@ -44,7 +45,10 @@ func (h *EmailTaskHandler) ProcessTask(ctx context.Context, task *asynq.Task) (e
|
||||
|
||||
message.SetBodyString(mail.TypeTextHTML, payload.Body)
|
||||
|
||||
client, e := mail.NewClient(payload.SMTPHost, mail.WithPort(payload.SMTPPort), mail.WithSMTPAuth(mail.SMTPAuthAutoDiscover),
|
||||
client, e := mail.NewClient(payload.SMTPHost, mail.WithPort(payload.SMTPPort),
|
||||
mail.WithSMTPAuth(mail.SMTPAuthLogin), // Outlook 使用 LOGIN 认证
|
||||
mail.WithTLSPortPolicy(mail.TLSMandatory),
|
||||
mail.WithTimeout(30*time.Second), // 连接超时 30 秒
|
||||
mail.WithUsername(payload.SMTPUsername), mail.WithPassword(payload.SMTPPassword))
|
||||
utils.OkOrPanic(e, oops.WithContext(ctx).Wrap)
|
||||
|
||||
|
||||
@@ -2,21 +2,85 @@ package schedule
|
||||
|
||||
import (
|
||||
"context"
|
||||
cst2 "likedream-goframe/internal/common/cst"
|
||||
"likedream-goframe/internal/common/db"
|
||||
"likedream-goframe/internal/ent/cptask"
|
||||
"likedream-goframe/internal/framework/queue"
|
||||
"likedream-goframe/internal/utils"
|
||||
|
||||
"github.com/gogf/gf/v2/frame/g"
|
||||
"github.com/gogf/gf/v2/os/gctx"
|
||||
"github.com/hibiken/asynq"
|
||||
)
|
||||
|
||||
func Init(ctx context.Context) {
|
||||
queue.InitClient(ctx)
|
||||
initServer(ctx)
|
||||
initInspector(ctx)
|
||||
cleanupStuckTasks(ctx) // 清理卡住的任务
|
||||
initScanner()
|
||||
initPeriodicTasks(ctx)
|
||||
}
|
||||
|
||||
// cleanupStuckTasks 清理服务重启时卡在 queue 或 doing 状态的任务
|
||||
// 检查 asynq 队列中是否有 archived 的任务,如果有则删除并重置数据库状态
|
||||
func cleanupStuckTasks(ctx context.Context) {
|
||||
// 获取所有状态为 queue 或 doing 的任务
|
||||
stuckTasks, err := db.Global.CpTask.Query().
|
||||
Where(
|
||||
cptask.Or(
|
||||
cptask.TaskStatusEQ(cptask.TaskStatusQueue),
|
||||
cptask.TaskStatusEQ(cptask.TaskStatusDoing),
|
||||
),
|
||||
).
|
||||
All(ctx)
|
||||
|
||||
if err != nil {
|
||||
g.Log().Warningf(ctx, "查询卡住的任务失败: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
if len(stuckTasks) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
// 检查 archived 队列中的任务数量
|
||||
archivedTasks, err := globalInspector.ListArchivedTasks(cst2.TaskQueueCpdaily, asynq.PageSize(10000))
|
||||
if err != nil {
|
||||
g.Log().Warningf(ctx, "获取 archived 任务列表失败: %v", err)
|
||||
}
|
||||
|
||||
// 删除所有 archived 的任务,让它们可以重新入队
|
||||
for _, task := range archivedTasks {
|
||||
if err := globalInspector.DeleteTask(cst2.TaskQueueCpdaily, task.ID); err != nil {
|
||||
g.Log().Debugf(ctx, "删除 archived 任务失败: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
if len(archivedTasks) > 0 {
|
||||
g.Log().Infof(ctx, "已清理 %d 个 archived 状态的 asynq 任务", len(archivedTasks))
|
||||
}
|
||||
|
||||
// 重置数据库中卡住的任务状态
|
||||
affected, err := db.Global.CpTask.Update().
|
||||
Where(
|
||||
cptask.Or(
|
||||
cptask.TaskStatusEQ(cptask.TaskStatusQueue),
|
||||
),
|
||||
).
|
||||
SetTaskStatus(cptask.TaskStatusNotStart).
|
||||
Save(ctx)
|
||||
|
||||
if err != nil {
|
||||
g.Log().Warningf(ctx, "重置卡住的任务失败: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
if affected > 0 {
|
||||
g.Log().Infof(ctx, "已重置 %d 个卡住的任务状态为 not_start", affected)
|
||||
}
|
||||
}
|
||||
|
||||
func Stop() {
|
||||
globalScanner.StopScan()
|
||||
g.Log().Info(gctx.GetInitCtx(), "task scanner stopped")
|
||||
@@ -30,7 +94,10 @@ func Stop() {
|
||||
g.Log().Info(gctx.GetInitCtx(), "asynq client closed")
|
||||
|
||||
globalServer.Shutdown()
|
||||
g.Log().Info(gctx.GetInitCtx(), "asynq server stopped")
|
||||
g.Log().Info(gctx.GetInitCtx(), "asynq main server stopped")
|
||||
|
||||
auxiliaryServer.Shutdown()
|
||||
g.Log().Info(gctx.GetInitCtx(), "asynq auxiliary server stopped")
|
||||
|
||||
e = globalInspector.Close()
|
||||
utils.OkOrPanic(e)
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
cst2 "likedream-goframe/internal/common/cst"
|
||||
"likedream-goframe/internal/common/db"
|
||||
"likedream-goframe/internal/ent"
|
||||
"likedream-goframe/internal/ent/courseentity"
|
||||
"likedream-goframe/internal/ent/cptask"
|
||||
"likedream-goframe/internal/framework/queue"
|
||||
"likedream-goframe/internal/utils"
|
||||
@@ -26,6 +27,20 @@ import (
|
||||
var globalScanner *TaskScanner
|
||||
|
||||
func initScanner() {
|
||||
ctx := gctx.GetInitCtx()
|
||||
|
||||
// 应用启动时,将所有 StatusDoing(执行中)状态的学习通任务重置为 StatusWaiting
|
||||
// 这样可以确保应用重启后,之前正在执行的任务能够继续执行
|
||||
count, err := db.Global.CourseEntity.Update().
|
||||
Where(courseentity.StatusEQ(courseentity.StatusDoing)).
|
||||
SetStatus(courseentity.StatusWaiting).
|
||||
Save(ctx)
|
||||
if err != nil {
|
||||
g.Log().Warningf(ctx, "重置执行中的学习通任务失败: %v", err)
|
||||
} else if count > 0 {
|
||||
g.Log().Infof(ctx, "应用启动时重置了 %d 个执行中的学习通任务为等待状态", count)
|
||||
}
|
||||
|
||||
globalScanner = NewTaskScanner()
|
||||
go globalScanner.StartScan()
|
||||
}
|
||||
@@ -65,6 +80,7 @@ func (ts *TaskScanner) StartScan() {
|
||||
}
|
||||
|
||||
ts.scanCpdailyTask()
|
||||
ts.scanXuexitongTask()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -121,12 +137,16 @@ func (ts *TaskScanner) scanCpdailyTask() {
|
||||
year, month, day := currentTime.Date()
|
||||
execTime := time.Date(year, month, day, *task.ExecuteHour, *task.ExecuteMinute, 0, 0, cst2.TimeZoneShangHai)
|
||||
|
||||
// 添加随机延迟(0-30秒),分散同一时间点的任务执行,避免瞬间占满所有 worker
|
||||
randomDelay := time.Duration(task.ID%30) * time.Second
|
||||
execTime = execTime.Add(randomDelay)
|
||||
|
||||
e = utils.Catch(func() {
|
||||
queue.AddTask(ts.ctx, asynq.NewTask(cst2.TaskCpdaily, payloadWriter.Bytes()),
|
||||
asynq.Unique(5*time.Minute),
|
||||
asynq.Unique(2*time.Minute),
|
||||
asynq.MaxRetry(4),
|
||||
asynq.ProcessAt(execTime),
|
||||
asynq.Timeout(10*time.Minute),
|
||||
asynq.Timeout(5*time.Minute),
|
||||
asynq.Queue(cst2.TaskQueueCpdaily),
|
||||
)
|
||||
// 更新未开始的任务状态为队列中
|
||||
@@ -134,7 +154,8 @@ func (ts *TaskScanner) scanCpdailyTask() {
|
||||
})
|
||||
if e != nil {
|
||||
if errors.Is(e, asynq.ErrDuplicateTask) {
|
||||
// 任务已在队列中,不更新下次执行时间,等任务执行完成后再处理
|
||||
// 任务已在队列中,确保数据库状态也是 queue,然后跳过
|
||||
db.Global.CpTask.Update().Where(cptask.ID(task.ID)).SetTaskStatus(cptask.TaskStatusQueue).Exec(ts.ctx)
|
||||
g.Log().Debugf(ts.ctx, "任务ID %d 已在队列中,跳过本次扫描", task.ID)
|
||||
failedIDS = append(failedIDS, task.ID)
|
||||
continue
|
||||
@@ -186,3 +207,76 @@ func (ts *TaskScanner) scanCpdailyTask() {
|
||||
utils.LogError(ts.ctx, "重置过期任务下次执行时间失败", oops.With("task_id", task.ID, "next_execute_at", nextExecuteAt).Wrap(e))
|
||||
}
|
||||
}
|
||||
|
||||
// scanXuexitongTask 扫描学习通刷课任务
|
||||
func (ts *TaskScanner) scanXuexitongTask() {
|
||||
// 查询所有状态为not_start或waiting的课程
|
||||
allCourses := db.Global.CourseEntity.Query().
|
||||
Where(
|
||||
courseentity.Or(
|
||||
courseentity.StatusEQ(courseentity.StatusNotStart),
|
||||
courseentity.StatusEQ(courseentity.StatusWaiting),
|
||||
),
|
||||
).
|
||||
AllX(ts.ctx)
|
||||
|
||||
if len(allCourses) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
// 按暴力模式区分任务
|
||||
for _, course := range allCourses {
|
||||
// 检查是否暂停
|
||||
if course.Status == courseentity.StatusPause {
|
||||
continue
|
||||
}
|
||||
|
||||
payload := &XuexitongTaskPayload{
|
||||
CourseID: course.ID,
|
||||
}
|
||||
|
||||
payloadWriter := bytes.NewBuffer(nil)
|
||||
|
||||
e := gob.NewEncoder(payloadWriter).Encode(payload)
|
||||
utils.OkOrPanic(e, oops.WithContext(ts.ctx).With("payload", payload).In("XuexitongTaskScanner.scanXuexitongTask").Wrap)
|
||||
|
||||
// 根据violence字段选择队列和任务类型
|
||||
var queueName string
|
||||
var taskType string
|
||||
|
||||
if course.Violence == courseentity.ViolenceYes {
|
||||
queueName = cst2.TaskQueueXuexitongVio
|
||||
taskType = cst2.TaskXuexitongVio
|
||||
} else {
|
||||
queueName = cst2.TaskQueueXuexitong
|
||||
taskType = cst2.TaskXuexitong
|
||||
}
|
||||
|
||||
e = utils.Catch(func() {
|
||||
queue.AddTask(ts.ctx, asynq.NewTask(taskType, payloadWriter.Bytes()),
|
||||
//asynq.Unique(30*time.Minute), // 30分钟内去重
|
||||
asynq.MaxRetry(3),
|
||||
asynq.Timeout(2*time.Hour), // 刷课可能需要较长时间
|
||||
asynq.Queue(queueName),
|
||||
)
|
||||
// 更新状态为等待中
|
||||
db.Global.CourseEntity.Update().
|
||||
Where(courseentity.ID(course.ID), courseentity.StatusEQ(courseentity.StatusNotStart)).
|
||||
SetStatus(courseentity.StatusWaiting).
|
||||
Exec(ts.ctx)
|
||||
})
|
||||
if e != nil {
|
||||
if errors.Is(e, asynq.ErrDuplicateTask) {
|
||||
// 任务已在队列中,跳过
|
||||
g.Log().Debugf(ts.ctx, "学习通课程ID %d 已在队列中,跳过本次扫描", course.ID)
|
||||
continue
|
||||
} else if errors.Is(e, context.Canceled) {
|
||||
return
|
||||
} else {
|
||||
utils.LogError(ts.ctx, "扫描学习通任务时,入列失败", oops.With("course_id", course.ID).Wrap(e))
|
||||
}
|
||||
} else {
|
||||
g.Log().Debugf(ts.ctx, "学习通课程 %s (ID: %d) 已加入队列: %s", course.CourseName, course.ID, queueName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,13 +12,19 @@ import (
|
||||
"github.com/hibiken/asynq"
|
||||
)
|
||||
|
||||
var globalServer *asynq.Server
|
||||
var (
|
||||
// 主任务服务器:处理 cpdaily、xuexitong 等业务任务
|
||||
globalServer *asynq.Server
|
||||
// 辅助任务服务器:处理 email、reset 等轻量级任务
|
||||
auxiliaryServer *asynq.Server
|
||||
)
|
||||
|
||||
func initServer(ctx context.Context) {
|
||||
cfg := g.Cfg()
|
||||
|
||||
taskConcurrency := cfg.MustGetWithEnv(ctx, cst2.ConfigTaskConcurrency).Int()
|
||||
|
||||
// 主服务器:专门处理业务任务,使用大部分 worker
|
||||
globalServer = asynq.NewServerFromRedisClient(redis.GetClient(), asynq.Config{
|
||||
Concurrency: taskConcurrency,
|
||||
BaseContext: gctx.GetInitCtx,
|
||||
@@ -28,24 +34,45 @@ func initServer(ctx context.Context) {
|
||||
},
|
||||
DelayedTaskCheckInterval: 2 * time.Second,
|
||||
ErrorHandler: taskErrorHandler{},
|
||||
// 只处理业务队列,使用严格优先级模式
|
||||
StrictPriority: true,
|
||||
Queues: map[string]int{
|
||||
cst2.TaskQueueEmail: 2,
|
||||
cst2.TaskQueueCpdaily: 10,
|
||||
cst2.TaskQueueXuexitong: 5,
|
||||
cst2.TaskQueueCpdaily: 10, // 最高优先级
|
||||
cst2.TaskQueueXuexitongVio: 8,
|
||||
cst2.TaskQueueDefault: 1,
|
||||
cst2.TaskQueueXuexitong: 5,
|
||||
},
|
||||
})
|
||||
|
||||
mux := asynq.NewServeMux()
|
||||
// 辅助服务器:专门处理邮件等轻量级任务,独立的 worker 池
|
||||
auxiliaryServer = asynq.NewServerFromRedisClient(redis.GetClient(), asynq.Config{
|
||||
Concurrency: 5, // 邮件任务不需要太多并发
|
||||
BaseContext: gctx.GetInitCtx,
|
||||
TaskCheckInterval: 10 * time.Second,
|
||||
RetryDelayFunc: func(n int, _ error, _ *asynq.Task) time.Duration {
|
||||
return time.Duration(n) * 2 * time.Second
|
||||
},
|
||||
DelayedTaskCheckInterval: 2 * time.Second,
|
||||
Queues: map[string]int{
|
||||
cst2.TaskQueueEmail: 2,
|
||||
cst2.TaskQueueDefault: 1,
|
||||
},
|
||||
})
|
||||
|
||||
mux.Handle(cst2.TaskCpdaily, &CpdailyTaskHandler{})
|
||||
mux.Handle(cst2.TaskEmail, &EmailTaskHandler{})
|
||||
mux.Handle(cst2.TaskResetDaily, &ResetTaskHandler{})
|
||||
mux.Handle(cst2.TaskXuexitong, &XuexitongTaskHandler{})
|
||||
mux.Handle(cst2.TaskXuexitongVio, &XuexitongTaskHandler{})
|
||||
// 主服务器的任务处理器
|
||||
mainMux := asynq.NewServeMux()
|
||||
mainMux.Handle(cst2.TaskCpdaily, &CpdailyTaskHandler{})
|
||||
mainMux.Handle(cst2.TaskXuexitong, &XuexitongTaskHandler{})
|
||||
mainMux.Handle(cst2.TaskXuexitongVio, &XuexitongTaskHandler{})
|
||||
|
||||
e := globalServer.Start(mux)
|
||||
// 辅助服务器的任务处理器
|
||||
auxMux := asynq.NewServeMux()
|
||||
auxMux.Handle(cst2.TaskEmail, &EmailTaskHandler{})
|
||||
auxMux.Handle(cst2.TaskResetDaily, &ResetTaskHandler{})
|
||||
|
||||
e := globalServer.Start(mainMux)
|
||||
utils.OkOrPanic(e)
|
||||
|
||||
e = auxiliaryServer.Start(auxMux)
|
||||
utils.OkOrPanic(e)
|
||||
}
|
||||
|
||||
|
||||
@@ -112,6 +112,52 @@ func (h *XuexitongTaskHandler) ProcessTask(ctx context.Context, task *asynq.Task
|
||||
})
|
||||
}
|
||||
|
||||
// 先获取课程列表找到目标课程
|
||||
courseList := courseService.PullCourseList(ctx)
|
||||
var course *entity.XueXiTCourse
|
||||
for _, c := range courseList {
|
||||
if c.CourseID == targetCourse.CourseID {
|
||||
course = &c
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if course == nil {
|
||||
utils.OkOrPanic(errors.NewBusinessError(404, "未找到课程"))
|
||||
}
|
||||
|
||||
// 开始刷课前,先获取并更新任务点统计
|
||||
g.Log().Infof(ctx, "课程 %s 正在获取任务点统计...", targetCourse.CourseName)
|
||||
|
||||
chapters := courseService.PullCourseChapterList(ctx, *course)
|
||||
// FetchChapterPointStatus 会更新 chapters 中每个章节的 PointTotal 和 PointFinish
|
||||
_, statusErr := courseService.FetchChapterPointStatus(ctx, *course, chapters)
|
||||
if statusErr != nil {
|
||||
g.Log().Warningf(ctx, "获取章节任务点状态失败: %v", statusErr)
|
||||
} else {
|
||||
// 通过累加每个章节的 PointTotal 和 PointFinish 计算总数
|
||||
var totalPointCount, finishedPointCount int
|
||||
for _, chapter := range chapters {
|
||||
totalPointCount += chapter.PointTotal
|
||||
finishedPointCount += chapter.PointFinish
|
||||
}
|
||||
g.Log().Infof(ctx, "课程 %s 任务点统计: 总数 %d, 已完成 %d", targetCourse.CourseName, totalPointCount, finishedPointCount)
|
||||
|
||||
// 更新数据库
|
||||
db.Global.CourseEntity.UpdateOneID(taskPayload.CourseID).
|
||||
SetTaskCount(totalPointCount).
|
||||
SetSuccessCount(finishedPointCount).
|
||||
ExecX(ctx)
|
||||
}
|
||||
|
||||
// 设置任务点完成回调,每完成一个任务点更新 success_count
|
||||
courseService.SetTaskCompleteCallback(func() {
|
||||
// 增加 success_count
|
||||
db.Global.CourseEntity.UpdateOneID(taskPayload.CourseID).
|
||||
AddSuccessCount(1).
|
||||
ExecX(ctx)
|
||||
})
|
||||
|
||||
// 执行刷课
|
||||
err = courseService.AutoStudyByCourseID(ctx, targetCourse.CourseID)
|
||||
if err != nil {
|
||||
@@ -125,36 +171,32 @@ func (h *XuexitongTaskHandler) ProcessTask(ctx context.Context, task *asynq.Task
|
||||
utils.OkOrPanic(errors.NewBusinessErrorWithDetail(503, "刷课失败", err))
|
||||
}
|
||||
|
||||
// 刷课完成后,统计任务情况
|
||||
g.Log().Infof(ctx, "刷课完成,正在统计任务情况...")
|
||||
// 刷课完成后,重新统计任务情况
|
||||
g.Log().Infof(ctx, "刷课完成,正在重新统计任务情况...")
|
||||
|
||||
// 先获取课程列表找到目标课程
|
||||
courseList := courseService.PullCourseList(ctx)
|
||||
var course *entity.XueXiTCourse
|
||||
for _, c := range courseList {
|
||||
if c.CourseID == targetCourse.CourseID {
|
||||
course = &c
|
||||
break
|
||||
// 重新获取章节列表和任务点状态
|
||||
chaptersAfter := courseService.PullCourseChapterList(ctx, *course)
|
||||
// FetchChapterPointStatus 会更新 chapters 中每个章节的 PointTotal 和 PointFinish
|
||||
_, statusErrAfter := courseService.FetchChapterPointStatus(ctx, *course, chaptersAfter)
|
||||
|
||||
var totalPointCountAfter, finishedPointCountAfter int
|
||||
if statusErrAfter != nil {
|
||||
g.Log().Warningf(ctx, "获取章节任务点状态失败: %v", statusErrAfter)
|
||||
} else {
|
||||
// 通过累加每个章节的 PointTotal 和 PointFinish 计算总数
|
||||
for _, chapter := range chaptersAfter {
|
||||
totalPointCountAfter += chapter.PointTotal
|
||||
finishedPointCountAfter += chapter.PointFinish
|
||||
}
|
||||
}
|
||||
|
||||
totalTasks := 0
|
||||
if course != nil {
|
||||
// 获取章节列表
|
||||
chapters := courseService.PullCourseChapterList(ctx, *course)
|
||||
g.Log().Infof(ctx, "课程 %s 统计完成: 总任务点 %d, 已完成 %d", targetCourse.CourseName, totalPointCountAfter, finishedPointCountAfter)
|
||||
|
||||
// 统计总任务数(累加所有章节的JobCount)
|
||||
for _, chapter := range chapters {
|
||||
totalTasks += chapter.JobCount
|
||||
}
|
||||
}
|
||||
|
||||
g.Log().Infof(ctx, "课程 %s 统计完成: 总任务点 %d", targetCourse.CourseName, totalTasks)
|
||||
|
||||
// 更新数据库(暂时不统计完成数,只统计总数)
|
||||
// 更新数据库
|
||||
db.Global.CourseEntity.UpdateOneID(taskPayload.CourseID).
|
||||
SetStatus(courseentity.StatusDone).
|
||||
SetTaskCount(totalTasks).
|
||||
SetTaskCount(totalPointCountAfter).
|
||||
SetSuccessCount(finishedPointCountAfter).
|
||||
ExecX(ctx)
|
||||
|
||||
g.Log().Infof(ctx, "学习通刷课完成 - 课程: %s", targetCourse.CourseName)
|
||||
|
||||
@@ -36,7 +36,7 @@ func (s *ConfigServiceV1) Get(ctx context.Context, req *v1.ConfigGetReq) *utils.
|
||||
// PublicGet 获取公开配置(无需认证)
|
||||
func (s *ConfigServiceV1) PublicGet(ctx context.Context, req *v1.ConfigPublicGetReq) *utils.Response[*ent.SysConfig] {
|
||||
// 只允许获取特定的公开配置
|
||||
allowedKeys := []string{"system.announcement"}
|
||||
allowedKeys := []string{"system.announcement", "system.allowRegister"}
|
||||
|
||||
allowed := false
|
||||
for _, key := range allowedKeys {
|
||||
|
||||
@@ -13,9 +13,7 @@ import (
|
||||
"likedream-goframe/internal/ent/sysuser"
|
||||
"likedream-goframe/internal/framework/logger"
|
||||
"likedream-goframe/internal/utils"
|
||||
"strconv"
|
||||
|
||||
"github.com/bytedance/sonic"
|
||||
"go.uber.org/zap"
|
||||
"resty.dev/v3"
|
||||
)
|
||||
@@ -91,109 +89,8 @@ func (s CourseServiceV1) AddCourse(ctx context.Context, req *v1.AddCourseReq) *u
|
||||
if targetCourse == nil {
|
||||
utils.OkOrPanic(errors2.NewBusinessError(400, "未找到该课程"))
|
||||
}
|
||||
chapters := courseService.PullCourseChapterList(ctx, *targetCourse)
|
||||
|
||||
// 定义节点信息结构
|
||||
type NodeInfo struct {
|
||||
ChapterID string `json:"chapter_id"`
|
||||
ChapterName string `json:"chapter_name"`
|
||||
CardID string `json:"card_id"`
|
||||
CardTitle string `json:"card_title"`
|
||||
CardType string `json:"card_type"`
|
||||
}
|
||||
|
||||
var allNodes []NodeInfo
|
||||
var completedNodes []string
|
||||
|
||||
// 递归获取所有章节的任务点
|
||||
var collectNodes func(chapters []entity.XueXiTCourseChapter)
|
||||
collectNodes = func(chapters []entity.XueXiTCourseChapter) {
|
||||
for _, chapter := range chapters {
|
||||
// 如果有任务点,获取卡片信息
|
||||
if chapter.JobCount > 0 {
|
||||
cards, points, err := courseService.FetchChapterCards(ctx, *targetCourse, chapter.ID)
|
||||
if err != nil {
|
||||
logger.Logger.Warn("获取章节任务点失败", zap.String("chapter", chapter.Name), zap.Error(err))
|
||||
} else if points != nil {
|
||||
chapterIDStr := strconv.Itoa(chapter.ID)
|
||||
// 统计视频任务点
|
||||
for _, video := range points.Videos {
|
||||
nodeInfo := NodeInfo{
|
||||
ChapterID: chapterIDStr,
|
||||
ChapterName: chapter.Name,
|
||||
CardID: video.JobID,
|
||||
CardTitle: video.Title,
|
||||
CardType: "video",
|
||||
}
|
||||
allNodes = append(allNodes, nodeInfo)
|
||||
if video.IsPassed {
|
||||
completedNodes = append(completedNodes, chapterIDStr+":"+video.JobID)
|
||||
}
|
||||
}
|
||||
// 统计文档任务点
|
||||
for _, doc := range points.Documents {
|
||||
nodeInfo := NodeInfo{
|
||||
ChapterID: chapterIDStr,
|
||||
ChapterName: chapter.Name,
|
||||
CardID: doc.JobID,
|
||||
CardTitle: doc.Title,
|
||||
CardType: "document",
|
||||
}
|
||||
allNodes = append(allNodes, nodeInfo)
|
||||
}
|
||||
// 统计作业任务点
|
||||
for _, work := range points.Works {
|
||||
nodeInfo := NodeInfo{
|
||||
ChapterID: chapterIDStr,
|
||||
ChapterName: chapter.Name,
|
||||
CardID: work.JobID,
|
||||
CardTitle: work.Title,
|
||||
CardType: "work",
|
||||
}
|
||||
allNodes = append(allNodes, nodeInfo)
|
||||
if work.IsPassed {
|
||||
completedNodes = append(completedNodes, chapterIDStr+":"+work.JobID)
|
||||
}
|
||||
}
|
||||
// 统计外链任务点
|
||||
for _, link := range points.Hyperlinks {
|
||||
nodeInfo := NodeInfo{
|
||||
ChapterID: chapterIDStr,
|
||||
ChapterName: chapter.Name,
|
||||
CardID: link.JobID,
|
||||
CardTitle: link.Title,
|
||||
CardType: "hyperlink",
|
||||
}
|
||||
allNodes = append(allNodes, nodeInfo)
|
||||
}
|
||||
// 统计直播任务点
|
||||
for _, live := range points.Lives {
|
||||
nodeInfo := NodeInfo{
|
||||
ChapterID: chapterIDStr,
|
||||
ChapterName: chapter.Name,
|
||||
CardID: live.JobID,
|
||||
CardTitle: live.Title,
|
||||
CardType: "live",
|
||||
}
|
||||
allNodes = append(allNodes, nodeInfo)
|
||||
}
|
||||
_ = cards // cards 暂时不使用
|
||||
}
|
||||
}
|
||||
|
||||
// 递归处理子章节
|
||||
if len(chapter.Knowledge) > 0 {
|
||||
collectNodes(chapter.Knowledge)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
collectNodes(chapters)
|
||||
|
||||
// 将节点信息序列化为JSON
|
||||
nodesJSON, _ := sonic.MarshalString(allNodes)
|
||||
completedNodesJSON, _ := sonic.MarshalString(completedNodes)
|
||||
|
||||
// 添加课程时不获取任务点统计,由定时任务处理
|
||||
db2.Global.CourseEntity.Create().
|
||||
SetUserID(user.ID).
|
||||
SetUsername(req.Username).
|
||||
@@ -205,10 +102,8 @@ func (s CourseServiceV1) AddCourse(ctx context.Context, req *v1.AddCourseReq) *u
|
||||
SetViolence(req.Violence).
|
||||
SetNillableDesc(&req.Desc).
|
||||
SetStatus(courseentity.StatusNotStart).
|
||||
SetTaskCount(len(allNodes)).
|
||||
SetSuccessCount(len(completedNodes)).
|
||||
SetNodes(nodesJSON).
|
||||
SetCompletedNodes(completedNodesJSON).
|
||||
SetTaskCount(0).
|
||||
SetSuccessCount(0).
|
||||
SaveX(ctx)
|
||||
|
||||
return utils.SuccessWithMsg("添加成功")
|
||||
|
||||
@@ -167,13 +167,10 @@ func (v CpLeaveServiceV1) Report(ctx context.Context, req *v1.CpLeaveReportReq)
|
||||
detail := reportApp.LeaveDetail(req.LeaveId)
|
||||
|
||||
// 填充表单
|
||||
form := reportApp.FillReportForm(detail)
|
||||
|
||||
// 获取位置信息
|
||||
lon, lat := reportApp.GetLocation(detail)
|
||||
form := reportApp.FillReportForm(detail, req)
|
||||
|
||||
// 提交销假
|
||||
reportApp.SubmitReport(ctx, form, lon, lat, cpUser.Username, cpUser.MobileCode)
|
||||
reportApp.SubmitReport(ctx, form, req.Longitude, req.Latitude, cpUser.Username, cpUser.MobileCode)
|
||||
|
||||
// 如果执行成功,更新记录状态
|
||||
db2.Global.CpLeave.UpdateOne(leaveRecord).
|
||||
@@ -184,6 +181,30 @@ func (v CpLeaveServiceV1) Report(ctx context.Context, req *v1.CpLeaveReportReq)
|
||||
return utils.SuccessWithMsg("销假成功")
|
||||
}
|
||||
|
||||
// Upload 上传图片并返回预览地址
|
||||
func (v CpLeaveServiceV1) Upload(ctx context.Context, req *v1.CpLeaveUploadReq) *utils.Response[string] {
|
||||
user := utils.GetUserInfoFromCtx(ctx)
|
||||
// 检测是否属于自己的cpuser
|
||||
cpUser := db2.Global.CpUser.Query().Where(cpuser.ID(req.CpUserId), cpuser.HasSysuserWith(sysuser.ID(user.ID))).WithSysuser().WithSchool().OnlyX(ctx)
|
||||
if cpUser.Edges.Sysuser == nil {
|
||||
utils.OkOrPanic(errors2.NewBusinessError(400, "非法的今日校园账号"))
|
||||
}
|
||||
schoolDetail := school.GetSchoolDetail(ctx, cpUser.SchoolID)
|
||||
client := login.GetClient(ctx, cpUser.Cookie)
|
||||
if !login.CookieEnabled(ctx, schoolDetail.WecloudUrl, client, cpUser.LoginType) {
|
||||
loginExecutor := login.GetCpdailyLoginBySchoolInfo(ctx, &schoolDetail)
|
||||
loginExecutor.Login(ctx, &schoolDetail, cpUser.Username, cpUser.Password)
|
||||
cookie := loginExecutor.GetCookieString()
|
||||
db2.Global.CpUser.UpdateOne(cpUser).SetCookie(cookie).ExecX(ctx)
|
||||
client = login.GetClient(ctx, cookie)
|
||||
}
|
||||
// 创建销假服务
|
||||
reportApp := leave.NewCpdailyReportApp(client, schoolDetail.WecloudUrl)
|
||||
|
||||
imageUrl := reportApp.UploadImage(ctx, req.File)
|
||||
return utils.SuccessWithData(imageUrl)
|
||||
}
|
||||
|
||||
func NewCpLeaveServiceV1() *CpLeaveServiceV1 {
|
||||
return &CpLeaveServiceV1{}
|
||||
}
|
||||
|
||||
@@ -265,7 +265,7 @@ func (v CpTaskServiceV1) ExecuteNow(ctx context.Context, req *v1.ExecuteNowReq)
|
||||
queue.AddTask(ctx, asynq.NewTask(cst2.TaskCpdaily, payloadWriter.Bytes()),
|
||||
asynq.Unique(2*time.Minute),
|
||||
asynq.MaxRetry(0),
|
||||
asynq.Timeout(10*time.Minute),
|
||||
asynq.Timeout(5*time.Minute),
|
||||
asynq.Deadline(time.Now().Add(10*time.Minute)),
|
||||
asynq.Queue(cst2.TaskQueueCpdaily),
|
||||
)
|
||||
|
||||
@@ -143,8 +143,8 @@ func (s *EmailServiceV1) sendEmail(ctx context.Context, to, subject, body string
|
||||
utils.OkOrPanic(e, oops.WithContext(ctx).Wrap)
|
||||
|
||||
task := queue.AddTask(ctx, asynq.NewTask(cst2.TaskEmail, payload.Bytes()), asynq.Queue(cst2.TaskQueueEmail),
|
||||
asynq.MaxRetry(3),
|
||||
asynq.Timeout(10*time.Minute),
|
||||
asynq.MaxRetry(1),
|
||||
asynq.Timeout(5*time.Minute),
|
||||
)
|
||||
logger.Logger.Info("添加任务: ", zap.String("task_id", task.ID), zap.String("邮箱", to))
|
||||
return nil
|
||||
|
||||
@@ -4,10 +4,11 @@ import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"likedream-goframe/internal/api/v1"
|
||||
v1 "likedream-goframe/internal/api/v1"
|
||||
cst2 "likedream-goframe/internal/common/cst"
|
||||
"likedream-goframe/internal/common/db"
|
||||
"likedream-goframe/internal/ent"
|
||||
"likedream-goframe/internal/ent/sysconfig"
|
||||
"likedream-goframe/internal/ent/sysrole"
|
||||
"likedream-goframe/internal/ent/sysuser"
|
||||
"likedream-goframe/internal/framework/redis"
|
||||
@@ -47,6 +48,12 @@ func (s *UserLoginServiceV1) Login(ctx context.Context, req *v1.UserLoginReq) *u
|
||||
}
|
||||
|
||||
func (s *UserLoginServiceV1) Register(ctx context.Context, req *v1.UserRegisterReq) *utils.Response[any] {
|
||||
// 检查是否允许注册
|
||||
allowRegister := s.IsRegistrationAllowed(ctx)
|
||||
if !allowRegister {
|
||||
return utils.FailParam("系统当前不允许注册")
|
||||
}
|
||||
|
||||
//邀请码查询
|
||||
var parent *ent.SysUser
|
||||
if req.InviteCode != "" {
|
||||
@@ -255,3 +262,18 @@ func (s *UserLoginServiceV1) GetResetPasswordInfo(ctx context.Context, req *v1.R
|
||||
Email: user.Email,
|
||||
})
|
||||
}
|
||||
|
||||
// IsRegistrationAllowed 检查是否允许注册
|
||||
func (s *UserLoginServiceV1) IsRegistrationAllowed(ctx context.Context) bool {
|
||||
config, err := db.Global.SysConfig.Query().
|
||||
Where(sysconfig.KeyEQ(cst2.ConfigSystemAllowRegister)).
|
||||
Only(ctx)
|
||||
|
||||
// 如果配置不存在或查询出错,默认允许注册
|
||||
if err != nil {
|
||||
return true
|
||||
}
|
||||
|
||||
// 检查配置值,"true" 或 "1" 表示允许注册
|
||||
return config.Value == "true" || config.Value == "1"
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user