fix all error and bug !!!!!!!!!!!!!

This commit is contained in:
Jay 2018-09-21 01:14:08 +08:00
parent 07436cd8df
commit 906b7be381
24 changed files with 133 additions and 109 deletions

View File

@ -10,6 +10,7 @@ import (
"strconv"
"strings"
"git.trj.tw/golang/mtfosbot/module/apis/twitch"
"git.trj.tw/golang/mtfosbot/module/cmd"
"git.trj.tw/golang/mtfosbot/module/options"
"git.trj.tw/golang/mtfosbot/module/utils"
@ -89,5 +90,7 @@ func registerTypes() {
gob.Register(model.OpayDonateList{})
gob.Register(model.TwitchChannel{})
gob.Register(model.YoutubeChannel{})
gob.Register(twitch.TwitchTokenData{})
gob.Register(twitch.UserInfo{})
gob.Register(map[string]interface{}{})
}

View File

@ -1,7 +1,6 @@
package model
import (
"database/sql"
"errors"
"time"
)
@ -26,24 +25,17 @@ func GetGroupCommand(c, g string) (cmd *Commands, err error) {
if len(c) == 0 {
return nil, errors.New("command is empty")
}
tmpCmd := struct {
Commands
Message2 sql.NullString `db:"message2"`
}{}
query := `select c.*, c2.message as message2 from "public"."commands" c
left join "public"."commands" c2
on c2.cmd = c.cmd and c2."group" = $2
query := `select c.* from "public"."commands" c
where c."cmd" = $1
and c."group" = ''`
err = x.Get(&tmpCmd, query, c, g)
and (c."group" = '' or c."group" = $2)
order by c."group" desc
limit 1`
row := x.QueryRowx(query, c, g)
// err = x.Get(&cmd, query, c, g)
cmd = &Commands{}
err = row.StructScan(cmd)
if err != nil {
return nil, err
}
cmd = &tmpCmd.Commands
if tmpCmd.Message2.Valid {
cmd.Message = tmpCmd.Message2.String
}
return
}

View File

@ -28,7 +28,8 @@ func GetAllFacebookPage() (pages []*FacebookPage, err error) {
// GetFacebookPage -
func GetFacebookPage(id string) (page *FacebookPage, err error) {
err = x.Get(&page, `select * from "public"."facebook_page" where "id" = $1`, id)
page = &FacebookPage{}
err = x.Get(page, `select * from "public"."facebook_page" where "id" = $1`, id)
return
}

View File

@ -1,7 +1,6 @@
package model
import (
"database/sql"
"errors"
"time"
)
@ -20,24 +19,19 @@ func GetGroupKeyCommand(c, g string) (cmd *KeyCommands, err error) {
if len(c) == 0 {
return nil, errors.New("command is empty")
}
tmpCmd := struct {
KeyCommands
Message2 sql.NullString `db:"message2"`
}{}
query := `select c.*, c2.message as message2 from "public"."key_commands" c
left join "public"."key_commands" c2
on c2.key = c.key and c2."group" = $2
query := `select c.* from "public"."key_commands" c
where c."key" = $1
and c."group" = ''`
err = x.Get(&tmpCmd, query, c, g)
and (c."group" = '' or c."group" = $2)
order by c."group" desc
limit 1`
row := x.QueryRowx(query, c, g)
// err = x.Get(&cmd, query, c, g)
cmd = &KeyCommands{}
err = row.StructScan(cmd)
if err != nil {
return nil, err
}
cmd = &tmpCmd.KeyCommands
if tmpCmd.Message2.Valid {
cmd.Message = tmpCmd.Message2.String
}
return
}

View File

@ -40,13 +40,15 @@ func CheckGroupOwner(user, g string) (exists bool, err error) {
// GetLineGroup -
func GetLineGroup(id string) (g *LineGroup, err error) {
err = x.Get(&g, `select * from "public"."line_group" where "id" = $1`, id)
g = &LineGroup{}
err = x.Get(g, `select * from "public"."line_group" where "id" = $1`, id)
return
}
// AddLineGroup -
func AddLineGroup(name, owner string, notify bool) (g *LineGroup, err error) {
err = x.Get(&g, `insert into "public"."line_group" ("name", "owner", "notify") values ($1, $2, $3)`, name, owner, notify)
g = &LineGroup{}
err = x.Get(g, `insert into "public"."line_group" ("name", "owner", "notify") values ($1, $2, $3)`, name, owner, notify)
if err != nil {
return nil, err
}

View File

@ -15,6 +15,7 @@ type LineMessageLog struct {
// AddLineMessageLog -
func AddLineMessageLog(g, u, msg string) (msglog *LineMessageLog, err error) {
query := `insert into "public"."line_message_log" ("group", "user", "message") values ($1, $2, $3)`
err = x.Get(&msglog, query, g, u, msg)
msglog = &LineMessageLog{}
err = x.Get(msglog, query, g, u, msg)
return
}

View File

@ -12,7 +12,8 @@ type LineUser struct {
// GetLineUserByID -
func GetLineUserByID(id string) (u *LineUser, err error) {
err = x.Get(&u, `select * from "public"."line_user" where "id" = $1`, id)
u = &LineUser{}
err = x.Get(u, `select * from "public"."line_user" where "id" = $1`, id)
return
}

View File

@ -40,7 +40,8 @@ func GetTwitchChannelWithName(name string) (ch *TwitchChannel, err error) {
if len(name) == 0 {
return nil, errors.New("name empty")
}
err = x.Get(&ch, `select * from "public"."twitch_channel" where "name" = $1`, name)
ch = &TwitchChannel{}
err = x.Get(ch, `select * from "public"."twitch_channel" where "name" = $1`, name)
return
}
@ -49,7 +50,8 @@ func GetTwitchChannelWithID(id string) (ch *TwitchChannel, err error) {
if len(id) == 0 {
return nil, errors.New("id empty")
}
err = x.Get(&ch, `select * from "public"."twitch_channel" where "id" = $1`, id)
ch = &TwitchChannel{}
err = x.Get(ch, `select * from "public"."twitch_channel" where "id" = $1`, id)
return
}

View File

@ -33,7 +33,8 @@ func GetYoutubeChannelsWithExpire(e int64) (yt []*YoutubeChannel, err error) {
// GetYoutubeChannelWithID -
func GetYoutubeChannelWithID(id string) (yt *YoutubeChannel, err error) {
err = x.Get(&yt, `select * from "public"."youtube_channel" where "id" = $1`, id)
yt = &YoutubeChannel{}
err = x.Get(yt, `select * from "public"."youtube_channel" where "id" = $1`, id)
return
}

View File

@ -63,6 +63,9 @@ func GetRes(name string, msg interface{}) *ResObject {
case map[string]interface{}:
resobj.Obj = msg
break
case map[string]string:
resobj.Obj = msg
break
default:
resobj.Obj = obj.Obj
}

View File

@ -93,7 +93,6 @@ func PushMessage(target string, message interface{}) {
body.Messages = append(body.Messages, message)
dataByte, err := json.Marshal(body)
if err != nil {
fmt.Println("json encoding error")
return
}
@ -101,7 +100,6 @@ func PushMessage(target string, message interface{}) {
apiURL, ok := getURL(urlPath)
if !ok {
fmt.Println("url parser fail")
return
}
@ -119,7 +117,6 @@ func PushMessage(target string, message interface{}) {
_, err = http.DefaultClient.Do(req)
if err != nil {
fmt.Println("post api fail")
return
}
}
@ -136,24 +133,24 @@ func ReplyMessage(replyToken string, message interface{}) {
}
switch message.(type) {
case ImageMessage:
m := (message.(ImageMessage))
case *ImageMessage:
m := (message.(*ImageMessage))
m.Type = "image"
message = m
break
case TextMessage:
m := (message.(TextMessage))
case *TextMessage:
m := (message.(*TextMessage))
m.Type = "text"
message = m
break
default:
fmt.Println("input type error")
return
}
body.Messages = append(body.Messages, message)
dataByte, err := json.Marshal(body)
if err != nil {
fmt.Println("json encoding error")
return
}
@ -161,7 +158,6 @@ func ReplyMessage(replyToken string, message interface{}) {
apiURL, ok := getURL(urlPath)
if !ok {
fmt.Println("url parser fail")
return
}
@ -179,7 +175,6 @@ func ReplyMessage(replyToken string, message interface{}) {
_, err = http.DefaultClient.Do(req)
if err != nil {
fmt.Println("post api fail")
return
}
}

View File

@ -241,7 +241,7 @@ type TwitchTokenData struct {
AccessToken string `json:"access_token" cc:"access_token"`
RefreshToken string `json:"refresh_token" cc:"refresh_token"`
ExpiresIn int64 `json:"expires_in" cc:"expires_in"`
Scope string `json:"scope" cc:"scope"`
Scope []string `json:"scope" cc:"scope"`
TokenType string `json:"token_type" cc:"token_type"`
}
@ -261,17 +261,17 @@ func GetTokenData(code string) (token *TwitchTokenData, err error) {
qs.Add("grant_type", "authorization_code")
qs.Add("redirect_uri", redirectTo)
u, err := url.Parse(twitchURL)
if err != nil {
return nil, err
}
u, err = u.Parse(qs.Encode())
if err != nil {
return nil, err
}
// u, err := url.Parse(twitchURL)
// if err != nil {
// return nil, err
// }
// u, err = u.Parse(qs.Encode())
// if err != nil {
// return nil, err
// }
reqObj := apis.RequestObj{
URL: u.String(),
URL: twitchURL + "?" + qs.Encode(),
Method: "POST",
}
req, err := apis.GetRequest(reqObj)
@ -285,15 +285,15 @@ func GetTokenData(code string) (token *TwitchTokenData, err error) {
}
defer resp.Body.Close()
if resp.StatusCode != 200 || strings.HasPrefix(resp.Header.Get("Content-Type"), "application/json") {
return nil, errors.New("api response error")
}
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode != 200 || !strings.HasPrefix(resp.Header.Get("Content-Type"), "application/json") {
return nil, errors.New("api response error")
}
err = json.Unmarshal(bodyBytes, &token)
return

View File

@ -43,7 +43,6 @@ func readFacebookPage() {
}
for _, v := range pages {
fmt.Println("get facebook page ::: ", v.ID)
go getPageHTML(v)
}
}
@ -51,8 +50,6 @@ func readFacebookPage() {
func getPageHTML(page *model.FacebookPage) {
err := page.GetGroups()
if err != nil {
fmt.Println(err)
fmt.Println("get group fail")
return
}
@ -71,12 +68,10 @@ func getPageHTML(page *model.FacebookPage) {
timeEl := s.Find("abbr")
time, timeExists := timeEl.Attr("data-utime")
if !timeExists {
fmt.Println("time not found")
return
}
link, linkExists := timeEl.Parent().Attr("href")
if !linkExists {
fmt.Println("link not found")
return
}
postContent := s.Find("div.userContent")
@ -93,16 +88,14 @@ func getPageHTML(page *model.FacebookPage) {
}
}
if !idFlag {
fmt.Println("id not found")
return
}
}
fmt.Printf("Time: %s / Text: %s / ID: %s \n", time, text, postID)
// fmt.Printf("Time: %s / Text: %s / ID: %s \n", time, text, postID)
timeInt, err := strconv.ParseInt(time, 10, 32)
if err != nil {
fmt.Println("convert time to int error")
return
}
@ -120,7 +113,6 @@ func getPageHTML(page *model.FacebookPage) {
})
if len(pageData) == 0 {
fmt.Println("no data found")
return
}

View File

@ -4,7 +4,7 @@ package lineobj
type EventObject struct {
Source *SourceObject `json:"source" cc:"source"`
Type string `json:"type" cc:"type"`
Timestamp int32 `json:"timestamp" cc:"timestamp"`
Timestamp int64 `json:"timestamp" cc:"timestamp"`
ReplyToken string `json:"replyToken" cc:"replyToken"`
Message map[string]interface{} `json:"message" cc:"message"`
}

View File

@ -4,16 +4,16 @@ import (
"fmt"
lineobj "git.trj.tw/golang/mtfosbot/module/line-message/line-object"
"git.trj.tw/golang/mtfosbot/module/utils"
)
// MessageEvent -
func MessageEvent(e *lineobj.EventObject) {
fmt.Println(utils.ToMap(e))
switch e.Type {
case "message":
messageType(e)
break
default:
fmt.Println("line webhook type not match")
}
}

View File

@ -17,6 +17,7 @@ func messageType(e *lineobj.EventObject) {
if t, ok := mtype.(string); ok {
switch t {
case "text":
textMsg(e)
break
case "image":
break

View File

@ -1,6 +1,7 @@
package msgcmd
import (
"fmt"
"strconv"
"strings"
@ -23,6 +24,10 @@ func selectAct(cmd, sub, txt string, s *lineobj.SourceObject) (res string) {
return delFacebookPage(sub, txt, s)
case "deltwitch":
return delTwitchChannel(sub, txt, s)
case "image":
return fmt.Sprintf("$image$%s", sub)
case "hello":
return "World!!"
}
return
}
@ -181,7 +186,7 @@ func addTwitchChannel(sub, txt string, s *lineobj.SourceObject) (res string) {
if ch == nil {
ch = &model.TwitchChannel{
ID: info.ID,
Name: info.DisplayName,
Name: info.Login,
}
err = ch.Add()
if err != nil {

View File

@ -1,9 +1,12 @@
package msgcmd
import (
"fmt"
"regexp"
"strings"
"git.trj.tw/golang/mtfosbot/module/utils"
"git.trj.tw/golang/mtfosbot/model"
"git.trj.tw/golang/mtfosbot/module/apis/line"
@ -23,10 +26,12 @@ func parseCMD(in string) (c [][]string) {
// ParseLineMsg -
func ParseLineMsg(txt, replyToken string, source *lineobj.SourceObject) {
fmt.Println("parse Line msg ;::: ", txt, utils.ToMap(source))
if source.Type != "group" {
return
}
strs := strings.Split(strings.Trim(txt, " "), " ")
fmt.Println(strs)
// skip empty string
if len(strs[0]) == 0 {
return
@ -35,27 +40,36 @@ func ParseLineMsg(txt, replyToken string, source *lineobj.SourceObject) {
if strings.HasPrefix(strs[0], "!") || strings.HasPrefix(strs[0], "") {
// nor cmd
cmd := strs[0][1:]
fmt.Println(cmd)
if len(cmd) == 0 {
return
}
c, err := model.GetGroupCommand(cmd, source.GroupID)
c, err := model.GetGroupCommand(strings.ToLower(cmd), source.GroupID)
if err != nil || c == nil {
fmt.Println("get command fail ", err)
return
}
fmt.Println("get command ::::", utils.ToMap(c))
str := runCMD(strings.Join(strs[1:], " "), c.Message, source)
fmt.Println("cmd result ::::::", str)
m := parseResult(str)
fmt.Println("parsed cmd result :::::", m)
line.ReplyMessage(replyToken, m)
} else {
// key cmd
c, err := model.GetGroupKeyCommand(strs[0], source.GroupID)
c, err := model.GetGroupKeyCommand(strings.ToLower(strs[0]), source.GroupID)
if err != nil || c == nil {
fmt.Println("get command fail::::", err)
return
}
fmt.Println("get command ::::", utils.ToMap(c))
str := runCMD(strings.Join(strs[1:], " "), c.Message, source)
fmt.Println("cmd result ::::", str)
m := parseResult(str)
fmt.Println("parsed cmd result :::::", m)
line.ReplyMessage(replyToken, m)
}
@ -81,6 +95,7 @@ func parseResult(str string) interface{} {
}
func runCMD(txt, c string, s *lineobj.SourceObject) (res string) {
fmt.Println("run run run::::::", txt, c, s)
cmdAct := parseCMD(c)
if len(cmdAct) == 0 {
return c
@ -94,8 +109,9 @@ func runCMD(txt, c string, s *lineobj.SourceObject) (res string) {
if len(m) > 1 {
sub = strings.Join(m[1:], " ")
}
fmt.Println("run ::::::::", m[0], sub, txt)
cmdRes := selectAct(m[0], sub, txt, s)
res = strings.Replace(res, v[1], cmdRes, 1)
res = strings.Replace(res, v[0], cmdRes, 1)
}
}
return

View File

@ -172,6 +172,15 @@ func runQueue() {
func ircHandle(c *irc.Client, m *irc.Message) {
fmt.Println("> ", m.String())
if m.Command == "PING" {
tmp := &irc.Message{
Command: "PONG",
Params: []string{
m.Params[0],
},
}
client.WriteMessage(tmp)
}
}
func indexOf(c []string, data string) int {

View File

@ -24,7 +24,7 @@ func CheckSession(c *context.Context) {
case model.Account:
name = userData.(model.Account).Account
case twitch.UserInfo:
name = userData.(twitch.UserInfo).DisplayName
name = userData.(twitch.UserInfo).Login
default:
c.LoginFirst(nil)
return
@ -85,3 +85,18 @@ func UserLogout(c *context.Context) {
c.Success(nil)
}
// GetSessionData -
func GetSessionData(c *context.Context) {
session := sessions.Default(c.Context)
loginUser := session.Get("loginUser")
if loginUser == nil {
c.LoginFirst(nil)
return
}
user := map[string]interface{}{
"user": loginUser,
}
c.Success(user)
}

View File

@ -1,10 +1,10 @@
package api
import (
"fmt"
"time"
"git.trj.tw/golang/mtfosbot/model"
"git.trj.tw/golang/mtfosbot/module/apis/twitch"
"git.trj.tw/golang/mtfosbot/module/context"
"git.trj.tw/golang/mtfosbot/module/twitch-irc"
"git.trj.tw/golang/mtfosbot/module/utils"
@ -49,7 +49,7 @@ func GetChannels(c *context.Context) {
c.LoginFirst(nil)
return
}
user, ok := u.(model.TwitchChannel)
user, ok := u.(twitch.UserInfo)
if !ok {
c.LoginFirst(nil)
return
@ -121,9 +121,12 @@ func GetChannelList(c *context.Context) {
return
}
mapList := make([]map[string]interface{}, len(list))
for k, v := range list {
mapList[k] = utils.ToMap(v)
mapList := make([]map[string]interface{}, 0)
for _, v := range list {
if v == nil {
continue
}
mapList = append(mapList, utils.ToMap(v))
}
c.Success(map[string]interface{}{
@ -221,7 +224,6 @@ func GetDonateSetting(c *context.Context) {
ds, err := model.GetDonateSettingByChannel(chdata.ID)
if err != nil {
fmt.Println(ds, err)
c.ServerError(nil)
return
}
@ -251,7 +253,7 @@ func UpdateDonateSetting(c *context.Context) {
End int64 `json:"end" binding:"exists"`
Title string `json:"title" binding:"required"`
Amount int `json:"amount" binding:"exists"`
StartAmount int `json:"start_amount"`
StartAmount int `json:"start_amount" binding:"exists"`
}{}
err := c.BindData(&bodyArg)
if err != nil {

View File

@ -5,7 +5,6 @@ import (
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"git.trj.tw/golang/mtfosbot/module/config"
@ -78,7 +77,6 @@ func GetLineMessage(c *context.Context) {
err := json.Unmarshal(raw, &events)
if err != nil {
fmt.Println("parse line message error ::: ", err)
c.ServerError(nil)
return
}

View File

@ -44,7 +44,6 @@ func NewServ() *gin.Engine {
// SetRoutes - set routes
func SetRoutes(r *gin.Engine) {
r.GET("/", func(c *gin.Context) {
fmt.Println("in next")
c.JSON(200, gin.H{
"message": "ok",
})
@ -60,6 +59,7 @@ func SetRoutes(r *gin.Engine) {
{
apiGroup.POST("/login", context.PatchCtx(api.UserLogin))
apiGroup.POST("/logout", context.PatchCtx(api.UserLogout))
apiGroup.GET("/session", context.PatchCtx(api.CheckSession), context.PatchCtx(api.GetSessionData))
apiGroup.GET("/twitch/channel/:chid/opay/bar", context.PatchCtx(api.GetDonateBarStatus))
}
apiTwitchGroup := apiGroup.Group("/twitch", context.PatchCtx(api.CheckSession))

View File

@ -14,6 +14,7 @@ import (
// OAuthLogin -
func OAuthLogin(c *context.Context) {
session := sessions.Default(c.Context)
twOauth := `https://id.twitch.tv/oauth2/authorize`
conf := config.GetConf()
redirectTo := strings.TrimRight(conf.URL, "/")
redirectTo += "/twitch/oauth"
@ -29,17 +30,7 @@ func OAuthLogin(c *context.Context) {
session.Save()
}
u, err := url.Parse(redirectTo)
if err != nil {
c.ServerError(nil)
return
}
finalURL, err := u.Parse(qs.Encode())
if err != nil {
c.ServerError(nil)
return
}
c.Redirect(301, finalURL.String())
c.Redirect(302, twOauth+"?"+qs.Encode())
}
// OAuthProc -
@ -52,7 +43,7 @@ func OAuthProc(c *context.Context) {
tokenData, err := twitchapi.GetTokenData(code)
if err != nil {
c.DataFormat(nil)
c.DataFormat("token get fail")
return
}
@ -76,7 +67,7 @@ func OAuthProc(c *context.Context) {
if chData == nil {
chData = &model.TwitchChannel{
ID: userData.ID,
Name: userData.DisplayName,
Name: userData.Login,
}
err = chData.Add()
if err != nil {
@ -84,8 +75,8 @@ func OAuthProc(c *context.Context) {
return
}
} else {
if userData.DisplayName != chData.Name {
chData.UpdateName(userData.DisplayName)
if userData.Login != chData.Name {
chData.UpdateName(userData.Login)
}
}