增加推送

This commit is contained in:
johlanse 2022-07-24 15:56:12 +08:00
parent dd2f316509
commit 38acc17d75
15 changed files with 96 additions and 16 deletions

1
go.mod
View File

@ -38,6 +38,7 @@ require (
github.com/gorilla/websocket v1.4.2 // indirect github.com/gorilla/websocket v1.4.2 // indirect
github.com/hashicorp/errwrap v1.0.0 // indirect github.com/hashicorp/errwrap v1.0.0 // indirect
github.com/hashicorp/go-multierror v1.1.1 // indirect github.com/hashicorp/go-multierror v1.1.1 // indirect
github.com/huoxue1/lorca v0.1.11 // indirect
github.com/jonboulle/clockwork v0.2.2 // indirect github.com/jonboulle/clockwork v0.2.2 // indirect
github.com/json-iterator/go v1.1.10 // indirect github.com/json-iterator/go v1.1.10 // indirect
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect

3
go.sum
View File

@ -43,6 +43,8 @@ github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/U
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo=
github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM=
github.com/huoxue1/lorca v0.1.11 h1:B5x4Xta8rauGCERoCHY7nWg2z1GUrksf9ycZGHwLs4Q=
github.com/huoxue1/lorca v0.1.11/go.mod h1:eEI3aGkmMladREqFJwUhd8cLlSUgG13wvuNprVjaVaY=
github.com/imroc/req/v3 v3.8.2 h1:wFZ7B0dclCQyjClP5GwXRboUGIek5l0mCpodrGgT01c= github.com/imroc/req/v3 v3.8.2 h1:wFZ7B0dclCQyjClP5GwXRboUGIek5l0mCpodrGgT01c=
github.com/imroc/req/v3 v3.8.2/go.mod h1:3JIicOKEDHfCSYYNLb/ObZNpx64EV5y40VlHMwhUCzU= github.com/imroc/req/v3 v3.8.2/go.mod h1:3JIicOKEDHfCSYYNLb/ObZNpx64EV5y40VlHMwhUCzU=
github.com/jonboulle/clockwork v0.2.2 h1:UOGuzwb1PwsrDAObMuhUnj0p5ULPj8V/xJ7Kx9qUBdQ= github.com/jonboulle/clockwork v0.2.2 h1:UOGuzwb1PwsrDAObMuhUnj0p5ULPj8V/xJ7Kx9qUBdQ=
@ -139,6 +141,7 @@ golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200222125558-5a598a2470a0/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20220111093109-d55c255bac03 h1:0FB83qp0AzVJm+0wcIlauAjJ+tNdh7jLuacRYCIVv7s= golang.org/x/net v0.0.0-20220111093109-d55c255bac03 h1:0FB83qp0AzVJm+0wcIlauAjJ+tNdh7jLuacRYCIVv7s=

View File

@ -56,6 +56,12 @@ type Config struct {
} `json:"retry" yaml:"retry"` } `json:"retry" yaml:"retry"`
// 专项答题可接受的最小值 // 专项答题可接受的最小值
SpecialMinScore int `json:"special_min_score" yaml:"special_min_score"` SpecialMinScore int `json:"special_min_score" yaml:"special_min_score"`
JiGuangPush struct {
Enable bool `json:"enable" yaml:"enable"`
Secret string `json:"secret" yaml:"secret"`
AppKey string `json:"app_key" yaml:"app_key"`
} `json:"ji_guang_push" yaml:"ji_guang_push"`
} }
var ( var (

View File

@ -76,3 +76,10 @@ start_wait: 0
# 专项答题可接受的最小分值,因一天重复运行的时候,若专项答题未能答满会继续答新的一套题,会浪费题 # 专项答题可接受的最小分值,因一天重复运行的时候,若专项答题未能答满会继续答新的一套题,会浪费题
special_min_score: 10 special_min_score: 10
weekly_min_score:
ji_guang_push:
enable: false
secret: ""
app_key: ""

View File

@ -90,7 +90,7 @@ func (c *Core) Init() {
} }
} }
func GetToken(code, sign string) (bool, error) { func GetToken(code, sign, pushId string) (bool, error) {
client := req.C() client := req.C()
client.SetCommonHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36") client.SetCommonHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36")
response, err := client.R().SetQueryParams(map[string]string{ response, err := client.R().SetQueryParams(map[string]string{
@ -118,6 +118,7 @@ func GetToken(code, sign string) (bool, error) {
UID: uid, UID: uid,
Token: token, Token: token,
LoginTime: time.Now().Unix(), LoginTime: time.Now().Unix(),
PushId: pushId,
} }
err = model.AddUser(user) err = model.AddUser(user)
if err != nil { if err != nil {

View File

@ -101,7 +101,6 @@ func (c *Core) RespondDaily(user *model.User, model string) {
err = page.Click(WEEKEND) err = page.Click(WEEKEND)
if err != nil { if err != nil {
log.Errorln("跳转到积分页面错误") log.Errorln("跳转到积分页面错误")
return return
} }
c.Push("text", "已加载每周答题模块") c.Push("text", "已加载每周答题模块")

View File

@ -116,7 +116,7 @@ func PrintScore(score Score) string {
return result return result
} }
func formatScore(score Score) string { func FormatScore(score Score) string {
result := "" result := ""
result += fmt.Sprintf("当前学习总积分:%d 今日得分:%d\n", score.TotalScore, score.TodayScore) result += fmt.Sprintf("当前学习总积分:%d 今日得分:%d\n", score.TotalScore, score.TodayScore)
result += fmt.Sprintf("登录:%v/%v 文章学习:%v/%v 视频学习:%v/%v 视频时长:%v/%v\n每日答题%v/%v 每周答题:%v/%v 专项答题:%v/%v", result += fmt.Sprintf("登录:%v/%v 文章学习:%v/%v 视频学习:%v/%v 视频时长:%v/%v\n每日答题%v/%v 每周答题:%v/%v 专项答题:%v/%v",

View File

@ -376,7 +376,7 @@ func getScores(bot *Telegram, args []string) {
if err != nil { if err != nil {
message += err.Error() + "\n" message += err.Error() + "\n"
} }
message += formatScore(score) + "\n" message += FormatScore(score) + "\n"
} }
bot.SendMsg(message) bot.SendMsg(message)
} }

View File

@ -164,6 +164,7 @@ func main() {
} }
func do(m string) { func do(m string) {
defer func() { defer func() {
err := recover() err := recover()
if err != nil { if err != nil {
@ -202,6 +203,13 @@ func do(m string) {
return return
} }
message := u.Nick + " 学习完成:今日得分:" + strconv.Itoa(score.TodayScore) message := u.Nick + " 学习完成:今日得分:" + strconv.Itoa(score.TodayScore)
score, _ = lib.GetUserScore(user.ToCookies())
content := lib.FormatScore(score)
err = push.PushMessage(user.Nick+"学习情况", content, "score", user.PushId)
if err != nil {
log.Errorln(err.Error())
err = nil
}
core2.Push("markdown", message) core2.Push("markdown", message)
core2.Push("flush", "") core2.Push("flush", "")
} }

View File

@ -26,7 +26,8 @@ func init() {
constraint user_pk constraint user_pk
primary key, primary key,
token TEXT not null, token TEXT not null,
login_time integer not null login_time integer not null,
push_id TEXT
); );
`) `)
} }

View File

@ -28,6 +28,7 @@ type User struct {
UID string `json:"uid"` UID string `json:"uid"`
Token string `json:"token"` Token string `json:"token"`
LoginTime int64 `json:"login_time"` LoginTime int64 `json:"login_time"`
PushId string `json:"push_id"`
} }
// Query // Query
@ -51,7 +52,7 @@ func Query() ([]*User, error) {
}(results) }(results)
for results.Next() { for results.Next() {
u := new(User) u := new(User)
err := results.Scan(&u.Nick, &u.UID, &u.Token, &u.LoginTime) err := results.Scan(&u.Nick, &u.UID, &u.Token, &u.LoginTime, &u.PushId)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -79,7 +80,7 @@ func Query() ([]*User, error) {
*/ */
func Find(uid string) *User { func Find(uid string) *User {
u := new(User) u := new(User)
err := db.QueryRow("select * from user where uid=?;", uid).Scan(&u.Nick, &u.UID, &u.Token, &u.LoginTime) err := db.QueryRow("select * from user where uid=?;", uid).Scan(&u.Nick, &u.UID, &u.Token, &u.LoginTime, &u.PushId)
if err != nil { if err != nil {
return nil return nil
} }
@ -96,7 +97,7 @@ func AddUser(user *User) error {
ping() ping()
count := UserCount(user.UID) count := UserCount(user.UID)
if count < 1 { if count < 1 {
_, err := db.Exec("insert into user (nick, uid, token, login_time) values (?,?,?,?)", user.Nick, user.UID, user.Token, user.LoginTime) _, err := db.Exec("insert into user (nick, uid, token, login_time,push_id) values (?,?,?,?,?)", user.Nick, user.UID, user.Token, user.LoginTime, user.PushId)
if err != nil { if err != nil {
log.Errorln("数据库插入失败") log.Errorln("数据库插入失败")
log.Errorln(err.Error()) log.Errorln(err.Error())
@ -119,7 +120,7 @@ func AddUser(user *User) error {
*/ */
func UpdateUser(user *User) error { func UpdateUser(user *User) error {
ping() ping()
_, err := db.Exec("update user set token=? where uid = ?", user.Token, user.UID) _, err := db.Exec("update user set token=?,login_time=?,push_id=? where uid = ?", user.Token, user.LoginTime, user.PushId, user.UID)
if err != nil { if err != nil {
log.Errorln("更新数据失败") log.Errorln("更新数据失败")
log.Errorln(err.Error()) log.Errorln(err.Error())
@ -242,10 +243,9 @@ func check() {
} }
if token != "" { if token != "" {
user.Token = token user.Token = token
user.LoginTime = time.Now().Unix()
_ = UpdateUser(user) _ = UpdateUser(user)
} }
} }
time.Sleep(time.Hour * time.Duration(rand.Intn(3))) time.Sleep(time.Hour * time.Duration(rand.Intn(6)))
} }
} }

38
push/jpush.go Normal file
View File

@ -0,0 +1,38 @@
package push
import (
"encoding/base64"
"errors"
"github.com/imroc/req/v3"
"github.com/huoxue1/study_xxqg/lib"
)
func PushMessage(title, content, message, pushID string) error {
if !lib.GetConfig().JiGuangPush.Enable {
return nil
}
c := req.C()
c.SetProxyURL("http://127.0.0.1:8898")
response, err := c.R().SetBodyJsonMarshal(map[string]interface{}{
"platform": "all",
"audience": map[string][]string{
"registration_id": {pushID},
},
"notification": map[string]interface{}{
"alert": content,
},
"message": map[string]string{
"msg_content": message,
},
}).SetHeader("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(lib.GetConfig().JiGuangPush.AppKey+":"+lib.GetConfig().JiGuangPush.Secret))).Post("https://api.jpush.cn/v3/push")
if err != nil {
return err
}
if response.IsSuccess() {
return nil
}
return errors.New("消息推送失败" + response.Response.Status)
}

View File

@ -14,6 +14,7 @@ import (
"github.com/huoxue1/study_xxqg/lib" "github.com/huoxue1/study_xxqg/lib"
"github.com/huoxue1/study_xxqg/model" "github.com/huoxue1/study_xxqg/model"
"github.com/huoxue1/study_xxqg/push"
"github.com/huoxue1/study_xxqg/utils" "github.com/huoxue1/study_xxqg/utils"
) )
@ -117,7 +118,9 @@ func addUser() gin.HandlerFunc {
}) })
return return
} }
_, err = lib.GetToken(p.Code, p.State) registerID, _ := ctx.GetQuery("register_id")
log.Infoln("the jpush register id is " + registerID)
_, err = lib.GetToken(p.Code, p.State, registerID)
if err != nil { if err != nil {
ctx.JSON(403, Resp{ ctx.JSON(403, Resp{
Code: 403, Code: 403,
@ -228,8 +231,21 @@ func study() gin.HandlerFunc {
core.RespondDaily(user, "weekly") core.RespondDaily(user, "weekly")
core.RespondDaily(user, "special") core.RespondDaily(user, "special")
} }
score, _ := lib.GetUserScore(user.ToCookies())
content := lib.FormatScore(score)
err := push.PushMessage(user.Nick+"学习情况", content, "score", user.PushId)
if err != nil {
log.Errorln(err.Error())
}
state.Delete(uid) state.Delete(uid)
}() }()
ctx.JSON(200, Resp{
Code: 200,
Message: "",
Data: "",
Success: true,
Error: "",
})
} }
} }

View File

@ -17,7 +17,7 @@ var static embed.FS
// @Description: // @Description:
// @return *gin.Engine // @return *gin.Engine
func RouterInit() *gin.Engine { func RouterInit() *gin.Engine {
router := gin.New() router := gin.Default()
router.Use(Cors()) router.Use(Cors())
router.StaticFS("/static", http.FS(static)) router.StaticFS("/static", http.FS(static))
@ -35,7 +35,7 @@ func RouterInit() *gin.Engine {
user := router.Group("/user", check()) user := router.Group("/user", check())
// 添加用户 // 添加用户
user.POST("/", addUser()) user.POST("", addUser())
user.GET("/", getUsers()) user.GET("/", getUsers())