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

View File

@ -1,7 +1,6 @@
package model package model
import ( import (
"database/sql"
"errors" "errors"
"time" "time"
) )
@ -26,24 +25,17 @@ func GetGroupCommand(c, g string) (cmd *Commands, err error) {
if len(c) == 0 { if len(c) == 0 {
return nil, errors.New("command is empty") return nil, errors.New("command is empty")
} }
tmpCmd := struct { query := `select c.* from "public"."commands" c
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
where c."cmd" = $1 where c."cmd" = $1
and c."group" = ''` and (c."group" = '' or c."group" = $2)
err = x.Get(&tmpCmd, query, c, g) 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 { if err != nil {
return nil, err return nil, err
} }
cmd = &tmpCmd.Commands
if tmpCmd.Message2.Valid {
cmd.Message = tmpCmd.Message2.String
}
return return
} }

View File

@ -28,7 +28,8 @@ func GetAllFacebookPage() (pages []*FacebookPage, err error) {
// GetFacebookPage - // GetFacebookPage -
func GetFacebookPage(id string) (page *FacebookPage, err error) { 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 return
} }

View File

@ -1,7 +1,6 @@
package model package model
import ( import (
"database/sql"
"errors" "errors"
"time" "time"
) )
@ -20,24 +19,19 @@ func GetGroupKeyCommand(c, g string) (cmd *KeyCommands, err error) {
if len(c) == 0 { if len(c) == 0 {
return nil, errors.New("command is empty") return nil, errors.New("command is empty")
} }
tmpCmd := struct {
KeyCommands query := `select c.* from "public"."key_commands" c
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
where c."key" = $1 where c."key" = $1
and c."group" = ''` and (c."group" = '' or c."group" = $2)
err = x.Get(&tmpCmd, query, c, g) 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 { if err != nil {
return nil, err return nil, err
} }
cmd = &tmpCmd.KeyCommands
if tmpCmd.Message2.Valid {
cmd.Message = tmpCmd.Message2.String
}
return return
} }

View File

@ -40,13 +40,15 @@ func CheckGroupOwner(user, g string) (exists bool, err error) {
// GetLineGroup - // GetLineGroup -
func GetLineGroup(id string) (g *LineGroup, err error) { 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 return
} }
// AddLineGroup - // AddLineGroup -
func AddLineGroup(name, owner string, notify bool) (g *LineGroup, err error) { 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 { if err != nil {
return nil, err return nil, err
} }

View File

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

View File

@ -12,7 +12,8 @@ type LineUser struct {
// GetLineUserByID - // GetLineUserByID -
func GetLineUserByID(id string) (u *LineUser, err error) { 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 return
} }

View File

@ -40,7 +40,8 @@ func GetTwitchChannelWithName(name string) (ch *TwitchChannel, err error) {
if len(name) == 0 { if len(name) == 0 {
return nil, errors.New("name empty") 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 return
} }
@ -49,7 +50,8 @@ func GetTwitchChannelWithID(id string) (ch *TwitchChannel, err error) {
if len(id) == 0 { if len(id) == 0 {
return nil, errors.New("id empty") 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 return
} }

View File

@ -33,7 +33,8 @@ func GetYoutubeChannelsWithExpire(e int64) (yt []*YoutubeChannel, err error) {
// GetYoutubeChannelWithID - // GetYoutubeChannelWithID -
func GetYoutubeChannelWithID(id string) (yt *YoutubeChannel, err error) { 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 return
} }

View File

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

View File

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

View File

@ -241,7 +241,7 @@ type TwitchTokenData struct {
AccessToken string `json:"access_token" cc:"access_token"` AccessToken string `json:"access_token" cc:"access_token"`
RefreshToken string `json:"refresh_token" cc:"refresh_token"` RefreshToken string `json:"refresh_token" cc:"refresh_token"`
ExpiresIn int64 `json:"expires_in" cc:"expires_in"` 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"` 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("grant_type", "authorization_code")
qs.Add("redirect_uri", redirectTo) qs.Add("redirect_uri", redirectTo)
u, err := url.Parse(twitchURL) // u, err := url.Parse(twitchURL)
if err != nil { // if err != nil {
return nil, err // return nil, err
} // }
u, err = u.Parse(qs.Encode()) // u, err = u.Parse(qs.Encode())
if err != nil { // if err != nil {
return nil, err // return nil, err
} // }
reqObj := apis.RequestObj{ reqObj := apis.RequestObj{
URL: u.String(), URL: twitchURL + "?" + qs.Encode(),
Method: "POST", Method: "POST",
} }
req, err := apis.GetRequest(reqObj) req, err := apis.GetRequest(reqObj)
@ -285,15 +285,15 @@ func GetTokenData(code string) (token *TwitchTokenData, err error) {
} }
defer resp.Body.Close() 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) bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil { if err != nil {
return nil, err 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) err = json.Unmarshal(bodyBytes, &token)
return return

View File

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

View File

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

View File

@ -4,16 +4,16 @@ import (
"fmt" "fmt"
lineobj "git.trj.tw/golang/mtfosbot/module/line-message/line-object" lineobj "git.trj.tw/golang/mtfosbot/module/line-message/line-object"
"git.trj.tw/golang/mtfosbot/module/utils"
) )
// MessageEvent - // MessageEvent -
func MessageEvent(e *lineobj.EventObject) { func MessageEvent(e *lineobj.EventObject) {
fmt.Println(utils.ToMap(e))
switch e.Type { switch e.Type {
case "message": case "message":
messageType(e) messageType(e)
break 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 { if t, ok := mtype.(string); ok {
switch t { switch t {
case "text": case "text":
textMsg(e)
break break
case "image": case "image":
break break

View File

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

View File

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

View File

@ -172,6 +172,15 @@ func runQueue() {
func ircHandle(c *irc.Client, m *irc.Message) { func ircHandle(c *irc.Client, m *irc.Message) {
fmt.Println("> ", m.String()) 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 { func indexOf(c []string, data string) int {

View File

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

View File

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

View File

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

View File

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