From ce62048c18cf49b241d2ad0a86a906190b9f1f36 Mon Sep 17 00:00:00 2001 From: jay Date: Tue, 18 Sep 2018 00:35:48 +0800 Subject: [PATCH] add twitch apis , bar api not ok --- main.go | 17 +++ model/donate_setting.go | 37 ++++- model/twitch_channel.go | 18 ++- module/background/opay.go | 2 - module/background/twitch.go | 2 - router/api/twitch.go | 272 +++++++++++++++++++++++++++++++++++- router/routes/routes.go | 15 +- 7 files changed, 354 insertions(+), 9 deletions(-) diff --git a/main.go b/main.go index f4b4098..14922a6 100644 --- a/main.go +++ b/main.go @@ -1,6 +1,7 @@ package main import ( + "encoding/gob" "log" "strconv" "strings" @@ -21,6 +22,7 @@ func main() { log.Fatal(err) } + registerTypes() background.SetBackground() // create http server @@ -38,3 +40,18 @@ func main() { server.Run(strings.Join([]string{":", strconv.Itoa(config.GetConf().Port)}, "")) } + +func registerTypes() { + gob.Register(model.Account{}) + gob.Register(model.Commands{}) + gob.Register(model.DonateSetting{}) + gob.Register(model.FacebookPage{}) + gob.Register(model.KeyCommands{}) + gob.Register(model.LineGroup{}) + gob.Register(model.LineMessageLog{}) + gob.Register(model.LineUser{}) + gob.Register(model.OpayDonateList{}) + gob.Register(model.TwitchChannel{}) + gob.Register(model.YoutubeChannel{}) + gob.Register(map[string]interface{}{}) +} diff --git a/model/donate_setting.go b/model/donate_setting.go index 74a317e..bd90949 100644 --- a/model/donate_setting.go +++ b/model/donate_setting.go @@ -1,6 +1,7 @@ package model import ( + "database/sql" "time" ) @@ -10,8 +11,42 @@ type DonateSetting struct { StartDate time.Time `db:"start_date" cc:"start_date"` EndDate time.Time `db:"end_date" cc:"end_date"` TargetAmount int `db:"target_amount" cc:"target_amount"` + StartAmount int `db:"start_amount" cc:"start_amount"` Title string `db:"title" cc:"title"` Type string `db:"type" cc:"type"` Ctime time.Time `db:"ctime" cc:"ctime"` - Mtime time.Time `db:"mtime" cc:"ctime"` + Mtime time.Time `db:"mtime" cc:"mtime"` +} + +// GetDonateSettingByChannel - +func GetDonateSettingByChannel(id string) (ds *DonateSetting, err error) { + query := `select ds.* + from "public"."donate_setting" ds + left join "public"."twitch_channel" ch + on ch.id = ds.twitch + where + ch.id = $1` + row := x.QueryRowx(query, id) + ds = &DonateSetting{} + err = row.StructScan(ds) + if err == sql.ErrNoRows { + return nil, nil + } + return +} + +// InsertOrUpdate - +func (p *DonateSetting) InsertOrUpdate() (err error) { + query := `insert into "public"."donate_setting" + ("twitch", "start_date", "end_date", "target_amount", "title", "start_amount") values + (:twitch, now(), :end_date, :target_amount, :title, :start_amount) + on CONFLICT ("twitch") DO UPDATE + set + "start_date" = now(), + "end_date" = :end_date, + "target_amount" = :target_amount, + "title" = :title, + "start_amount" = :start_amount` + _, err = x.NamedExec(query, p) + return } diff --git a/model/twitch_channel.go b/model/twitch_channel.go index f446588..ec1894e 100644 --- a/model/twitch_channel.go +++ b/model/twitch_channel.go @@ -20,12 +20,12 @@ type TwitchChannel struct { OpayID string `db:"opayid" cc:"opayid"` Ctime time.Time `db:"ctime" cc:"ctime"` Mtime time.Time `db:"mtime" cc:"ctime"` - Groups []*TwitchGroup `db:"-"` + Groups []*TwitchGroup `db:"-" cc:"-"` } // GetAllTwitchChannel - func GetAllTwitchChannel() (channels []*TwitchChannel, err error) { - err = x.Select(&channels, `select * from "public"."twitch_channel"`) + err = x.Select(&channels, `select * from "public"."twitch_channel" order by "name" desc`) return } @@ -95,6 +95,20 @@ func (p *TwitchChannel) UpdateName(name string) (err error) { return } +// UpdateJoin - +func (p *TwitchChannel) UpdateJoin(join bool) (err error) { + p.Join = join + _, err = x.NamedExec(`update "public"."twitch_channel" set "join" = :join where "id" = :id`, p) + return +} + +// UpdateOpayID - +func (p *TwitchChannel) UpdateOpayID(id string) (err error) { + p.OpayID = id + _, err = x.NamedExec(`update "public"."twitch_channel" set "opayid" = :opayid where "id" = :id`, p) + return +} + // GetGroups - func (p *TwitchChannel) GetGroups() (err error) { query := `select g.*, rt.tmpl as tmpl from "public"."twitch_channel" tw diff --git a/module/background/opay.go b/module/background/opay.go index f31745a..e2b9dcc 100644 --- a/module/background/opay.go +++ b/module/background/opay.go @@ -78,8 +78,6 @@ func getOpayData(ch *model.TwitchChannel) { return } - fmt.Println(oResp.LstDonate) - if len(oResp.LstDonate) == 0 { return } diff --git a/module/background/twitch.go b/module/background/twitch.go index 60c5b12..86c2712 100644 --- a/module/background/twitch.go +++ b/module/background/twitch.go @@ -10,7 +10,6 @@ import ( ) func getStreamStatus() { - fmt.Println("run twitch check") channels, err := model.GetAllTwitchChannel() if err != nil { return @@ -21,7 +20,6 @@ func getStreamStatus() { } info := twitch.GetUserStreamStatus(ids) - fmt.Printf("info len: %d\n", len(info)) if len(info) == 0 { return } diff --git a/router/api/twitch.go b/router/api/twitch.go index 100e4af..e32606f 100644 --- a/router/api/twitch.go +++ b/router/api/twitch.go @@ -1,13 +1,283 @@ package api import ( + "fmt" + "time" + "git.trj.tw/golang/mtfosbot/model" + "git.trj.tw/golang/mtfosbot/module/context" + "git.trj.tw/golang/mtfosbot/module/twitch-irc" + "git.trj.tw/golang/mtfosbot/module/utils" + "github.com/gin-gonic/contrib/sessions" ) func sessionTypeTwitch(id string) (ch []*model.TwitchChannel, err error) { - return + chdata, err := model.GetTwitchChannelWithID(id) + if err != nil { + return + } + if chdata == nil { + return nil, nil + } + list := make([]*model.TwitchChannel, 1) + list = append(list, chdata) + return list, nil } func sessionTypeSystem() (ch []*model.TwitchChannel, err error) { + ch, err = model.GetAllTwitchChannel() return } + +// GetChannels - middleware +func GetChannels(c *context.Context) { + sess := sessions.Default(c.Context) + logingType := sess.Get("loginType") + if logingType == nil { + c.LoginFirst(nil) + return + } + + ltype, ok := logingType.(string) + if !ok { + c.LoginFirst(nil) + return + } + if ltype == "twitch" { + u := sess.Get("user") + if u == nil { + c.LoginFirst(nil) + return + } + user, ok := u.(model.TwitchChannel) + if !ok { + c.LoginFirst(nil) + return + } + chs, err := sessionTypeTwitch(user.ID) + if err != nil || chs == nil { + c.ServerError(nil) + return + } + c.Set("channels", chs) + } else if ltype == "system" { + u := sess.Get("user") + if u == nil { + c.LoginFirst(nil) + return + } + _, ok := u.(model.Account) + if !ok { + c.LoginFirst(nil) + return + } + chs, err := sessionTypeSystem() + if err != nil || chs == nil { + c.LoginFirst(nil) + return + } + c.Set("channels", chs) + } else { + c.LoginFirst(nil) + return + } + + c.Next() +} + +func hasChannel(id string, c *context.Context) *model.TwitchChannel { + if len(id) == 0 { + return nil + } + + channels, exists := c.Get("channels") + if !exists { + return nil + } + chs, ok := channels.([]*model.TwitchChannel) + if !ok { + return nil + } + + for _, v := range chs { + if v.ID == id { + return v + } + } + + return nil +} + +// GetChannelList - +func GetChannelList(c *context.Context) { + channels, exists := c.Get("channels") + if !exists { + c.ServerError(nil) + return + } + list, ok := channels.([]*model.TwitchChannel) + if !ok { + c.ServerError(nil) + return + } + + mapList := make([]map[string]interface{}, len(list)) + for k, v := range list { + mapList[k] = utils.ToMap(v) + } + + c.Success(map[string]interface{}{ + "list": mapList, + }) +} + +// GetChannelData - +func GetChannelData(c *context.Context) { + chid := c.Param("chid") + chdata := hasChannel(chid, c) + if chdata == nil { + c.NotFound(nil) + return + } + + c.Success(map[string]interface{}{ + "channel": utils.ToMap(chdata), + }) +} + +// BotJoinChannel - +func BotJoinChannel(c *context.Context) { + chid := c.Param("chid") + chdata := hasChannel(chid, c) + if chdata == nil { + c.NotFound(nil) + return + } + + bodyArg := struct { + Join int `json:"join"` + }{} + err := c.BindData(&bodyArg) + if err != nil { + c.DataFormat(nil) + return + } + + if bodyArg.Join != 0 && bodyArg.Join != 1 { + c.DataFormat(nil) + return + } + + err = chdata.UpdateJoin(bodyArg.Join == 1) + if err != nil { + c.ServerError(nil) + return + } + + if bodyArg.Join == 1 { + twitchirc.JoinChannel(chdata.Name) + } else { + twitchirc.LeaveChannel(chdata.Name) + } + + c.Success(nil) +} + +// OpayIDChange - +func OpayIDChange(c *context.Context) { + chid := c.Param("chid") + chdata := hasChannel(chid, c) + if chdata == nil { + c.NotFound(nil) + return + } + + bodyArg := struct { + Opay string `json:"opay" binding:"required"` + }{} + err := c.BindData(&bodyArg) + if err != nil { + c.DataFormat(nil) + return + } + + err = chdata.UpdateOpayID(bodyArg.Opay) + if err != nil { + c.ServerError(nil) + return + } + + c.Success(nil) +} + +// GetDonateSetting - +func GetDonateSetting(c *context.Context) { + chid := c.Param("chid") + chdata := hasChannel(chid, c) + if chdata == nil { + c.NotFound(nil) + return + } + + ds, err := model.GetDonateSettingByChannel(chdata.ID) + if err != nil { + fmt.Println(ds, err) + c.ServerError(nil) + return + } + + var mapData map[string]interface{} + if ds != nil { + mapData = utils.ToMap(ds) + } else { + mapData = map[string]interface{}{} + } + + c.Success(map[string]interface{}{ + "setting": mapData, + }) +} + +// UpdateDonateSetting - +func UpdateDonateSetting(c *context.Context) { + chid := c.Param("chid") + chdata := hasChannel(chid, c) + if chdata == nil { + c.NotFound(nil) + return + } + + bodyArg := struct { + End int64 `json:"end" binding:"exists"` + Title string `json:"title" binding:"required"` + Amount int `json:"amount" binding:"exists"` + StartAmount int `json:"start_amount"` + }{} + err := c.BindData(&bodyArg) + if err != nil { + c.DataFormat(nil) + return + } + + if bodyArg.End > 10000000000-1 { + bodyArg.End = bodyArg.End / 1000 + } + + t := time.Unix(bodyArg.End, 0) + + ds := &model.DonateSetting{ + Title: bodyArg.Title, + EndDate: t, + StartDate: time.Now(), + StartAmount: bodyArg.StartAmount, + TargetAmount: bodyArg.Amount, + Twitch: chdata.ID, + } + err = ds.InsertOrUpdate() + if err != nil { + c.ServerError(nil) + return + } + + c.Success(nil) +} diff --git a/router/routes/routes.go b/router/routes/routes.go index 04ba3cc..61a918e 100644 --- a/router/routes/routes.go +++ b/router/routes/routes.go @@ -17,7 +17,7 @@ import ( func NewServ() *gin.Engine { r := gin.New() - store, err := sessions.NewRedisStore(10, "tcp", "localhost:6379", "") + store, err := sessions.NewRedisStore(10, "tcp", "localhost:6379", "", []byte("seckey")) if err != nil { log.Fatal(err) } @@ -47,6 +47,19 @@ func SetRoutes(r *gin.Engine) { apiGroup.POST("/login", context.PatchCtx(api.UserLogin)) apiGroup.POST("/logout", context.PatchCtx(api.UserLogout)) } + apiTwitchGroup := apiGroup.Group("/twitch", context.PatchCtx(api.CheckSession)) + { + apiTwitchGroup.GET("/channels", context.PatchCtx(api.GetChannels), context.PatchCtx(api.GetChannelList)) + twitchChannelGroup := apiTwitchGroup.Group("/channel/:chid", context.PatchCtx(api.GetChannels)) + { + twitchChannelGroup.GET("/", context.PatchCtx(api.GetChannelData)) + twitchChannelGroup.PUT("/botjoin", context.PatchCtx(api.BotJoinChannel)) + twitchChannelGroup.PUT("/opay", context.PatchCtx(api.OpayIDChange)) + twitchChannelGroup.GET("/opay/setting", context.PatchCtx(api.GetDonateSetting)) + twitchChannelGroup.PUT("/opay/setting", context.PatchCtx(api.UpdateDonateSetting)) + } + + } lineApis := r.Group("/line") {