Compare commits

..

5 Commits

Author SHA1 Message Date
sugarBecomer 98eb15f4e4 ✨ 手机号登录 2025-12-06 02:16:20 +08:00
sugarBecomer 3a2e679b85 ✨ 学习通 & 销假 2025-12-05 22:09:47 +08:00
sugarBecomer 921192a914 ✅ 查寝获取近期任务信息 2025-12-05 10:08:43 +08:00
sugarBecomer 107b472cf7 🐛 限制注册 2025-12-04 22:53:47 +08:00
sugarBecomer 14108f6ba3 🥚 关闭注册 2025-12-03 23:09:30 +08:00
38 changed files with 2441 additions and 1419 deletions
+3 -1
View File
@@ -51,6 +51,8 @@ sliderIds = ["1018764144934965", "sdhyxy", "hqdx"]
[basePoint]
cpdaily = "0.5"
cpdailyTask = "0.5"
cpdailyLeave = "4"
cpdailyPhone = "0.25"
[task]
concurrency = 20
+1
View File
@@ -59,6 +59,7 @@ func StartServer(ctx context.Context) {
cpdailyGroup.Bind(cpdaily.NewCpTaskCtrlV1())
cpdailyGroup.Bind(cpdaily.NewCpImageCtrlV1())
cpdailyGroup.Bind(cpdaily.NewCpTaskLogCtrlV1())
cpdailyGroup.Bind(cpdaily.NewCpLeaveCtrlV1())
// 娱乐
musicGroup := group.Group("/music").Middleware(middleware.AuthHandler, middleware.PermissionHandler)
musicGroup.Bind(music.NewMusicCtrlV1())
+3
View File
@@ -30,10 +30,13 @@ type LoginGetCode struct {
type AddByCode struct {
g.Meta `path:"/user/addByCode" method:"post" tags:"CpUser" summary:"手机号登录"`
Id int64 `json:"id"`
CaptchaKey string `json:"captchaKey" v:"required#验证码不能不能为空"`
Dots []captcha.ConfirmData `json:"dots" v:"required#验证码不能为空"`
Mobile string `json:"mobile" v:"required#手机号不能为空"`
SchoolId string `json:"school_id"`
Code string `json:"code"`
Email string `json:"email" v:"email|regex:^.*@qq\\.com$#邮箱格式不正确|必须是QQ邮箱"`
}
type CpUserConfirmAddReq struct {
+7 -2
View File
@@ -62,12 +62,17 @@ func (c *CpdailyReportApp) GetLeaveList() []leavetype.LeaveListOne {
var listList []leavetype.LeaveListOne
for _, row := range rows.Array() {
// 已完成
if row.Get("status").String() == "4" {
continue
}
leaveOne := leavetype.LeaveListOne{
Id: row.Get("id").String(),
LeaveType: row.Get("leaveType").String(),
CreateTime: row.Get("createTime").String(),
Reason: row.Get("reason").String(),
AceEndTime: row.Get("aceEndTime").String(),
Reason: row.Get("leaveReason").String(),
AceEndTime: row.Get("actEndTime").String(),
Status: row.Get("status").String(),
}
listList = append(listList, leaveOne)
}
+7 -2
View File
@@ -6,6 +6,7 @@ import (
"likedream-goframe/internal/application/cookiejar"
"likedream-goframe/internal/application/httpclient"
"likedream-goframe/internal/common/errors"
"likedream-goframe/internal/ent/cpuser"
"likedream-goframe/internal/utils"
"strings"
@@ -86,7 +87,7 @@ func ActivateSession(ctx context.Context, host string, client *resty.Client) {
client.SetRedirectPolicy(resty.NoRedirectPolicy())
}
func CookieEnabled(ctx context.Context, host string, client *resty.Client) bool {
func CookieEnabled(ctx context.Context, host string, client *resty.Client, loginType cpuser.LoginType) bool {
client.SetRedirectPolicy(resty.NoRedirectPolicy())
host = strings.TrimSuffix(host, "/")
sessionResponse, err := client.R().
@@ -95,7 +96,11 @@ func CookieEnabled(ctx context.Context, host string, client *resty.Client) bool
Post(fmt.Sprintf("%s/wec-counselor-attendance-apps/student/attendance/getStuAttendacesInOneDay", host))
utils.OkOrPanic(err)
return sessionResponse.StatusCode() != 302
needLogin := sessionResponse.StatusCode() == 302
if needLogin && loginType == cpuser.LoginTypePhone {
utils.OkOrPanic(errors.NewBusinessError(500, "登录信息失效,请重新通过短信验证码登录"))
}
return !needLogin
}
func GetClient(ctx context.Context, cookie string) *resty.Client {
+14 -9
View File
@@ -75,15 +75,15 @@ func NewSmsWithoutDeviceID() *SmsLoginHandler {
type SmsLoginHandler struct {
deviceID string
client *resty.Client
}
func (s *SmsLoginHandler) SendSms(ctx context.Context, phone string) *CpdailySmsSendSmsData {
jar := cookiejar.NewPersistCookieJar()
phoneEncrypted := base64.StdEncoding.EncodeToString(cryptoutil.AesEncrypt([]byte(phone)))
req := httpclient.
NewCpdailyClient().
s.client = httpclient.NewCpdailyClient()
req := s.client.
SetCookieJar(jar).
R().
SetContext(utils.NewCpdailySmsContextBuilder().
@@ -126,8 +126,9 @@ func (s *SmsLoginHandler) LoginByCode(ctx context.Context, phone, code string, j
"a": encodedPayload,
"b": cryptoutil.EncryptVersion,
}
req := httpclient.NewCpdailyClient().SetCookieJar(jar).R().
s.client = httpclient.NewCpdailyClient()
s.client.SetCookieJar(jar)
req := s.client.R().
SetBody(payload).
SetContext(utils.NewCpdailySmsContextBuilder().
WithDeviceID(s.deviceID).
@@ -198,10 +199,8 @@ func (s *SmsLoginHandler) SetLoginCookie(ctx context.Context, jar http.CookieJar
jar.SetCookies(targetSchoolUrl, []*http.Cookie{cookie})
jar.SetCookies(targetApiUrl, []*http.Cookie{cookie})
}
req := httpclient.NewCpdailyClient().
SetRedirectPolicy(resty.FlexibleRedirectPolicy(50)).
SetCookieJar(jar).R().
s.client.SetRedirectPolicy(resty.FlexibleRedirectPolicy(50))
req := s.client.R().
SetHeader("AmpCookies", ampToken).
SetContext(ctx)
@@ -273,3 +272,9 @@ func setSmsRequestHeaders(ctx context.Context, request *resty.Request) {
"CpdailyInfo": encodedCpdailyInfo,
})
}
func (s *SmsLoginHandler) GetCookieString() string {
cookieJar := s.client.CookieJar()
serializableJar := cookieJar.(*cookiejar.PersistCookieJar)
return serializableJar.Serialize()
}
@@ -6,4 +6,5 @@ type LeaveListOne struct {
CreateTime string `json:"createTime"`
AceEndTime string `json:"aceEndTime"`
Reason string `json:"reason"`
Status string `json:"status"`
}
@@ -693,3 +693,18 @@ func (c *CpdailySleepCheckTask) Submit(ctx context.Context, form map[string]*gva
utils.OkOrPanic(errors.NewBusinessError(503, responseJSON.Get("message").String()), oops.WithContext(ctx).Wrap)
}
}
func (c *CpdailySleepCheckTask) GetYearAndMonth(ctx context.Context) (string, string) {
// Get current time in Shanghai timezone
timeNow := time.Now().In(cst.TimeZoneShangHai)
// Check if current day is within first 2 days of the month
if timeNow.Day() <= 2 {
// Return previous month
prevTime := timeNow.AddDate(0, -1, 0)
return strconv.Itoa(prevTime.Year()), strconv.Itoa(int(prevTime.Month()))
} else {
// Return current month
return strconv.Itoa(timeNow.Year()), strconv.Itoa(int(timeNow.Month()))
}
}
@@ -1,135 +0,0 @@
package task
import (
"context"
"likedream-goframe/internal/testutil"
"testing"
"github.com/joomcode/errorx"
)
func TestCpdailySleepCheckTask_QueryFormByTitle(t *testing.T) {
loginClient, schoolDetail := testutil.LoginTestUser()
task := NewSleepCheckTask(loginClient, schoolDetail.WecloudUrl)
tasks := task.QueryFormByTitle(context.Background(), "查寝")
if len(tasks) == 0 {
t.Error("未查询到查寝任务")
} else {
t.Logf("查询到查寝任务: %v", tasks)
}
}
func TestCpdailySleepCheckTask_GetRecentTaskTitle(t *testing.T) {
loginClient, schoolDetail := testutil.LoginTestUser()
task := NewSleepCheckTask(loginClient, schoolDetail.WecloudUrl)
titles := task.GetRecentTaskTitle(context.Background())
if len(titles) == 0 {
t.Error("未查询到查寝任务标题")
} else {
t.Logf("查询到查寝任务标题: %v", titles)
}
}
func TestCpdailySleepCheckTask_QueryFormByYearMonth(t *testing.T) {
loginClient, schoolDetail := testutil.LoginTestUser()
task := NewSleepCheckTask(loginClient, schoolDetail.WecloudUrl)
tests := []struct {
name string
titleGlob string
year string
month string
wantErr bool
}{
{
name: "查询当前月份查寝任务",
titleGlob: "查寝",
year: "2025",
month: "6",
wantErr: false,
},
{
name: "查询单数字月份查寝任务",
titleGlob: "查寝",
year: "2025",
month: "6", // 将会被格式化为 "06"
wantErr: false,
},
{
name: "使用通配符模式匹配",
titleGlob: "*查寝*",
year: "2025",
month: "6",
wantErr: false,
},
{
name: "查询不存在的任务",
titleGlob: "不存在的任务",
year: "2025",
month: "6",
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
defer func() {
if r := recover(); r != nil {
oopsError, _ := errorx.ErrorFromPanic(r)
if !tt.wantErr {
t.Errorf("QueryFormByYearMonth() 意外的panic: %+v", oopsError)
} else {
t.Logf("预期的错误: %+v", oopsError)
}
}
}()
form := task.QueryFormByYearMonth(context.Background(), tt.titleGlob, tt.year, tt.month)
if tt.wantErr {
t.Error("预期应该出现错误,但没有出现")
return
}
if form == nil {
t.Error("未查询到查寝任务表单")
return
}
// 验证返回结果的结构
if realTitle := form["realTitle"].String(); realTitle == "" {
t.Error("返回结果中缺少 realTitle 或 realTitle 为空")
} else {
t.Logf("任务真实标题: %s", realTitle)
}
if taskInfo := form["taskInfo"].Map(); taskInfo == nil {
t.Error("返回结果中缺少 taskInfo 或 taskInfo 为空")
} else {
t.Logf("任务信息包含字段: %d", len(taskInfo))
// 验证关键字段是否存在
requiredFields := []string{"taskName", "signWid", "signInstanceWid"}
for _, field := range requiredFields {
if _, exists := taskInfo[field]; !exists {
t.Errorf("taskInfo 中缺少必要字段: %s", field)
}
}
}
if rows := form["rows"].Map(); rows == nil {
t.Error("返回结果中缺少 rows 或 rows 为空")
} else {
t.Logf("表单数据包含字段: %d", len(rows))
}
t.Logf("查询到查寝任务表单,标题: %v", form["realTitle"])
})
}
}
@@ -0,0 +1,19 @@
package task
import (
"context"
"likedream-goframe/internal/testutil"
"testing"
"github.com/bytedance/sonic"
)
func TestGetHistoryForm(t *testing.T) {
ctx := context.Background()
loginClient, schoolDetail := testutil.LoginTestUser()
task := NewSleepCheckTask(loginClient, schoolDetail.WecloudUrl)
y, m := task.GetYearAndMonth(ctx)
month := task.QueryFormByYearMonth(ctx, "晚查寝", y, m)
marshal, _ := sonic.Marshal(month)
t.Log(string(marshal))
}
@@ -62,44 +62,33 @@ type XueXiTCourse struct {
CourseID string `json:"courseId"` // 课程ID
ChatID string `json:"chatId"`
CourseTeacher string `json:"courseTeacher"` // 课程老师
CourseName string `json:"courseName"` //课程名
CourseName string `json:"courseName"` // 课程名
CourseImage string `json:"courseImage"`
// 两个标识 暂时不知道有什么用
CourseDataID int `json:"courseDataId"`
ContentID int `json:"ContentID"`
IsStart bool `json:"isstart"` //是否开课了,开课了为true,没开课为false。一般来说开课才能刷,不然刷不了的
State int `json:"state"` //课程状态,0为正常,1为课程已经结束
IsStart bool `json:"isstart"` // 是否开课了,开课了为true,没开课为false
State int `json:"state"` // 课程状态,0为正常,1为课程已经结束
}
// XueXiTCourseChapter 课程章节信息
type XueXiTCourseChapter struct {
ID string `json:"id"` // 章节ID
ID int `json:"id"` // 章节ID
Name string `json:"name"` // 章节名称
ParentNodeID string `json:"parentnodeid"` // 父节点ID
ParentNodeID int `json:"parentnodeid"` // 父节点ID
Layer int `json:"layer"` // 层级
Label string `json:"label"` // 标签
IndexOrder int `json:"indexOrder"` // 排序索引
JobCount int `json:"jobcount"` // 任务点数量
Status int `json:"status"` // 状态
Status string `json:"status"` // 状态
IsReview int `json:"isReview"` // 是否复习
BeginTime int64 `json:"begintime"` // 开始时间
EndTime int64 `json:"endtime"` // 结束时间
Attachment []XueXiTAttachment `json:"attachment"` // 附件列表
PointTotal int `json:"pointTotal"` // 总任务点
PointFinish int `json:"pointFinish"` // 已完成任务点
Knowledge []XueXiTCourseChapter `json:"knowledge"` // 子章节列表
}
// XueXiTAttachment 附件信息
type XueXiTAttachment struct {
ID string `json:"id"` // 附件ID
Type string `json:"type"` // 附件类型(video/document等)
ObjectID string `json:"objectid"` // 对象ID
Extension string `json:"extension"` // 扩展信息
JobID string `json:"jobid"` // 任务ID
Property string `json:"property"` // 属性
Name string `json:"name"` // 附件名称
IsPassed bool `json:"isPassed"` // 是否已完成
}
// ChapterData 章节数据响应
type ChapterData struct {
Data []struct {
@@ -133,20 +122,7 @@ type ChapterData struct {
Belongschoolid string `json:"belongschoolid"`
Objectid string `json:"objectid"`
Knowledge struct {
Data []struct {
Jobcount int `json:"jobcount"`
Isreview int `json:"isreview"`
Attachment struct {
Data []interface{} `json:"data"`
} `json:"attachment"`
Indexorder int `json:"indexorder"`
Name string `json:"name"`
ID int `json:"id"`
Label string `json:"label"`
Layer int `json:"layer"`
Parentnodeid int `json:"parentnodeid"`
Status string `json:"status"`
} `json:"data"`
Data []KnowledgeData `json:"data"`
} `json:"knowledge"`
} `json:"data"`
} `json:"course"`
@@ -157,152 +133,15 @@ type ChapterData struct {
} `json:"data"`
}
// Card 任务点卡片信息
type Card struct {
ID string `json:"id"` // 卡片ID
Title string `json:"title"` // 标题
Description string `json:"description"` // 描述
KnowledgeID string `json:"knowledgeid"` // 知识点ID
Type string `json:"type"` // 类型(video/document/work等)
IsPassed bool `json:"isPassed"` // 是否完成
ObjectID string `json:"objectid"` // 对象ID
JobID string `json:"jobid"` // 任务ID
ResourceID string `json:"resourceid"` // 资源ID
Attachment *IframeAttributes `json:"attachment,omitempty"` // iframe属性
}
// IframeAttributes iframe属性
type IframeAttributes struct {
Src string `json:"src"` // iframe地址
Module string `json:"module"` // 模块名
ModToken string `json:"modtoken"` // 模块token
Width string `json:"width"` // 宽度
Height string `json:"height"` // 高度
Scrolling string `json:"scrolling"` // 滚动
ClassID string `json:"classid"` // 课程ID
ObjectID string `json:"objectid"` // 对象ID
Enc string `json:"enc"` // 加密参数
UtEnc string `json:"utenc"` // ut加密参数
OtherInfo string `json:"otherinfo"` // 其他信息
JobID string `json:"jobid"` // 任务ID
KnowledgeID string `json:"knowledgeid"` // 知识点ID
CourseFaceCheck int `json:"coursefacecheck"` // 人脸识别
}
// DataItem 任务点数据项
type DataItem struct {
ID string `json:"id"`
IndexOrder int `json:"indexorder"`
KnowledgeID string `json:"knowledgeid"`
Attachment struct {
ObjectID string `json:"objectid"`
Property struct {
Name string `json:"name"`
IsPassed bool `json:"ispassed"`
JobID string `json:"jobid"`
} `json:"property"`
Type string `json:"type"`
} `json:"attachment"`
PointList []interface{} `json:"pointList"`
JobCount int `json:"jobcount"`
Duration int64 `json:"duration"`
ClazzID string `json:"clazzid"`
CourseID string `json:"courseid"`
Module string `json:"module"`
}
// VideoDto 视频信息
type VideoDto struct {
VideoPath string `json:"videoPath"` // 视频路径
ObjectID string `json:"objectid"` // 对象ID
OtherInfo string `json:"otherInfo"` // 其他信息
JobID string `json:"jobid"` // 任务ID
Duration int `json:"duration"` // 时长(秒)
DToken string `json:"dtoken"` // dtoken
IsAudio bool `json:"isAudio"` // 是否是音频
IsPassed bool `json:"isPassed"` // 是否已完成
}
// DocumentDto 文档信息
type DocumentDto struct {
ObjectID string `json:"objectid"` // 对象ID
JobID string `json:"jobid"` // 任务ID
OtherInfo string `json:"otherInfo"` // 其他信息
JToken string `json:"jtoken"` // jtoken
PageCount int `json:"pageCount"` // 页数
IsPassed bool `json:"isPassed"` // 是否已完成
}
// FaceQRCodeResponse 人脸识别二维码响应
type FaceQRCodeResponse struct {
Status bool `json:"status"`
Msg string `json:"msg"`
QR string `json:"qr"` // 二维码base64数据
Enc string `json:"enc"` // 加密参数
}
// FaceTokenResponse 人脸识别上传令牌响应
type FaceTokenResponse struct {
Result int `json:"result"`
UploadToken string `json:"uploadtoken"`
}
// FaceUploadResponse 人脸识别上传响应
type FaceUploadResponse struct {
Result bool `json:"result"`
Msg string `json:"msg"`
Data struct {
FileID string `json:"fileId"`
} `json:"data"`
}
// FaceVerifyResponse 人脸识别验证响应
type FaceVerifyResponse struct {
Status bool `json:"status"`
Msg string `json:"msg"`
}
// WorkDto 作业信息
type WorkDto struct {
WorkID string `json:"workid"` // 作业ID
CourseID string `json:"courseid"` // 课程ID
ClassID string `json:"classid"` // 班级ID
KnowledgeID string `json:"knowledgeid"` // 知识点ID
JobID string `json:"jobid"` // 任务ID
Enc string `json:"enc"` // 加密参数
UTEnc string `json:"utenc"` // UT加密参数
Title string `json:"title"` // 作业标题
IsPassed bool `json:"isPassed"` // 是否已完成
Questions []WorkQuestion `json:"questions"` // 题目列表
}
// WorkQuestion 作业题目
type WorkQuestion struct {
QuestionID string `json:"questionId"` // 题目ID
Type int `json:"type"` // 题目类型: 0单选 1多选 2判断 3填空 4简答
Title string `json:"title"` // 题目标题
Description string `json:"description"` // 题目描述
Options []string `json:"options"` // 选项列表(单选/多选/判断)
Answer string `json:"answer"` // 答案
Score float64 `json:"score"` // 分值
}
// WorkSubmitRequest 作业提交请求
type WorkSubmitRequest struct {
WorkID string `json:"workid"`
TotalScore string `json:"totalScore"`
AnswerList []WorkAnswerItem `json:"answerlist"`
UserId string `json:"userId"`
ClassId string `json:"classId"`
CourseId string `json:"courseId"`
KnowledgeId string `json:"knowledgeid"`
JobId string `json:"jobid"`
Enc string `json:"enc"`
UTEnc string `json:"utenc"`
}
// WorkAnswerItem 作业答案项
type WorkAnswerItem struct {
QuestionID string `json:"questionId"`
Answer string `json:"answer"`
// KnowledgeData 章节知识点数据
type KnowledgeData struct {
Jobcount int `json:"jobcount"`
Isreview int `json:"isreview"`
Indexorder int `json:"indexorder"`
Name string `json:"name"`
ID int `json:"id"`
Label string `json:"label"`
Layer int `json:"layer"`
Parentnodeid int `json:"parentnodeid"`
Status string `json:"status"`
}
@@ -0,0 +1,223 @@
package entity
// PointType 任务点类型
type PointType string
const (
PointTypeVideo PointType = "insertvideo"
PointTypeDocument PointType = "insertdoc"
PointTypeDocument2 PointType = "document"
PointTypeBook PointType = "insertbook"
PointTypeWork PointType = "insertwork"
PointTypeHyperlink PointType = "insertlink"
PointTypeLive PointType = "insertlive"
)
// PointVideoDto 视频任务点
type PointVideoDto struct {
CardIndex int
CourseID string
ClassID string
KnowledgeID int
Cpi string
ObjectID string
// 从SSR视图中获取
IsPassed bool
FID int
DToken string
PlayTime int
Duration int
JobID string
OtherInfo string
Title string
RT float64
VideoFaceCaptureEnc string
RandomCaptureTime string
AttDurationEnc string
Enc string
Mid string
}
// PointDocumentDto 文档查看任务点
type PointDocumentDto struct {
CardIndex int
CourseID string
ClassID string
KnowledgeID int
Cpi string
ObjectID string
Title string
JobID string
Jtoken string
IsJob bool // 是否是任务点
Type string // document / insertbook
}
// PointWorkDto 测验/作业任务点
type PointWorkDto struct {
CardIndex int
CourseID string
ClassID string
KnowledgeID int
Cpi string
WorkID string
SchoolID string
JobID string
PUID string
KToken string
Enc string
Title string
IsPassed bool
}
// PointHyperlinkDto 外链任务点
type PointHyperlinkDto struct {
CardIndex int
CourseID string
ClassID string
KnowledgeID int
Cpi string
ObjectID string
Title string
JobID string
Jtoken string
LinkType int // 外链类型
IsJob bool // 是否是任务点
}
// PointLiveDto 直播任务点
type PointLiveDto struct {
CardIndex int
CourseID string
ClassID string
KnowledgeID int
Cpi string
UserId string // 用户ID
Live bool
LiveId string // 直播ID
Vdoid string
Mid string
Title string // 直播标题
JobID string
StreamName string // 直播流名称
LiveStatusStr string // 直播状态文字
LiveStatusCode int // 直播状态码 0=未开始
VideoDuration int // 视频时长
Aid string
Module string // 类型
IsJob bool // 是否为任务点
AuthEnc string
LiveDragEnc string
LiveSetEnc string
OtherInfo string
Enc string
LiveSwDsEnc string
VideoCompletePercent float64 // 观看进度
}
// Card 任务点卡片信息
type Card struct {
ID int `json:"id"`
Title string `json:"title"`
Description string `json:"description"`
CardOrder int `json:"cardorder"`
KnowledgeID int `json:"knowledgeid"`
}
// CardAPIResponse 卡片API响应
type CardAPIResponse struct {
Data []CardDataItem `json:"data"`
}
// CardDataItem 卡片数据项
type CardDataItem struct {
ClickCount int `json:"clickcount"`
Createtime int64 `json:"createtime"`
OpenLock int `json:"openlock"`
IndexOrder int `json:"indexorder"`
Name string `json:"name"`
LastModifyTime int64 `json:"lastmodifytime"`
ID int `json:"id"`
Label string `json:"label"`
Layer int `json:"layer"`
Card struct {
Data []Card `json:"data"`
} `json:"card"`
ParentNodeID int `json:"parentnodeid"`
Status string `json:"status"`
}
// IframeAttributes iframe 的属性
type IframeAttributes struct {
Data map[string]interface{} `json:"data"`
Other map[string]string
HasData bool
}
// ChapterPointStatus 章节任务点状态
type ChapterPointStatus map[string]struct {
ClickCount int `json:"clickcount"`
FinishCount int `json:"finishcount"`
TotalCount int `json:"totalcount"`
OpenLock int `json:"openlock"`
UnFinishCount int `json:"unfinishcount"`
}
// AttachmentSetting 附件设置(从页面JS中解析)
type AttachmentSetting struct {
Attachments []map[string]interface{} `json:"attachments"`
Defaults map[string]interface{} `json:"defaults"`
}
// ChapterPoints 章节所有任务点集合
type ChapterPoints struct {
Videos []PointVideoDto
Documents []PointDocumentDto
Works []PointWorkDto
Hyperlinks []PointHyperlinkDto
Lives []PointLiveDto
}
// QuestionType 题目类型
type QuestionType int
const (
QuestionTypeSingleChoice QuestionType = 0 // 单选题
QuestionTypeMultipleChoice QuestionType = 1 // 多选题
QuestionTypeFillBlank QuestionType = 2 // 填空题
QuestionTypeTrueFalse QuestionType = 3 // 判断题
QuestionTypeShortAnswer QuestionType = 4 // 简答题
)
// WorkQuestion 作业题目
type WorkQuestion struct {
Qid string `json:"qid"` // 题目ID
Type QuestionType `json:"type"` // 题目类型
Text string `json:"text"` // 题目内容
Options map[string]string `json:"options"` // 选项 (A: xxx, B: xxx)
Answers []string `json:"answers"` // 答案
BlankCount int `json:"blankCount"` // 填空题空格数量
BlankAnswer map[string]string `json:"blankAnswer"` // 填空题答案 (第1空: xxx)
}
// WorkDto 作业详情
type WorkDto struct {
Title string `json:"title"` // 作业标题
Cpi string `json:"cpi"` // cpi
JobId string `json:"jobId"` // 任务ID
WorkId string `json:"workId"` // 作业ID
ClassId string `json:"classId"` // 班级ID
CourseId string `json:"courseId"` // 课程ID
KnowledgeId string `json:"knowledgeId"` // 知识点ID
UserId string `json:"userId"` // 用户ID
FullScore string `json:"fullScore"` // 满分
OldWorkId string `json:"oldWorkId"` // 原始作业ID
OldSchoolId string `json:"oldSchoolId"` // 原始学校ID
Api string `json:"api"` // API值
WorkRelationId string `json:"workRelationId"` // 作业关联ID
EncWork string `json:"encWork"` // 加密参数
WorkAnswerId string `json:"workAnswerId"` // 作业答案ID
AnswerId string `json:"answerId"` // 答案ID
TotalQuestionNum string `json:"totalQuestionNum"` // 题目总数
Questions []WorkQuestion `json:"questions"` // 题目列表
}
@@ -9,10 +9,8 @@ import (
"resty.dev/v3"
)
var randChar []string = []string{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "A", "B", "C", "D", "E", "F"}
// ApiVerifyCodeBytes 获取学习通验证码图片
func ApiVerifyCodeBytes(client *resty.Client) ([]byte, error) {
urlStr := "https://mooc1-api.chaoxing.com/processVerifyPng.ac?t=" + fmt.Sprintf("%d", time.Now().UnixMilli())
req := client.R()
@@ -32,8 +30,9 @@ func ApiVerifyCodeBytes(client *resty.Client) ([]byte, error) {
return all, nil
}
func ApiPassVerifyCode(client *resty.Client, code string, retry int) bool {
if retry < 0 {
// ApiPassVerifyCode 提交学习通验证码
func ApiPassVerifyCode(client *resty.Client, code string, retryCount int) bool {
if retryCount < 0 {
return false
}
urlStr := "https://mooc1-api.chaoxing.com/html/processVerify.ac"
@@ -47,7 +46,7 @@ func ApiPassVerifyCode(client *resty.Client, code string, retry int) bool {
req.Header.Add("Connection", "keep-alive")
res, err := req.Post(urlStr)
if err != nil {
return ApiPassVerifyCode(client, code, retry-1)
return ApiPassVerifyCode(client, code, retryCount-1)
}
client.SetRedirectPolicy(resty.FlexibleRedirectPolicy(20))
return res.StatusCode() == 302
File diff suppressed because it is too large Load Diff
+41 -124
View File
@@ -2,11 +2,27 @@ package xuexitong
import (
"context"
"likedream-goframe/internal/application/xuexitong/entity"
"likedream-goframe/internal/framework/errors"
"likedream-goframe/internal/utils"
"testing"
)
func TestSchedule(t *testing.T) {
ctx := context.Background()
xuexitongLogin := NewXuexitongLogin(ctx)
err := xuexitongLogin.Login(context.Background(), "13151832241", "yyz@083422", 5)
utils.OkOrPanic(err)
client := xuexitongLogin.GetClient()
courseService := NewXuexitongCourse(client)
// 人人必修的人工智能课
err = courseService.AutoStudyByCourseID(ctx, "258109701")
if err != nil {
utils.OkOrPanic(errors.NewBusinessErrorWithDetail(503, "刷课失败", err))
}
}
func TestXuexitongLogin(t *testing.T) {
xuexitongLogin := NewXuexitongLogin(context.Background())
err := xuexitongLogin.Login(context.Background(), "13551503012", "xiaozhi520", 5)
@@ -39,7 +55,7 @@ func TestPullChapter(t *testing.T) {
}
// 获取第一个课程的章节
chapters := courseAction.PullCourseChapterList(context.Background(), courseList[0].CourseID)
chapters := courseAction.PullCourseChapterList(context.Background(), courseList[0])
t.Logf("课程 %s 的章节数量: %d", courseList[0].CourseName, len(chapters))
for _, chapter := range chapters {
@@ -64,147 +80,48 @@ func TestFetchChapterCards(t *testing.T) {
course := courseList[0]
// 获取章节列表
chapters := courseAction.PullCourseChapterList(context.Background(), course.CourseID)
chapters := courseAction.PullCourseChapterList(context.Background(), course)
if len(chapters) == 0 {
t.Fatal("没有找到章节")
}
// 找一个有任务点的章节
var targetChapter *entity.XueXiTCourseChapter
for i := range chapters {
if chapters[i].JobCount > 0 {
targetChapter = &chapters[i]
var targetChapterID int
for _, ch := range chapters {
if ch.JobCount > 0 {
targetChapterID = ch.ID
break
}
}
if targetChapter == nil {
if targetChapterID == 0 {
t.Fatal("没有找到有任务点的章节")
}
// 获取任务点卡片
cards, err := courseAction.FetchChapterCards(context.Background(), course, targetChapter.ID, targetChapter.ID)
cards, points, err := courseAction.FetchChapterCards(context.Background(), course, targetChapterID)
utils.OkOrPanic(err)
t.Logf("章节 %s 的任务点数量: %d", targetChapter.Name, len(cards))
t.Logf("卡片数量: %d", len(cards))
if points != nil {
t.Logf("视频数量: %d, 文档数量: %d, 作业数量: %d, 外链数量: %d, 直播数量: %d",
len(points.Videos), len(points.Documents), len(points.Works),
len(points.Hyperlinks), len(points.Lives))
for _, card := range cards {
t.Logf("任务点: 类型=%s, JobID=%s, ObjectID=%s", card.Type, card.JobID, card.ObjectID)
}
}
func TestAutoPlayVideo(t *testing.T) {
xuexitongLogin := NewXuexitongLogin(context.Background())
err := xuexitongLogin.Login(context.Background(), "13551503012", "xiaozhi520", 5)
utils.OkOrPanic(err)
client := xuexitongLogin.GetClient()
courseAction := NewXuexitongCourse(client)
// 获取课程列表
courseList := courseAction.PullCourseList(context.Background())
if len(courseList) == 0 {
t.Fatal("没有找到课程")
}
course := courseList[0]
// 获取章节列表
chapters := courseAction.PullCourseChapterList(context.Background(), course.CourseID)
if len(chapters) == 0 {
t.Fatal("没有找到章节")
}
// 找一个有任务点的章节
var targetChapter *entity.XueXiTCourseChapter
for i := range chapters {
if chapters[i].JobCount > 0 {
targetChapter = &chapters[i]
break
for _, video := range points.Videos {
t.Logf("视频任务点: JobID=%s, ObjectID=%s", video.JobID, video.ObjectID)
}
}
if targetChapter == nil {
t.Fatal("没有找到有任务点的章节")
}
// 获取任务点卡片
cards, err := courseAction.FetchChapterCards(context.Background(), course, targetChapter.ID, targetChapter.ID)
utils.OkOrPanic(err)
// 找视频任务点
for _, card := range cards {
if card.Type == "video" {
t.Logf("开始处理视频任务点: %s", card.JobID)
// 获取视频信息
videoDto, err := courseAction.FetchVideoDto(context.Background(), card.ObjectID, "", card.JobID)
utils.OkOrPanic(err)
// 自动播放视频
err = courseAction.AutoPlayVideo(context.Background(), course, card, videoDto)
utils.OkOrPanic(err)
t.Logf("视频任务点完成: %s", card.JobID)
break // 只测试一个视频
for _, doc := range points.Documents {
t.Logf("文档任务点: JobID=%s, Type=%s", doc.JobID, doc.Type)
}
}
}
func TestAutoReadDocument(t *testing.T) {
xuexitongLogin := NewXuexitongLogin(context.Background())
err := xuexitongLogin.Login(context.Background(), "13551503012", "xiaozhi520", 5)
utils.OkOrPanic(err)
client := xuexitongLogin.GetClient()
courseAction := NewXuexitongCourse(client)
// 获取课程列表
courseList := courseAction.PullCourseList(context.Background())
if len(courseList) == 0 {
t.Fatal("没有找到课程")
}
course := courseList[0]
// 获取章节列表
chapters := courseAction.PullCourseChapterList(context.Background(), course.CourseID)
if len(chapters) == 0 {
t.Fatal("没有找到章节")
}
// 找一个有任务点的章节
var targetChapter *entity.XueXiTCourseChapter
for i := range chapters {
if chapters[i].JobCount > 0 {
targetChapter = &chapters[i]
break
for _, work := range points.Works {
t.Logf("作业任务点: JobID=%s, WorkID=%s", work.JobID, work.WorkID)
}
}
if targetChapter == nil {
t.Fatal("没有找到有任务点的章节")
}
// 获取任务点卡片
cards, err := courseAction.FetchChapterCards(context.Background(), course, targetChapter.ID, targetChapter.ID)
utils.OkOrPanic(err)
// 找文档任务点
for _, card := range cards {
if card.Type == "document" {
t.Logf("开始处理文档任务点: %s", card.JobID)
// 获取文档信息
documentDto, err := courseAction.FetchDocumentDto(context.Background(), card.ObjectID, "", card.JobID)
utils.OkOrPanic(err)
// 自动阅读文档
err = courseAction.AutoReadDocument(context.Background(), course, card, documentDto)
utils.OkOrPanic(err)
t.Logf("文档任务点完成: %s", card.JobID)
break // 只测试一个文档
for _, link := range points.Hyperlinks {
t.Logf("外链任务点: JobID=%s", link.JobID)
}
for _, live := range points.Lives {
t.Logf("直播任务点: JobID=%s, LiveId=%s, Title=%s", live.JobID, live.LiveId, live.Title)
}
}
}
@@ -2,9 +2,9 @@ package xuexitong
import (
"crypto/md5"
crand "crypto/rand"
"encoding/hex"
"fmt"
"math/rand"
"strings"
)
@@ -34,7 +34,7 @@ func GetUA(uaType string) string {
return strings.Join([]string{
fmt.Sprintf("Mozilla/5.0 (Linux; %s; %s Build/OPM1.171019.019; wv)", ANDROID_VERSION, DEVICE_VENDOR),
fmt.Sprintf("AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/71.0.3578.99 Mobile Safari/537.36"),
"AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/71.0.3578.99 Mobile Safari/537.36",
fmt.Sprintf("(schild:%s)", MobileUASign(DEVICE_VENDOR, "zh_CN", APP_VERSION, BUILD, IMEI)),
fmt.Sprintf("(device:%s)", DEVICE_VENDOR),
"Language/zh_CN",
@@ -48,15 +48,14 @@ func GetUA(uaType string) string {
}
}
// 用于生成IMEI
func TokenHex(len int) string {
b := make([]byte, 16)
_, err := rand.Read(b)
// TokenHex 用于生成IMEI
func TokenHex(length int) string {
b := make([]byte, length)
_, err := crand.Read(b)
if err != nil {
panic(err)
}
token := hex.EncodeToString(b)
return token
return hex.EncodeToString(b)
}
func MobileUASign(model, locale, version, build, imei string) string {
+3 -1
View File
@@ -37,7 +37,9 @@ const (
ConfigEmailFromName = "email.fromName"
// 基础积分配置
ConfigBasePointCpdaily = "basePoint.cpdaily"
ConfigBasePointCpdailyTask = "basePoint.cpdailyTask"
ConfigBasePointCpdailyLeave = "basePoint.cpdailyLeave"
ConfigBasePointCpdailyPhone = "basePoint.cpdailyPhone"
)
const (
@@ -4,8 +4,12 @@ import (
"context"
v1 "likedream-goframe/internal/api/v1"
"likedream-goframe/internal/ent"
"likedream-goframe/internal/framework/captcha"
"likedream-goframe/internal/framework/redis"
"likedream-goframe/internal/service"
"likedream-goframe/internal/utils"
"github.com/bytedance/sonic"
)
type CpUserCtrlV1 struct {
@@ -68,10 +72,32 @@ func (c CpUserCtrlV1) AuthorizeRandom(ctx context.Context, req *v1.CpUserAuthori
}
func (c CpUserCtrlV1) LoginGetCode(ctx context.Context, req *v1.LoginGetCode) (res *utils.Response[any], err error) {
defer utils.Pass(&err)
client := redis.GetClient()
dotsStr := client.GetDel(ctx, req.CaptchaKey).Val()
if dotsStr == "" {
return utils.Fail(10003, "验证码错误"), nil
}
var dots captcha.ConfirmData
err = sonic.Unmarshal([]byte(dotsStr), &dots)
utils.OkOrPanic(err)
if !captcha.VerifyCaptcha(dots, req.Dots) {
return utils.Fail(10003, "验证码错误"), nil
}
return service.Global.CpUser.LoginGetCode(ctx, req), nil
}
func (c CpUserCtrlV1) AddByCode(ctx context.Context, req *v1.AddByCode) (res *utils.Response[any], err error) {
defer utils.Pass(&err)
client := redis.GetClient()
dotsStr := client.GetDel(ctx, req.CaptchaKey).Val()
if dotsStr == "" {
return utils.Fail(10003, "验证码错误"), nil
}
var dots captcha.ConfirmData
err = sonic.Unmarshal([]byte(dotsStr), &dots)
utils.OkOrPanic(err)
if !captcha.VerifyCaptcha(dots, req.Dots) {
return utils.Fail(10003, "验证码错误"), nil
}
return service.Global.CpUser.AddByCode(ctx, req), nil
}
@@ -5,6 +5,7 @@ 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"
@@ -46,6 +47,7 @@ func (c *UserLoginV1) Login(ctx context.Context, req *v1.UserLoginReq) (res *uti
if !captcha.VerifyCaptcha(dots, req.Dots) {
return utils.Fail(10003, "验证码错误"), nil
}
return service.Global.UserLogin.Login(ctx, req), nil
}
@@ -62,6 +64,7 @@ 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
}
+12 -1
View File
@@ -39,6 +39,8 @@ type CpUser struct {
Cookie string `json:"cookie,omitempty"`
// MobileType holds the value of the "mobile_type" field.
MobileType cpuser.MobileType `json:"mobile_type,omitempty"`
// LoginType holds the value of the "login_type" field.
LoginType cpuser.LoginType `json:"login_type,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the CpUserQuery when eager-loading is set.
Edges CpUserEdges `json:"edges"`
@@ -123,7 +125,7 @@ func (*CpUser) scanValues(columns []string) ([]any, error) {
values[i] = new(ent2.CustomTime)
case cpuser.FieldID, cpuser.FieldUserID:
values[i] = new(sql.NullInt64)
case cpuser.FieldUsername, cpuser.FieldPassword, cpuser.FieldSchoolID, cpuser.FieldEmail, cpuser.FieldMobileCode, cpuser.FieldCookie, cpuser.FieldMobileType:
case cpuser.FieldUsername, cpuser.FieldPassword, cpuser.FieldSchoolID, cpuser.FieldEmail, cpuser.FieldMobileCode, cpuser.FieldCookie, cpuser.FieldMobileType, cpuser.FieldLoginType:
values[i] = new(sql.NullString)
default:
values[i] = new(sql.UnknownType)
@@ -206,6 +208,12 @@ func (_m *CpUser) assignValues(columns []string, values []any) error {
} else if value.Valid {
_m.MobileType = cpuser.MobileType(value.String)
}
case cpuser.FieldLoginType:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field login_type", values[i])
} else if value.Valid {
_m.LoginType = cpuser.LoginType(value.String)
}
default:
_m.selectValues.Set(columns[i], values[i])
}
@@ -296,6 +304,9 @@ func (_m *CpUser) String() string {
builder.WriteString(", ")
builder.WriteString("mobile_type=")
builder.WriteString(fmt.Sprintf("%v", _m.MobileType))
builder.WriteString(", ")
builder.WriteString("login_type=")
builder.WriteString(fmt.Sprintf("%v", _m.LoginType))
builder.WriteByte(')')
return builder.String()
}
+34 -2
View File
@@ -36,6 +36,8 @@ const (
FieldCookie = "cookie"
// FieldMobileType holds the string denoting the mobile_type field in the database.
FieldMobileType = "mobile_type"
// FieldLoginType holds the string denoting the login_type field in the database.
FieldLoginType = "login_type"
// EdgeCptasks holds the string denoting the cptasks edge name in mutations.
EdgeCptasks = "cptasks"
// EdgeCpLeave holds the string denoting the cp_leave edge name in mutations.
@@ -98,6 +100,7 @@ var Columns = []string{
FieldMobileCode,
FieldCookie,
FieldMobileType,
FieldLoginType,
}
// ValidColumn reports if the column name is valid (part of the table columns).
@@ -123,8 +126,6 @@ var (
DefaultUpdateTime func() *ent2.CustomTime
// UsernameValidator is a validator for the "username" field. It is called by the builders before save.
UsernameValidator func(string) error
// PasswordValidator is a validator for the "password" field. It is called by the builders before save.
PasswordValidator func(string) error
// SchoolIDValidator is a validator for the "school_id" field. It is called by the builders before save.
SchoolIDValidator func(string) error
)
@@ -152,6 +153,32 @@ func MobileTypeValidator(mt MobileType) error {
}
}
// LoginType defines the type for the "login_type" enum field.
type LoginType string
// LoginTypeAccount is the default value of the LoginType enum.
const DefaultLoginType = LoginTypeAccount
// LoginType values.
const (
LoginTypeAccount LoginType = "account"
LoginTypePhone LoginType = "phone"
)
func (lt LoginType) String() string {
return string(lt)
}
// LoginTypeValidator is a validator for the "login_type" field enum values. It is called by the builders before save.
func LoginTypeValidator(lt LoginType) error {
switch lt {
case LoginTypeAccount, LoginTypePhone:
return nil
default:
return fmt.Errorf("cpuser: invalid enum value for login_type field: %q", lt)
}
}
// OrderOption defines the ordering options for the CpUser queries.
type OrderOption func(*sql.Selector)
@@ -210,6 +237,11 @@ func ByMobileType(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldMobileType, opts...).ToFunc()
}
// ByLoginType orders the results by the login_type field.
func ByLoginType(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldLoginType, opts...).ToFunc()
}
// ByCptasksCount orders the results by cptasks count.
func ByCptasksCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
+30
View File
@@ -381,6 +381,16 @@ func PasswordHasSuffix(v string) predicate.CpUser {
return predicate.CpUser(sql.FieldHasSuffix(FieldPassword, v))
}
// PasswordIsNil applies the IsNil predicate on the "password" field.
func PasswordIsNil() predicate.CpUser {
return predicate.CpUser(sql.FieldIsNull(FieldPassword))
}
// PasswordNotNil applies the NotNil predicate on the "password" field.
func PasswordNotNil() predicate.CpUser {
return predicate.CpUser(sql.FieldNotNull(FieldPassword))
}
// PasswordEqualFold applies the EqualFold predicate on the "password" field.
func PasswordEqualFold(v string) predicate.CpUser {
return predicate.CpUser(sql.FieldEqualFold(FieldPassword, v))
@@ -701,6 +711,26 @@ func MobileTypeNotIn(vs ...MobileType) predicate.CpUser {
return predicate.CpUser(sql.FieldNotIn(FieldMobileType, vs...))
}
// LoginTypeEQ applies the EQ predicate on the "login_type" field.
func LoginTypeEQ(v LoginType) predicate.CpUser {
return predicate.CpUser(sql.FieldEQ(FieldLoginType, v))
}
// LoginTypeNEQ applies the NEQ predicate on the "login_type" field.
func LoginTypeNEQ(v LoginType) predicate.CpUser {
return predicate.CpUser(sql.FieldNEQ(FieldLoginType, v))
}
// LoginTypeIn applies the In predicate on the "login_type" field.
func LoginTypeIn(vs ...LoginType) predicate.CpUser {
return predicate.CpUser(sql.FieldIn(FieldLoginType, vs...))
}
// LoginTypeNotIn applies the NotIn predicate on the "login_type" field.
func LoginTypeNotIn(vs ...LoginType) predicate.CpUser {
return predicate.CpUser(sql.FieldNotIn(FieldLoginType, vs...))
}
// HasCptasks applies the HasEdge predicate on the "cptasks" edge.
func HasCptasks() predicate.CpUser {
return predicate.CpUser(func(s *sql.Selector) {
+98 -8
View File
@@ -57,6 +57,14 @@ func (_c *CpUserCreate) SetPassword(v string) *CpUserCreate {
return _c
}
// SetNillablePassword sets the "password" field if the given value is not nil.
func (_c *CpUserCreate) SetNillablePassword(v *string) *CpUserCreate {
if v != nil {
_c.SetPassword(*v)
}
return _c
}
// SetSchoolID sets the "school_id" field.
func (_c *CpUserCreate) SetSchoolID(v string) *CpUserCreate {
_c.mutation.SetSchoolID(v)
@@ -111,6 +119,20 @@ func (_c *CpUserCreate) SetMobileType(v cpuser.MobileType) *CpUserCreate {
return _c
}
// SetLoginType sets the "login_type" field.
func (_c *CpUserCreate) SetLoginType(v cpuser.LoginType) *CpUserCreate {
_c.mutation.SetLoginType(v)
return _c
}
// SetNillableLoginType sets the "login_type" field if the given value is not nil.
func (_c *CpUserCreate) SetNillableLoginType(v *cpuser.LoginType) *CpUserCreate {
if v != nil {
_c.SetLoginType(*v)
}
return _c
}
// AddCptaskIDs adds the "cptasks" edge to the CpTask entity by IDs.
func (_c *CpUserCreate) AddCptaskIDs(ids ...int64) *CpUserCreate {
_c.mutation.AddCptaskIDs(ids...)
@@ -223,6 +245,10 @@ func (_c *CpUserCreate) defaults() error {
v := cpuser.DefaultUpdateTime()
_c.mutation.SetUpdateTime(v)
}
if _, ok := _c.mutation.LoginType(); !ok {
v := cpuser.DefaultLoginType
_c.mutation.SetLoginType(v)
}
return nil
}
@@ -245,14 +271,6 @@ func (_c *CpUserCreate) check() error {
return &ValidationError{Name: "username", err: fmt.Errorf(`ent: validator failed for field "CpUser.username": %w`, err)}
}
}
if _, ok := _c.mutation.Password(); !ok {
return &ValidationError{Name: "password", err: errors.New(`ent: missing required field "CpUser.password"`)}
}
if v, ok := _c.mutation.Password(); ok {
if err := cpuser.PasswordValidator(v); err != nil {
return &ValidationError{Name: "password", err: fmt.Errorf(`ent: validator failed for field "CpUser.password": %w`, err)}
}
}
if _, ok := _c.mutation.SchoolID(); !ok {
return &ValidationError{Name: "school_id", err: errors.New(`ent: missing required field "CpUser.school_id"`)}
}
@@ -269,6 +287,14 @@ func (_c *CpUserCreate) check() error {
return &ValidationError{Name: "mobile_type", err: fmt.Errorf(`ent: validator failed for field "CpUser.mobile_type": %w`, err)}
}
}
if _, ok := _c.mutation.LoginType(); !ok {
return &ValidationError{Name: "login_type", err: errors.New(`ent: missing required field "CpUser.login_type"`)}
}
if v, ok := _c.mutation.LoginType(); ok {
if err := cpuser.LoginTypeValidator(v); err != nil {
return &ValidationError{Name: "login_type", err: fmt.Errorf(`ent: validator failed for field "CpUser.login_type": %w`, err)}
}
}
if len(_c.mutation.SysuserIDs()) == 0 {
return &ValidationError{Name: "sysuser", err: errors.New(`ent: missing required edge "CpUser.sysuser"`)}
}
@@ -335,6 +361,10 @@ func (_c *CpUserCreate) createSpec() (*CpUser, *sqlgraph.CreateSpec) {
_spec.SetField(cpuser.FieldMobileType, field.TypeEnum, value)
_node.MobileType = value
}
if value, ok := _c.mutation.LoginType(); ok {
_spec.SetField(cpuser.FieldLoginType, field.TypeEnum, value)
_node.LoginType = value
}
if nodes := _c.mutation.CptasksIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
@@ -522,6 +552,12 @@ func (u *CpUserUpsert) UpdatePassword() *CpUserUpsert {
return u
}
// ClearPassword clears the value of the "password" field.
func (u *CpUserUpsert) ClearPassword() *CpUserUpsert {
u.SetNull(cpuser.FieldPassword)
return u
}
// SetSchoolID sets the "school_id" field.
func (u *CpUserUpsert) SetSchoolID(v string) *CpUserUpsert {
u.Set(cpuser.FieldSchoolID, v)
@@ -600,6 +636,18 @@ func (u *CpUserUpsert) UpdateMobileType() *CpUserUpsert {
return u
}
// SetLoginType sets the "login_type" field.
func (u *CpUserUpsert) SetLoginType(v cpuser.LoginType) *CpUserUpsert {
u.Set(cpuser.FieldLoginType, v)
return u
}
// UpdateLoginType sets the "login_type" field to the value that was provided on create.
func (u *CpUserUpsert) UpdateLoginType() *CpUserUpsert {
u.SetExcluded(cpuser.FieldLoginType)
return u
}
// UpdateNewValues updates the mutable fields using the new values that were set on create.
// Using this option is equivalent to using:
//
@@ -701,6 +749,13 @@ func (u *CpUserUpsertOne) UpdatePassword() *CpUserUpsertOne {
})
}
// ClearPassword clears the value of the "password" field.
func (u *CpUserUpsertOne) ClearPassword() *CpUserUpsertOne {
return u.Update(func(s *CpUserUpsert) {
s.ClearPassword()
})
}
// SetSchoolID sets the "school_id" field.
func (u *CpUserUpsertOne) SetSchoolID(v string) *CpUserUpsertOne {
return u.Update(func(s *CpUserUpsert) {
@@ -792,6 +847,20 @@ func (u *CpUserUpsertOne) UpdateMobileType() *CpUserUpsertOne {
})
}
// SetLoginType sets the "login_type" field.
func (u *CpUserUpsertOne) SetLoginType(v cpuser.LoginType) *CpUserUpsertOne {
return u.Update(func(s *CpUserUpsert) {
s.SetLoginType(v)
})
}
// UpdateLoginType sets the "login_type" field to the value that was provided on create.
func (u *CpUserUpsertOne) UpdateLoginType() *CpUserUpsertOne {
return u.Update(func(s *CpUserUpsert) {
s.UpdateLoginType()
})
}
// Exec executes the query.
func (u *CpUserUpsertOne) Exec(ctx context.Context) error {
if len(u.create.conflict) == 0 {
@@ -1059,6 +1128,13 @@ func (u *CpUserUpsertBulk) UpdatePassword() *CpUserUpsertBulk {
})
}
// ClearPassword clears the value of the "password" field.
func (u *CpUserUpsertBulk) ClearPassword() *CpUserUpsertBulk {
return u.Update(func(s *CpUserUpsert) {
s.ClearPassword()
})
}
// SetSchoolID sets the "school_id" field.
func (u *CpUserUpsertBulk) SetSchoolID(v string) *CpUserUpsertBulk {
return u.Update(func(s *CpUserUpsert) {
@@ -1150,6 +1226,20 @@ func (u *CpUserUpsertBulk) UpdateMobileType() *CpUserUpsertBulk {
})
}
// SetLoginType sets the "login_type" field.
func (u *CpUserUpsertBulk) SetLoginType(v cpuser.LoginType) *CpUserUpsertBulk {
return u.Update(func(s *CpUserUpsert) {
s.SetLoginType(v)
})
}
// UpdateLoginType sets the "login_type" field to the value that was provided on create.
func (u *CpUserUpsertBulk) UpdateLoginType() *CpUserUpsertBulk {
return u.Update(func(s *CpUserUpsert) {
s.UpdateLoginType()
})
}
// Exec executes the query.
func (u *CpUserUpsertBulk) Exec(ctx context.Context) error {
if u.create.err != nil {
+62 -10
View File
@@ -83,6 +83,12 @@ func (_u *CpUserUpdate) SetNillablePassword(v *string) *CpUserUpdate {
return _u
}
// ClearPassword clears the value of the "password" field.
func (_u *CpUserUpdate) ClearPassword() *CpUserUpdate {
_u.mutation.ClearPassword()
return _u
}
// SetSchoolID sets the "school_id" field.
func (_u *CpUserUpdate) SetSchoolID(v string) *CpUserUpdate {
_u.mutation.SetSchoolID(v)
@@ -171,6 +177,20 @@ func (_u *CpUserUpdate) SetNillableMobileType(v *cpuser.MobileType) *CpUserUpdat
return _u
}
// SetLoginType sets the "login_type" field.
func (_u *CpUserUpdate) SetLoginType(v cpuser.LoginType) *CpUserUpdate {
_u.mutation.SetLoginType(v)
return _u
}
// SetNillableLoginType sets the "login_type" field if the given value is not nil.
func (_u *CpUserUpdate) SetNillableLoginType(v *cpuser.LoginType) *CpUserUpdate {
if v != nil {
_u.SetLoginType(*v)
}
return _u
}
// AddCptaskIDs adds the "cptasks" edge to the CpTask entity by IDs.
func (_u *CpUserUpdate) AddCptaskIDs(ids ...int64) *CpUserUpdate {
_u.mutation.AddCptaskIDs(ids...)
@@ -346,11 +366,6 @@ func (_u *CpUserUpdate) check() error {
return &ValidationError{Name: "username", err: fmt.Errorf(`ent: validator failed for field "CpUser.username": %w`, err)}
}
}
if v, ok := _u.mutation.Password(); ok {
if err := cpuser.PasswordValidator(v); err != nil {
return &ValidationError{Name: "password", err: fmt.Errorf(`ent: validator failed for field "CpUser.password": %w`, err)}
}
}
if v, ok := _u.mutation.SchoolID(); ok {
if err := cpuser.SchoolIDValidator(v); err != nil {
return &ValidationError{Name: "school_id", err: fmt.Errorf(`ent: validator failed for field "CpUser.school_id": %w`, err)}
@@ -361,6 +376,11 @@ func (_u *CpUserUpdate) check() error {
return &ValidationError{Name: "mobile_type", err: fmt.Errorf(`ent: validator failed for field "CpUser.mobile_type": %w`, err)}
}
}
if v, ok := _u.mutation.LoginType(); ok {
if err := cpuser.LoginTypeValidator(v); err != nil {
return &ValidationError{Name: "login_type", err: fmt.Errorf(`ent: validator failed for field "CpUser.login_type": %w`, err)}
}
}
if _u.mutation.SysuserCleared() && len(_u.mutation.SysuserIDs()) > 0 {
return errors.New(`ent: clearing a required unique edge "CpUser.sysuser"`)
}
@@ -397,6 +417,9 @@ func (_u *CpUserUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if value, ok := _u.mutation.Password(); ok {
_spec.SetField(cpuser.FieldPassword, field.TypeString, value)
}
if _u.mutation.PasswordCleared() {
_spec.ClearField(cpuser.FieldPassword, field.TypeString)
}
if value, ok := _u.mutation.Email(); ok {
_spec.SetField(cpuser.FieldEmail, field.TypeString, value)
}
@@ -418,6 +441,9 @@ func (_u *CpUserUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if value, ok := _u.mutation.MobileType(); ok {
_spec.SetField(cpuser.FieldMobileType, field.TypeEnum, value)
}
if value, ok := _u.mutation.LoginType(); ok {
_spec.SetField(cpuser.FieldLoginType, field.TypeEnum, value)
}
if _u.mutation.CptasksCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
@@ -696,6 +722,12 @@ func (_u *CpUserUpdateOne) SetNillablePassword(v *string) *CpUserUpdateOne {
return _u
}
// ClearPassword clears the value of the "password" field.
func (_u *CpUserUpdateOne) ClearPassword() *CpUserUpdateOne {
_u.mutation.ClearPassword()
return _u
}
// SetSchoolID sets the "school_id" field.
func (_u *CpUserUpdateOne) SetSchoolID(v string) *CpUserUpdateOne {
_u.mutation.SetSchoolID(v)
@@ -784,6 +816,20 @@ func (_u *CpUserUpdateOne) SetNillableMobileType(v *cpuser.MobileType) *CpUserUp
return _u
}
// SetLoginType sets the "login_type" field.
func (_u *CpUserUpdateOne) SetLoginType(v cpuser.LoginType) *CpUserUpdateOne {
_u.mutation.SetLoginType(v)
return _u
}
// SetNillableLoginType sets the "login_type" field if the given value is not nil.
func (_u *CpUserUpdateOne) SetNillableLoginType(v *cpuser.LoginType) *CpUserUpdateOne {
if v != nil {
_u.SetLoginType(*v)
}
return _u
}
// AddCptaskIDs adds the "cptasks" edge to the CpTask entity by IDs.
func (_u *CpUserUpdateOne) AddCptaskIDs(ids ...int64) *CpUserUpdateOne {
_u.mutation.AddCptaskIDs(ids...)
@@ -972,11 +1018,6 @@ func (_u *CpUserUpdateOne) check() error {
return &ValidationError{Name: "username", err: fmt.Errorf(`ent: validator failed for field "CpUser.username": %w`, err)}
}
}
if v, ok := _u.mutation.Password(); ok {
if err := cpuser.PasswordValidator(v); err != nil {
return &ValidationError{Name: "password", err: fmt.Errorf(`ent: validator failed for field "CpUser.password": %w`, err)}
}
}
if v, ok := _u.mutation.SchoolID(); ok {
if err := cpuser.SchoolIDValidator(v); err != nil {
return &ValidationError{Name: "school_id", err: fmt.Errorf(`ent: validator failed for field "CpUser.school_id": %w`, err)}
@@ -987,6 +1028,11 @@ func (_u *CpUserUpdateOne) check() error {
return &ValidationError{Name: "mobile_type", err: fmt.Errorf(`ent: validator failed for field "CpUser.mobile_type": %w`, err)}
}
}
if v, ok := _u.mutation.LoginType(); ok {
if err := cpuser.LoginTypeValidator(v); err != nil {
return &ValidationError{Name: "login_type", err: fmt.Errorf(`ent: validator failed for field "CpUser.login_type": %w`, err)}
}
}
if _u.mutation.SysuserCleared() && len(_u.mutation.SysuserIDs()) > 0 {
return errors.New(`ent: clearing a required unique edge "CpUser.sysuser"`)
}
@@ -1040,6 +1086,9 @@ func (_u *CpUserUpdateOne) sqlSave(ctx context.Context) (_node *CpUser, err erro
if value, ok := _u.mutation.Password(); ok {
_spec.SetField(cpuser.FieldPassword, field.TypeString, value)
}
if _u.mutation.PasswordCleared() {
_spec.ClearField(cpuser.FieldPassword, field.TypeString)
}
if value, ok := _u.mutation.Email(); ok {
_spec.SetField(cpuser.FieldEmail, field.TypeString, value)
}
@@ -1061,6 +1110,9 @@ func (_u *CpUserUpdateOne) sqlSave(ctx context.Context) (_node *CpUser, err erro
if value, ok := _u.mutation.MobileType(); ok {
_spec.SetField(cpuser.FieldMobileType, field.TypeEnum, value)
}
if value, ok := _u.mutation.LoginType(); ok {
_spec.SetField(cpuser.FieldLoginType, field.TypeEnum, value)
}
if _u.mutation.CptasksCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
+6
View File
@@ -190,6 +190,7 @@ var schemaGraph = func() *sqlgraph.Schema {
cpuser.FieldMobileCode: {Type: field.TypeString, Column: cpuser.FieldMobileCode},
cpuser.FieldCookie: {Type: field.TypeString, Column: cpuser.FieldCookie},
cpuser.FieldMobileType: {Type: field.TypeEnum, Column: cpuser.FieldMobileType},
cpuser.FieldLoginType: {Type: field.TypeEnum, Column: cpuser.FieldLoginType},
},
}
graph.Nodes[7] = &sqlgraph.Node{
@@ -1634,6 +1635,11 @@ func (f *CpUserFilter) WhereMobileType(p entql.StringP) {
f.Where(p.Field(cpuser.FieldMobileType))
}
// WhereLoginType applies the entql string predicate on the login_type field.
func (f *CpUserFilter) WhereLoginType(p entql.StringP) {
f.Where(p.Field(cpuser.FieldLoginType))
}
// WhereHasCptasks applies a predicate to check if query has an edge cptasks.
func (f *CpUserFilter) WhereHasCptasks() {
f.Where(entql.HasEdge("cptasks"))
File diff suppressed because one or more lines are too long
+4 -3
View File
@@ -201,11 +201,12 @@ var (
{Name: "create_time", Type: field.TypeString, SchemaType: map[string]string{"mysql": "datetime", "postgres": "timestamp", "sqlite3": "datetime"}},
{Name: "update_time", Type: field.TypeString, SchemaType: map[string]string{"mysql": "datetime", "postgres": "timestamp", "sqlite3": "datetime"}},
{Name: "username", Type: field.TypeString},
{Name: "password", Type: field.TypeString},
{Name: "password", Type: field.TypeString, Nullable: true},
{Name: "email", Type: field.TypeString, Nullable: true},
{Name: "mobile_code", Type: field.TypeString, Nullable: true},
{Name: "cookie", Type: field.TypeString, Nullable: true, Size: 2147483647},
{Name: "mobile_type", Type: field.TypeEnum, Enums: []string{"random", "authorize"}},
{Name: "login_type", Type: field.TypeEnum, Enums: []string{"account", "phone"}, Default: "account"},
{Name: "school_id", Type: field.TypeString},
{Name: "user_id", Type: field.TypeInt64},
}
@@ -217,13 +218,13 @@ var (
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "cp_users_cp_schools_cpusers",
Columns: []*schema.Column{CpUsersColumns[9]},
Columns: []*schema.Column{CpUsersColumns[10]},
RefColumns: []*schema.Column{CpSchoolsColumns[0]},
OnDelete: schema.NoAction,
},
{
Symbol: "cp_users_sys_user_cpuser",
Columns: []*schema.Column{CpUsersColumns[10]},
Columns: []*schema.Column{CpUsersColumns[11]},
RefColumns: []*schema.Column{SysUserColumns[0]},
OnDelete: schema.Cascade,
},
+74 -1
View File
@@ -6252,6 +6252,7 @@ type CpUserMutation struct {
mobile_code *string
cookie *string
mobile_type *cpuser.MobileType
login_type *cpuser.LoginType
clearedFields map[string]struct{}
cptasks map[int64]struct{}
removedcptasks map[int64]struct{}
@@ -6544,9 +6545,22 @@ func (m *CpUserMutation) OldPassword(ctx context.Context) (v string, err error)
return oldValue.Password, nil
}
// ClearPassword clears the value of the "password" field.
func (m *CpUserMutation) ClearPassword() {
m.password = nil
m.clearedFields[cpuser.FieldPassword] = struct{}{}
}
// PasswordCleared returns if the "password" field was cleared in this mutation.
func (m *CpUserMutation) PasswordCleared() bool {
_, ok := m.clearedFields[cpuser.FieldPassword]
return ok
}
// ResetPassword resets all changes to the "password" field.
func (m *CpUserMutation) ResetPassword() {
m.password = nil
delete(m.clearedFields, cpuser.FieldPassword)
}
// SetSchoolID sets the "school_id" field.
@@ -6768,6 +6782,42 @@ func (m *CpUserMutation) ResetMobileType() {
m.mobile_type = nil
}
// SetLoginType sets the "login_type" field.
func (m *CpUserMutation) SetLoginType(ct cpuser.LoginType) {
m.login_type = &ct
}
// LoginType returns the value of the "login_type" field in the mutation.
func (m *CpUserMutation) LoginType() (r cpuser.LoginType, exists bool) {
v := m.login_type
if v == nil {
return
}
return *v, true
}
// OldLoginType returns the old "login_type" field's value of the CpUser entity.
// If the CpUser object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *CpUserMutation) OldLoginType(ctx context.Context) (v cpuser.LoginType, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldLoginType is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldLoginType requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldLoginType: %w", err)
}
return oldValue.LoginType, nil
}
// ResetLoginType resets all changes to the "login_type" field.
func (m *CpUserMutation) ResetLoginType() {
m.login_type = nil
}
// AddCptaskIDs adds the "cptasks" edge to the CpTask entity by ids.
func (m *CpUserMutation) AddCptaskIDs(ids ...int64) {
if m.cptasks == nil {
@@ -7031,7 +7081,7 @@ func (m *CpUserMutation) Type() string {
// order to get all numeric fields that were incremented/decremented, call
// AddedFields().
func (m *CpUserMutation) Fields() []string {
fields := make([]string, 0, 10)
fields := make([]string, 0, 11)
if m.create_time != nil {
fields = append(fields, cpuser.FieldCreateTime)
}
@@ -7062,6 +7112,9 @@ func (m *CpUserMutation) Fields() []string {
if m.mobile_type != nil {
fields = append(fields, cpuser.FieldMobileType)
}
if m.login_type != nil {
fields = append(fields, cpuser.FieldLoginType)
}
return fields
}
@@ -7090,6 +7143,8 @@ func (m *CpUserMutation) Field(name string) (ent.Value, bool) {
return m.Cookie()
case cpuser.FieldMobileType:
return m.MobileType()
case cpuser.FieldLoginType:
return m.LoginType()
}
return nil, false
}
@@ -7119,6 +7174,8 @@ func (m *CpUserMutation) OldField(ctx context.Context, name string) (ent.Value,
return m.OldCookie(ctx)
case cpuser.FieldMobileType:
return m.OldMobileType(ctx)
case cpuser.FieldLoginType:
return m.OldLoginType(ctx)
}
return nil, fmt.Errorf("unknown CpUser field %s", name)
}
@@ -7198,6 +7255,13 @@ func (m *CpUserMutation) SetField(name string, value ent.Value) error {
}
m.SetMobileType(v)
return nil
case cpuser.FieldLoginType:
v, ok := value.(cpuser.LoginType)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetLoginType(v)
return nil
}
return fmt.Errorf("unknown CpUser field %s", name)
}
@@ -7231,6 +7295,9 @@ func (m *CpUserMutation) AddField(name string, value ent.Value) error {
// mutation.
func (m *CpUserMutation) ClearedFields() []string {
var fields []string
if m.FieldCleared(cpuser.FieldPassword) {
fields = append(fields, cpuser.FieldPassword)
}
if m.FieldCleared(cpuser.FieldEmail) {
fields = append(fields, cpuser.FieldEmail)
}
@@ -7254,6 +7321,9 @@ func (m *CpUserMutation) FieldCleared(name string) bool {
// error if the field is not defined in the schema.
func (m *CpUserMutation) ClearField(name string) error {
switch name {
case cpuser.FieldPassword:
m.ClearPassword()
return nil
case cpuser.FieldEmail:
m.ClearEmail()
return nil
@@ -7301,6 +7371,9 @@ func (m *CpUserMutation) ResetField(name string) error {
case cpuser.FieldMobileType:
m.ResetMobileType()
return nil
case cpuser.FieldLoginType:
m.ResetLoginType()
return nil
}
return fmt.Errorf("unknown CpUser field %s", name)
}
-4
View File
@@ -185,10 +185,6 @@ func init() {
cpuserDescUsername := cpuserFields[1].Descriptor()
// cpuser.UsernameValidator is a validator for the "username" field. It is called by the builders before save.
cpuser.UsernameValidator = cpuserDescUsername.Validators[0].(func(string) error)
// cpuserDescPassword is the schema descriptor for password field.
cpuserDescPassword := cpuserFields[2].Descriptor()
// cpuser.PasswordValidator is a validator for the "password" field. It is called by the builders before save.
cpuser.PasswordValidator = cpuserDescPassword.Validators[0].(func(string) error)
// cpuserDescSchoolID is the schema descriptor for school_id field.
cpuserDescSchoolID := cpuserFields[3].Descriptor()
// cpuser.SchoolIDValidator is a validator for the "school_id" field. It is called by the builders before save.
+2 -1
View File
@@ -19,12 +19,13 @@ func (CpUser) Fields() []ent.Field {
return []ent.Field{
field.Int64("user_id"),
field.String("username").NotEmpty(),
field.String("password").NotEmpty(),
field.String("password").Optional(),
field.String("school_id").NotEmpty(),
field.String("email").Optional(),
field.String("mobile_code").Optional(),
field.Text("cookie").Optional(),
field.Enum("mobile_type").Values("random", "authorize"),
field.Enum("login_type").Values("account", "phone").Default("account"),
}
}
@@ -94,7 +94,7 @@ func (c *CpdailyTaskHandler) ProcessTask(ctx context.Context, task *asynq.Task)
schoolDetail := school.GetSchoolDetail(ctx, targetTask.Edges.CpUser.SchoolID)
cookie := targetTask.Edges.CpUser.Cookie
restyClient := login.GetClient(ctx, cookie)
if !login.CookieEnabled(ctx, schoolDetail.WecloudUrl, restyClient) {
if !login.CookieEnabled(ctx, schoolDetail.WecloudUrl, restyClient, targetTask.Edges.CpUser.LoginType) {
loginExecutor := login.GetCpdailyLoginBySchoolInfo(ctx, &schoolDetail)
loginExecutor.Login(ctx, &schoolDetail, targetTask.Edges.CpUser.Username, targetTask.Edges.CpUser.Password)
cookie = loginExecutor.GetCookieString()
@@ -5,6 +5,7 @@ import (
"context"
"encoding/gob"
"likedream-goframe/internal/application/xuexitong"
"likedream-goframe/internal/application/xuexitong/entity"
"likedream-goframe/internal/common/db"
errors2 "likedream-goframe/internal/common/errors"
"likedream-goframe/internal/ent"
@@ -105,13 +106,25 @@ func (h *XuexitongTaskHandler) ProcessTask(ctx context.Context, task *asynq.Task
// 刷课完成后,统计任务情况
g.Log().Infof(ctx, "刷课完成,正在统计任务情况...")
// 获取章节列表
chapters := courseService.PullCourseChapterList(ctx, targetCourse.CourseID)
// 先获取课程列表找到目标课程
courseList := courseService.PullCourseList(ctx)
var course *entity.XueXiTCourse
for _, c := range courseList {
if c.CourseID == targetCourse.CourseID {
course = &c
break
}
}
// 统计总任务数(累加所有章节的JobCount)
totalTasks := 0
for _, chapter := range chapters {
totalTasks += chapter.JobCount
if course != nil {
// 获取章节列表
chapters := courseService.PullCourseChapterList(ctx, *course)
// 统计总任务数(累加所有章节的JobCount)
for _, chapter := range chapters {
totalTasks += chapter.JobCount
}
}
g.Log().Infof(ctx, "课程 %s 统计完成: 总任务点 %d", targetCourse.CourseName, totalTasks)
@@ -18,6 +18,9 @@ type BalanceServiceV1 struct {
}
func (v *BalanceServiceV1) ChangeUserBalance(ctx context.Context, userId int64, balance decimal.Decimal, reason string) {
if decimal.Zero.Equal(balance) {
return
}
err := db.WithTx(ctx, func(c context.Context, tx *ent.Tx) {
// 使用 SELECT ... FOR UPDATE 锁定用户记录
user, err := tx.SysUser.Query().
+72 -28
View File
@@ -13,6 +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"
@@ -78,9 +79,19 @@ func (s CourseServiceV1) AddCourse(ctx context.Context, req *v1.AddCourseReq) *u
client := loginClient.GetClient()
courseService := xuexitong.NewXuexitongCourse(client)
var targetCourse *entity.XueXiTCourse
// 获取课程章节列表
chapters := courseService.PullCourseChapterList(ctx, req.CourseID)
courseList := courseService.PullCourseList(ctx)
for _, course := range courseList {
if course.CourseID == req.CourseID {
targetCourse = &course
break
}
}
if targetCourse == nil {
utils.OkOrPanic(errors2.NewBusinessError(400, "未找到该课程"))
}
chapters := courseService.PullCourseChapterList(ctx, *targetCourse)
// 定义节点信息结构
type NodeInfo struct {
@@ -94,46 +105,79 @@ func (s CourseServiceV1) AddCourse(ctx context.Context, req *v1.AddCourseReq) *u
var allNodes []NodeInfo
var completedNodes []string
// 获取课程信息用于API调用
courses := courseService.PullCourseList(ctx)
var targetCourse *entity.XueXiTCourse
for _, c := range courses {
if c.CourseID == req.CourseID {
targetCourse = &c
break
}
}
if targetCourse == nil {
utils.OkOrPanic(errors2.NewBusinessError(400, "未找到该课程"))
}
// 递归获取所有章节的任务点
var collectNodes func(chapters []entity.XueXiTCourseChapter)
collectNodes = func(chapters []entity.XueXiTCourseChapter) {
for _, chapter := range chapters {
// 如果有任务点,获取卡片信息
if chapter.JobCount > 0 {
cards, err := courseService.FetchChapterCards(ctx, *targetCourse, chapter.ID, chapter.ID)
cards, points, err := courseService.FetchChapterCards(ctx, *targetCourse, chapter.ID)
if err != nil {
logger.Logger.Warn("获取章节任务点失败", zap.String("chapter", chapter.Name), zap.Error(err))
} else {
for _, card := range cards {
} else if points != nil {
chapterIDStr := strconv.Itoa(chapter.ID)
// 统计视频任务点
for _, video := range points.Videos {
nodeInfo := NodeInfo{
ChapterID: chapter.ID,
ChapterID: chapterIDStr,
ChapterName: chapter.Name,
CardID: card.ID,
CardTitle: card.Title,
CardType: card.Type,
CardID: video.JobID,
CardTitle: video.Title,
CardType: "video",
}
allNodes = append(allNodes, nodeInfo)
// 检查是否已完成
if card.IsPassed {
nodeKey := chapter.ID + ":" + card.ID
completedNodes = append(completedNodes, nodeKey)
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 暂时不使用
}
}
+4 -4
View File
@@ -45,7 +45,7 @@ func (v CpLeaveServiceV1) GetLeaveListFromSystem(ctx context.Context, req *v1.Ge
client := login.GetClient(ctx, cookie)
// 检查cookie是否有效
if !login.CookieEnabled(ctx, schoolDetail.WecloudUrl, client) {
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()
@@ -120,14 +120,14 @@ func (v CpLeaveServiceV1) Report(ctx context.Context, req *v1.CpLeaveReportReq)
}
// 计算扣款金额
basePoint, err := decimal.NewFromString(g.Cfg().MustGet(ctx, cst2.ConfigBasePointCpdaily).String())
basePoint, err := decimal.NewFromString(g.Cfg().MustGet(ctx, cst2.ConfigBasePointCpdailyLeave).String())
utils.OkOrPanic(err)
if user.Edges.Agent != nil {
basePoint = basePoint.Mul(user.Edges.Agent.Rate)
}
// 先扣款
balance.BalanceService.ChangeUserBalance(ctx, user.ID, basePoint.Neg(), "销假")
balance.BalanceService.ChangeUserBalance(ctx, user.ID, basePoint.Neg(), "今日校园销假")
// 创建销假记录
leaveRecord := db2.Global.CpLeave.Create().
@@ -161,7 +161,7 @@ func (v CpLeaveServiceV1) Report(ctx context.Context, req *v1.CpLeaveReportReq)
client := login.GetClient(ctx, cookie)
// 检查cookie是否有效
if !login.CookieEnabled(ctx, schoolDetail.WecloudUrl, client) {
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()
+3 -3
View File
@@ -43,7 +43,7 @@ func (v CpTaskServiceV1) GetRecentTasks(ctx context.Context, req *v1.GetRecentTa
}
schoolDetail := school.GetSchoolDetail(ctx, cpUser.SchoolID)
client := login.GetClient(ctx, cpUser.Cookie)
if !login.CookieEnabled(ctx, schoolDetail.WecloudUrl, client) {
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()
@@ -118,7 +118,7 @@ func (v CpTaskServiceV1) TaskFormData(ctx context.Context, req *v1.GetCpTaskForm
schoolDetail := school.GetSchoolDetail(ctx, cpTask.Edges.CpUser.SchoolID)
cookie := cpUser.Cookie
client := login.GetClient(ctx, cookie)
if !login.CookieEnabled(ctx, schoolDetail.WecloudUrl, client) {
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()
@@ -180,7 +180,7 @@ func (v CpTaskServiceV1) PostExecute(ctx context.Context, req *v1.PostCpTaskExec
}
//扣积分
basePoint, err := decimal.NewFromString(g.Cfg().MustGet(ctx, cst2.ConfigBasePointCpdaily).String())
basePoint, err := decimal.NewFromString(g.Cfg().MustGet(ctx, cst2.ConfigBasePointCpdailyTask).String())
utils.OkOrPanic(err)
if user.Edges.Agent != nil {
basePoint = basePoint.Mul(user.Edges.Agent.Rate)
+50 -2
View File
@@ -3,6 +3,7 @@ package cpdaily
import (
"context"
v1 "likedream-goframe/internal/api/v1"
"likedream-goframe/internal/application/cookiejar"
"likedream-goframe/internal/application/cpdaily/login"
"likedream-goframe/internal/application/cpdaily/school"
"likedream-goframe/internal/common/cst"
@@ -12,12 +13,15 @@ import (
"likedream-goframe/internal/ent/cpuser"
"likedream-goframe/internal/ent/sysuser"
"likedream-goframe/internal/framework/redis"
"likedream-goframe/internal/service/balance"
"likedream-goframe/internal/utils"
"strconv"
"time"
"github.com/bytedance/sonic"
"github.com/gogf/gf/v2/frame/g"
"github.com/samber/oops"
"github.com/shopspring/decimal"
)
type CpUserServiceV1 struct {
@@ -66,6 +70,7 @@ func (v CpUserServiceV1) ConfirmAdd(ctx context.Context, req *v1.CpUserConfirmAd
SetMobileType(cpuser.MobileTypeRandom).
SetSchoolID(sc.Id).
SetSysuserID(user.ID).
SetLoginType(cpuser.LoginTypeAccount).
SaveX(ctx)
return utils.SuccessWithMsg("添加成功")
}
@@ -88,6 +93,7 @@ func (v CpUserServiceV1) List(ctx context.Context, req *v1.CpUserListReq) *utils
// 忽略密码
for _, v := range data {
v.Password = ""
v.Cookie = ""
}
return utils.SuccessWithTotal[[]*ent.CpUser](data, total)
}
@@ -174,11 +180,53 @@ func (v CpUserServiceV1) AuthorizeRandom(ctx context.Context, req *v1.CpUserAuth
}
func (v CpUserServiceV1) LoginGetCode(ctx context.Context, req *v1.LoginGetCode) *utils.Response[any] {
return utils.SuccessWithMsg("")
user := utils.GetUserInfoFromCtx(ctx)
// 扣费
basePoint, err := decimal.NewFromString(g.Cfg().MustGet(ctx, cst.ConfigBasePointCpdailyPhone).String())
utils.OkOrPanic(err)
if user.Edges.Agent != nil {
basePoint = basePoint.Mul(user.Edges.Agent.Rate)
}
if user.Balance.Sub(basePoint).IsNegative() {
return utils.Fail(400, "余额不足")
}
loginExecutor := login.NewSmsWithoutDeviceID()
loginExecutor.SendSms(ctx, req.Mobile)
balance.BalanceService.ChangeUserBalance(ctx, user.ID, basePoint.Neg(), "手机号登录 - 验证码")
return utils.SuccessWithMsg("发送成功")
}
func (v CpUserServiceV1) AddByCode(ctx context.Context, req *v1.AddByCode) *utils.Response[any] {
return utils.SuccessWithMsg("")
user := utils.GetUserInfoFromCtx(ctx)
jar := cookiejar.NewPersistCookieJar()
loginExecutor := login.NewSmsWithoutDeviceID()
data := loginExecutor.LoginByCode(context.Background(), req.Mobile, req.Code, jar)
loginExecutor.SetLoginCookie(context.Background(), jar, data)
// 扣费
basePoint, err := decimal.NewFromString(g.Cfg().MustGet(ctx, cst.ConfigBasePointCpdailyPhone).String())
utils.OkOrPanic(err)
if user.Edges.Agent != nil {
basePoint = basePoint.Mul(user.Edges.Agent.Rate)
}
balance.BalanceService.ChangeUserBalance(ctx, user.ID, basePoint.Neg(), "手机号登录 - 登录")
if req.Id == 0 {
db.Global.CpUser.Create().
SetUsername(req.Mobile).
SetEmail(req.Email).
SetSchoolID(req.SchoolId).
SetCookie(loginExecutor.GetCookieString()).
SetMobileCode(utils.UUID()).
SetMobileType(cpuser.MobileTypeRandom).
SetSysuserID(user.ID).
SetLoginType(cpuser.LoginTypePhone).
SaveX(ctx)
return utils.SuccessWithMsg("添加成功")
} else {
db.Global.CpUser.UpdateOneID(req.Id).
SetCookie(loginExecutor.GetCookieString()).
ExecX(ctx)
return utils.SuccessWithMsg("更新成功")
}
}
func (v CpUserServiceV1) LoginUrl(ctx context.Context, req *v1.CpUserLoginUrlReq) *utils.Response[any] {
+6 -3
View File
@@ -4,14 +4,17 @@ import (
"context"
"likedream-goframe/internal/application/cpdaily/login"
"likedream-goframe/internal/application/cpdaily/school"
"likedream-goframe/internal/framework/redis"
"resty.dev/v3"
)
const testUsername = "22302204227"
const testPassword = "Yuki030616."
const testSchoolId = "fzfu"
const testUsername = "20241070187"
const testPassword = "Xqihan2006."
const testSchoolId = "1020481510696504"
func LoginTestUser() (*resty.Client, *school.SchoolDetailInfo) {
redis.Init(context.Background())
schoolDetail := school.GetSchoolDetail(context.Background(), testSchoolId)
loginExecutor := login.GetCpdailyLoginBySchoolInfo(context.Background(), &schoolDetail)