E5BotForSQLite/bots/control.go

74 lines
1.8 KiB
Go
Raw Permalink Normal View History

2021-03-11 12:57:30 +08:00
package bots
2020-03-27 22:01:19 +08:00
import (
2020-04-08 13:42:10 +08:00
"errors"
2020-03-27 22:01:19 +08:00
"fmt"
2021-06-14 21:40:03 +08:00
"github.com/iyear/E5SubBot/model"
2021-06-14 13:07:08 +08:00
"github.com/iyear/E5SubBot/util"
2020-03-27 22:01:19 +08:00
"github.com/tidwall/gjson"
tb "gopkg.in/tucnak/telebot.v2"
2020-03-28 10:22:07 +08:00
"strings"
2020-03-27 22:01:19 +08:00
)
2021-06-14 13:07:08 +08:00
// BindUser If Successfully return "",else return error information
2021-06-14 21:40:03 +08:00
func BindUser(m *tb.Message, ClientId, ClientSecret string) error {
2020-03-28 10:22:07 +08:00
tmp := strings.Split(m.Text, " ")
if len(tmp) != 2 {
2021-06-14 13:07:08 +08:00
return errors.New("wrong format")
2020-03-28 10:22:07 +08:00
}
2021-03-11 12:57:30 +08:00
code := util.GetURLValue(tmp[0], "code")
2021-06-14 21:40:03 +08:00
Alias := tmp[1]
cli := model.NewClient(ClientId, ClientSecret)
if err := cli.GetTokenWithCode(code); err != nil {
2020-04-08 13:42:10 +08:00
return err
2020-03-27 22:01:19 +08:00
}
bot.Send(m.Chat, "Token获取成功!")
2021-06-14 21:40:03 +08:00
info, err := cli.GetUserInfo()
2020-04-08 13:42:10 +08:00
if err != nil {
return err
2020-03-27 22:01:19 +08:00
}
2021-06-14 21:40:03 +08:00
var u = &model.Client{
2021-06-15 18:44:51 +08:00
TgId: m.Chat.ID,
2021-06-14 21:40:03 +08:00
RefreshToken: cli.RefreshToken,
MsId: util.Get16MD5Encode(gjson.Get(info, "id").String()),
Alias: Alias,
ClientId: ClientId,
ClientSecret: ClientSecret,
Other: "",
}
2020-03-27 23:01:17 +08:00
//MS User Is Exist
2021-03-11 12:57:30 +08:00
if MSAppIsExist(u.TgId, u.ClientId) {
2020-04-08 13:42:10 +08:00
return errors.New("该应用已经绑定过了,无需重复绑定")
2020-03-27 23:01:17 +08:00
}
//MS information has gotten
2021-06-14 21:40:03 +08:00
bot.Send(m.Chat,
2021-06-15 19:04:26 +08:00
fmt.Sprintf("ms_id(MD5)%s\nuserPrincipalName%s\ndisplayName%s",
2021-06-14 21:40:03 +08:00
u.MsId,
gjson.Get(info, "userPrincipalName").String(),
2021-06-15 19:04:26 +08:00
gjson.Get(info, "displayName").String(),
),
2021-06-14 21:40:03 +08:00
)
if result := model.DB.Create(&u); result.Error != nil {
return result.Error
2020-03-27 23:01:17 +08:00
}
2020-04-08 13:42:10 +08:00
return nil
2020-03-27 23:01:17 +08:00
}
2020-03-28 15:21:59 +08:00
2021-06-14 13:07:08 +08:00
// GetBindNum get bind num
2021-03-11 12:57:30 +08:00
func GetBindNum(TgId int64) int {
2021-06-14 21:40:03 +08:00
var bindings []*model.Client
result := model.DB.Where("tg_id = ?", TgId).Find(&bindings)
return int(result.RowsAffected)
2020-03-27 23:01:17 +08:00
}
2021-06-14 13:07:08 +08:00
// MSAppIsExist return true => exist
2021-03-11 12:57:30 +08:00
func MSAppIsExist(TgId int64, ClientId string) bool {
2021-06-14 21:40:03 +08:00
result := model.DB.
Where("tg_id = ? AND client_id = ?", TgId, ClientId).
First(&model.Client{})
return util.IF(result.RowsAffected == 0, false, true).(bool)
2020-03-27 22:01:19 +08:00
}