add twitch apis , bar api not ok

This commit is contained in:
Jay 2018-09-18 00:35:48 +08:00
parent 67eeab4ba1
commit ce62048c18
7 changed files with 354 additions and 9 deletions

17
main.go
View File

@ -1,6 +1,7 @@
package main package main
import ( import (
"encoding/gob"
"log" "log"
"strconv" "strconv"
"strings" "strings"
@ -21,6 +22,7 @@ func main() {
log.Fatal(err) log.Fatal(err)
} }
registerTypes()
background.SetBackground() background.SetBackground()
// create http server // create http server
@ -38,3 +40,18 @@ func main() {
server.Run(strings.Join([]string{":", strconv.Itoa(config.GetConf().Port)}, "")) 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{}{})
}

View File

@ -1,6 +1,7 @@
package model package model
import ( import (
"database/sql"
"time" "time"
) )
@ -10,8 +11,42 @@ type DonateSetting struct {
StartDate time.Time `db:"start_date" cc:"start_date"` StartDate time.Time `db:"start_date" cc:"start_date"`
EndDate time.Time `db:"end_date" cc:"end_date"` EndDate time.Time `db:"end_date" cc:"end_date"`
TargetAmount int `db:"target_amount" cc:"target_amount"` TargetAmount int `db:"target_amount" cc:"target_amount"`
StartAmount int `db:"start_amount" cc:"start_amount"`
Title string `db:"title" cc:"title"` Title string `db:"title" cc:"title"`
Type string `db:"type" cc:"type"` Type string `db:"type" cc:"type"`
Ctime time.Time `db:"ctime" cc:"ctime"` 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
} }

View File

@ -20,12 +20,12 @@ type TwitchChannel struct {
OpayID string `db:"opayid" cc:"opayid"` OpayID string `db:"opayid" cc:"opayid"`
Ctime time.Time `db:"ctime" cc:"ctime"` Ctime time.Time `db:"ctime" cc:"ctime"`
Mtime time.Time `db:"mtime" cc:"ctime"` Mtime time.Time `db:"mtime" cc:"ctime"`
Groups []*TwitchGroup `db:"-"` Groups []*TwitchGroup `db:"-" cc:"-"`
} }
// GetAllTwitchChannel - // GetAllTwitchChannel -
func GetAllTwitchChannel() (channels []*TwitchChannel, err error) { 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 return
} }
@ -95,6 +95,20 @@ func (p *TwitchChannel) UpdateName(name string) (err error) {
return 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 - // GetGroups -
func (p *TwitchChannel) GetGroups() (err error) { func (p *TwitchChannel) GetGroups() (err error) {
query := `select g.*, rt.tmpl as tmpl from "public"."twitch_channel" tw query := `select g.*, rt.tmpl as tmpl from "public"."twitch_channel" tw

View File

@ -78,8 +78,6 @@ func getOpayData(ch *model.TwitchChannel) {
return return
} }
fmt.Println(oResp.LstDonate)
if len(oResp.LstDonate) == 0 { if len(oResp.LstDonate) == 0 {
return return
} }

View File

@ -10,7 +10,6 @@ import (
) )
func getStreamStatus() { func getStreamStatus() {
fmt.Println("run twitch check")
channels, err := model.GetAllTwitchChannel() channels, err := model.GetAllTwitchChannel()
if err != nil { if err != nil {
return return
@ -21,7 +20,6 @@ func getStreamStatus() {
} }
info := twitch.GetUserStreamStatus(ids) info := twitch.GetUserStreamStatus(ids)
fmt.Printf("info len: %d\n", len(info))
if len(info) == 0 { if len(info) == 0 {
return return
} }

View File

@ -1,13 +1,283 @@
package api package api
import ( import (
"fmt"
"time"
"git.trj.tw/golang/mtfosbot/model" "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) { 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) { func sessionTypeSystem() (ch []*model.TwitchChannel, err error) {
ch, err = model.GetAllTwitchChannel()
return 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)
}

View File

@ -17,7 +17,7 @@ import (
func NewServ() *gin.Engine { func NewServ() *gin.Engine {
r := gin.New() r := gin.New()
store, err := sessions.NewRedisStore(10, "tcp", "localhost:6379", "") store, err := sessions.NewRedisStore(10, "tcp", "localhost:6379", "", []byte("seckey"))
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
@ -47,6 +47,19 @@ 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))
} }
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") lineApis := r.Group("/line")
{ {