Skip to content

Commit

Permalink
Refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
iyear committed Mar 12, 2021
1 parent 5c67054 commit 90248dc
Show file tree
Hide file tree
Showing 7 changed files with 104 additions and 323 deletions.
26 changes: 13 additions & 13 deletions bots/control.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (
"github.com/spf13/viper"
"github.com/tidwall/gjson"
tb "gopkg.in/tucnak/telebot.v2"
"main/db"
"main/core"
"main/logger"
"main/outlook"
"main/util"
Expand All @@ -29,22 +29,22 @@ func BindUser(m *tb.Message, cid, cse string) error {
Alias := tmp[1]
code := util.GetURLValue(tmp[0], "code")
//fmt.Println(code)
access, refresh, err := outlook.MSFirGetToken(code, cid, cse)
access, refresh, err := MSFirGetToken(code, cid, cse)
if err != nil {
logger.Println("%d Bind error:GetRefreshToken %s \n", m.Chat.ID, err.Error())
return err
}

//token has gotten
bot.Send(m.Chat, "Token获取成功!")
info, err := outlook.MSGetUserInfo(access)
info, err := outlook.GetUserInfo(access)
//fmt.Println("TgId:%d Refresh Token: %s\n", m.Chat.ID, refresh)
if err != nil {
logger.Println("%d Bind error:Getinfo %s \n", m.Chat.ID, err.Error())
return err
}

var u db.MSData
var u core.Client
u.TgId = m.Chat.ID
u.RefreshToken = refresh
//TG的Data传递最高64bytes,一些MsId超过了报错BUTTON_DATA_INVALID (0),采取md5
Expand All @@ -62,7 +62,7 @@ func BindUser(m *tb.Message, cid, cse string) error {
}
//MS information has gotten
bot.Send(m.Chat, "MS_ID(MD5): "+u.MsId+"\nuserPrincipalName: "+gjson.Get(info, "userPrincipalName").String()+"\ndisplayName: "+gjson.Get(info, "displayName").String()+"\n")
if ok, err := db.AddData(u); !ok {
if ok, err := core.AddData(u); !ok {
logger.Println("%d Bind error: %s\n", m.Chat.ID, err)
return err
}
Expand All @@ -72,14 +72,14 @@ func BindUser(m *tb.Message, cid, cse string) error {

//get bind num
func GetBindNum(TgId int64) int {
data := db.QueryDataByTG(TgId)
data := core.QueryDataByTG(TgId)
return len(data)
}

//return true => exist
func MSAppIsExist(TgId int64, ClientId string) bool {
data := db.QueryDataByTG(TgId)
var res db.MSData
data := core.QueryDataByTG(TgId)
var res core.Client
for _, res = range data {
if res.ClientId == ClientId {
return true
Expand All @@ -99,7 +99,7 @@ func SignTask() {
SignOk = make(map[int64]int)
fmt.Println("----Task Begin----")
fmt.Println("Time:" + time.Now().Format("2006-01-02 15:04:05"))
data := db.QueryDataAll()
data := core.QueryDataAll()
num = len(data)
fmt.Println("Start Sign")
//签到任务
Expand All @@ -118,7 +118,7 @@ func SignTask() {
tmpBtn := &tb.ReplyMarkup{InlineKeyboard: inlineKeys}

se := u.MsId + " ( @" + chat.Username + " )"
access, newRefreshToken, err := outlook.MSGetToken(u.RefreshToken, u.ClientId, u.ClientSecret)
access, newRefreshToken, err := outlook.GetToken(u.RefreshToken, u.ClientId, u.ClientSecret)

if err != nil {
logger.Println(u.MsId+" ", err)
Expand All @@ -127,7 +127,7 @@ func SignTask() {
ErrorTimes[u.MsId]++
continue
}
if ok, err := outlook.OutLookGetMails(access); !ok {
if ok, err := outlook.GetOutLookMails(access); !ok {
logger.Println(u.MsId+" ", err)
bot.Send(chat, pre+gjson.Get(err.Error(), "error").String(), tmpBtn)
ErrorTimes[u.MsId]++
Expand All @@ -136,7 +136,7 @@ func SignTask() {
}
u.Uptime = time.Now().Unix()
u.RefreshToken = newRefreshToken
if ok, err := db.UpdateData(u); !ok {
if ok, err := core.UpdateData(u); !ok {
logger.Println(u.MsId+" ", err)
bot.Send(chat, pre+err.Error(), tmpBtn)
SignErr = append(SignErr, se)
Expand All @@ -160,7 +160,7 @@ func SignTask() {
//错误上限账户清退
if ErrorTimes[u.MsId] == ErrMaxTimes {
logger.Println(u.MsId + " Error Limit")
if ok, err := db.DelData(u.MsId); !ok {
if ok, err := core.DelData(u.MsId); !ok {
logger.Println(err)
} else {
UnbindUser = append(UnbindUser, u.MsId+" ( @"+chat.Username+" )")
Expand Down
18 changes: 9 additions & 9 deletions bots/handle.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (
"github.com/spf13/viper"
tb "gopkg.in/tucnak/telebot.v2"
"io/ioutil"
"main/db"
"main/core"
"main/logger"
"main/outlook"
"main/util"
Expand Down Expand Up @@ -86,7 +86,7 @@ func bStart(m *tb.Message) {

func bMy(m *tb.Message) {
logger.Println(strconv.FormatInt(m.Chat.ID, 10) + " Start Manager Users")
data := db.QueryDataByTG(m.Chat.ID)
data := core.QueryDataByTG(m.Chat.ID)
var inlineKeys [][]tb.InlineButton
for _, u := range data {
inlineBtn := tb.InlineButton{
Expand All @@ -101,7 +101,7 @@ func bMy(m *tb.Message) {
}
func bMyInlineBtn(c *tb.Callback) {
logger.Println(strconv.FormatInt(c.Message.Chat.ID, 10) + " Get User Info")
r := db.QueryDataByMS(c.Data)
r := core.QueryDataByMS(c.Data)
u := r[0]
bot.Send(c.Message.Chat, "信息\n别名:"+u.Alias+"\nMS_ID(MD5): "+u.MsId+"\nclient_id: "+u.ClientId+"\nclient_secret: "+u.ClientSecret+"\n最近更新时间: "+time.Unix(u.Uptime, 0).Format("2006-01-02 15:04:05"))
bot.Respond(c)
Expand All @@ -110,7 +110,7 @@ func bMyInlineBtn(c *tb.Callback) {
func bBind1(m *tb.Message) {
logger.Println(strconv.FormatInt(m.Chat.ID, 10) + " Start Bind")
logger.Println("ReApp: " + strconv.FormatInt(m.Chat.ID, 10))
bot.Send(m.Chat, "应用注册: [点击直达]("+outlook.MSGetReAppUrl()+")", tb.ModeMarkdown)
bot.Send(m.Chat, "应用注册: [点击直达]("+outlook.GetMSRegisterAppUrl()+")", tb.ModeMarkdown)
_, err := bot.Send(m.Chat, "请回复client_id+空格+client_secret", &tb.ReplyMarkup{ForceReply: true})
if err != nil {
logger.Println(err)
Expand All @@ -131,7 +131,7 @@ func bBind2(m *tb.Message) {
logger.Println("client_id: " + tmp[0] + " client_secret: " + tmp[1])
cid := tmp[0]
cse := tmp[1]
bot.Send(m.Chat, "授权账户: [点击直达]("+outlook.MSGetAuthUrl(cid)+")", tb.ModeMarkdown)
bot.Send(m.Chat, "授权账户: [点击直达]("+outlook.GetMSAuthUrl(cid)+")", tb.ModeMarkdown)
_, err := bot.Send(m.Chat, "请回复http://localhost/…… + 空格 + 别名(用于管理)", &tb.ReplyMarkup{ForceReply: true})
if err != nil {
logger.Println(err)
Expand All @@ -144,7 +144,7 @@ func bBind2(m *tb.Message) {

func bUnBind(m *tb.Message) {
logger.Println(strconv.FormatInt(m.Chat.ID, 10) + " Start Unbind")
data := db.QueryDataByTG(m.Chat.ID)
data := core.QueryDataByTG(m.Chat.ID)
var inlineKeys [][]tb.InlineButton
for _, u := range data {
inlineBtn := tb.InlineButton{
Expand All @@ -159,9 +159,9 @@ func bUnBind(m *tb.Message) {
}
func bUnBindInlineBtn(c *tb.Callback) {
logger.Println(strconv.FormatInt(c.Message.Chat.ID, 10) + " Unbind: " + c.Data)
r := db.QueryDataByMS(c.Data)
r := core.QueryDataByMS(c.Data)
u := r[0]
if ok, _ := db.DelData(u.MsId); !ok {
if ok, _ := core.DelData(u.MsId); !ok {
logger.Println(u.MsId + " UnBind ERROR")
bot.Send(c.Message.Chat, "解绑失败!")
return
Expand All @@ -180,7 +180,7 @@ func bExport(m *tb.Message) {
Other string
}
var MsMini []MsMiniData
data := db.QueryDataByTG(m.Chat.ID)
data := core.QueryDataByTG(m.Chat.ID)
if len(data) == 0 {
bot.Send(m.Chat, "你还没有绑定过账户嗷~")
return
Expand Down
12 changes: 12 additions & 0 deletions core/client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package core

type Client struct {
TgId int64 `gorm:"column:tg_id"`
RefreshToken string `gorm:"column:refresh_token"`
MsId string `gorm:"column:ms_id"`
Uptime int64 `gorm:"column:uptime"`
Alias string `gorm:"column:alias"`
ClientId string `gorm:"column:client_id"`
ClientSecret string `gorm:"column:client_secret"`
Other string `gorm:"column:other"`
}
57 changes: 32 additions & 25 deletions db/mysql.go → core/mysql.go
Original file line number Diff line number Diff line change
@@ -1,31 +1,38 @@
package db
package core

import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
"gorm.io/gorm"
"main/logger"
"main/outlook"
"main/util"
"time"
)

type MSData struct {
TgId int64
RefreshToken string
MsId string
Uptime int64
Alias string
ClientId string
ClientSecret string
Other string
var db *gorm.DB

func InitDB() error {
var err error
db, err = gorm.Open("11", &gorm.Config{
NowFunc: func() time.Time {
return time.Now().UTC()
},
})
if err != nil {
return err
}
return nil
}

//update data by msId
func UpdateData(u MSData) (bool, error) {
func UpdateData(u Client) (bool, error) {
db, err := sql.Open(dbDriverName, dbPath)
if err != nil {
logger.Println(err)
}
defer db.Close()
sqlString := `UPDATE users set tg_id=?,refresh_token=?,uptime=?,alias=?,client_id=?,client_secret=?,other=? where ms_id=?`
sqlString := `UPDATE Clients set tg_id=?,refresh_token=?,uptime=?,alias=?,client_id=?,client_secret=?,other=? where ms_id=?`
stmt, err := db.Prepare(sqlString)
if err != nil {
return false, err
Expand All @@ -38,14 +45,14 @@ func UpdateData(u MSData) (bool, error) {
}

//add data
func AddData(u MSData) (bool, error) {
func AddData(u Client) (bool, error) {
db, err := sql.Open(dbDriverName, dbPath)
if err != nil {
logger.Println(err)
}
defer db.Close()
sqlString := `
INSERT INTO users (tg_id, refresh_token,ms_id, uptime,alias,client_id,client_secret,other)
INSERT INTO Clients (tg_id, refresh_token,ms_id, uptime,alias,client_id,client_secret,other)
VALUES (?,?,?,?,?,?,?,?)`
stmt, err := db.Prepare(sqlString)
if err != nil {
Expand All @@ -65,7 +72,7 @@ func DelData(msId string) (bool, error) {
logger.Println(err)
}
defer db.Close()
sqlString := `delete from users where ms_id=?`
sqlString := `delete from Clients where ms_id=?`
stmt, err := db.Prepare(sqlString)
if err != nil {
return false, err
Expand All @@ -80,9 +87,9 @@ func DelData(msId string) (bool, error) {
}
return true, nil
}
func QueryData(rows *sql.Rows) []MSData {
func QueryData(rows *sql.Rows) []Client {

var result = make([]MSData, 0)
var result = make([]Client, 0)
defer rows.Close()
for rows.Next() {
var (
Expand All @@ -91,40 +98,40 @@ func QueryData(rows *sql.Rows) []MSData {
)
rows.Scan(&tgIdt, &refresht, &msidt, &uptimet, &aliast, &clientIdt, &clientSet, &othert)
//fmt.Println(string(tgNamet) + "=>" + uptimet.Format("2006-01-02 15:04:05"))
result = append(result, MSData{tgIdt, refresht, msidt, uptimet, aliast, clientIdt, clientSet, othert})
result = append(result, Client{tgIdt, refresht, msidt, uptimet, aliast, clientIdt, clientSet, othert})
}
return result
}
func QueryDataByMS(msId string) []MSData {
func QueryDataByMS(msId string) []Client {
db, err := sql.Open(dbDriverName, dbPath)
if err != nil {
logger.Println(err)
}
defer db.Close()
rows, err := db.Query("select * from users where ms_id = ?", msId)
rows, err := db.Query("select * from Clients where ms_id = ?", msId)
util.CheckErr(err)
return QueryData(rows)
}

func QueryDataAll() []MSData {
func QueryDataAll() []Client {
db, err := sql.Open(dbDriverName, dbPath)
if err != nil {
logger.Println(err)
}
defer db.Close()
rows, err := db.Query("select * from users ")
rows, err := db.Query("select * from Clients ")
util.CheckErr(err)
return QueryData(rows)
}

//query data by tg_id
func QueryDataByTG(tgId int64) []MSData {
func QueryDataByTG(tgId int64) []Client {
db, err := sql.Open(dbDriverName, dbPath)
if err != nil {
logger.Println(err)
}
defer db.Close()
rows, err := db.Query("select * from users where tg_id = ?", tgId)
rows, err := db.Query("select * from Clients where tg_id = ?", tgId)
util.CheckErr(err)
return QueryData(rows)
}
Expand All @@ -135,7 +142,7 @@ func CreateTB() (bool, error) {
}
defer db.Close()
sqltable := `
create table if not exists users
create table if not exists Clients
(
tg_id INTEGER,
refresh_token TEXT,
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,5 @@ require (
golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e
gopkg.in/natefinch/lumberjack.v2 v2.0.0
gopkg.in/tucnak/telebot.v2 v2.0.0-20200328014118-dd123e949ee1
gorm.io/gorm v1.21.3
)
Loading

0 comments on commit 90248dc

Please sign in to comment.