diff --git a/module/twitch-irc/message-queue.go b/module/twitch-irc/message-queue.go new file mode 100644 index 0000000..acc0837 --- /dev/null +++ b/module/twitch-irc/message-queue.go @@ -0,0 +1,63 @@ +package twitchirc + +import ( + "sync" +) + +// MsgObj - +type MsgObj struct { + Command string + Params []string +} + +// QueueList - +type QueueList struct { + Messages []*MsgObj + Lock *sync.Mutex +} + +// NewQueue - +func NewQueue() *QueueList { + return &QueueList{} +} + +// Add - add element +func (q *QueueList) Add(m *MsgObj) { + q.Messages = append(q.Messages, m) +} + +// Get - get element +func (q *QueueList) Get() (m *MsgObj) { + if q.IsEmpty() { + return nil + } + m = q.Messages[0] + q.Messages = q.Messages[1:] + return +} + +// IsEmpty - +func (q *QueueList) IsEmpty() bool { + if len(q.Messages) == 0 { + return true + } + return false +} + +// Size - +func (q *QueueList) Size() int { + return len(q.Messages) +} + +// Clear - +func (q *QueueList) Clear() { + if q.IsEmpty() { + return + } + + for i := 0; i < len(q.Messages); i++ { + q.Messages[i] = nil + } + q.Messages = nil + return +} diff --git a/module/twitch-irc/twitch-irc.go b/module/twitch-irc/twitch-irc.go index 6445980..a35fb19 100644 --- a/module/twitch-irc/twitch-irc.go +++ b/module/twitch-irc/twitch-irc.go @@ -3,6 +3,7 @@ package twitchirc import ( "fmt" "net" + "time" "gopkg.in/irc.v2" @@ -10,6 +11,8 @@ import ( ) var client *irc.Client +var queue *QueueList +var channels []string // InitIRC - func InitIRC() (err error) { @@ -25,9 +28,91 @@ func InitIRC() (err error) { client = irc.NewClient(conn, config) err = client.Run() + + queue = NewQueue() + go runQueue() + + channels = make([]string, 0) return } -func ircHandle(c *irc.Client, m *irc.Message) { - fmt.Println(m.String()) +// JoinChannel - +func JoinChannel(ch string) { + if len(ch) == 0 { + return + } + + if indexOf(channels, ch) != -1 { + return + } + + m := &MsgObj{ + Command: "JOIN", + Params: []string{ + fmt.Sprintf("#%s", ch), + }, + } + queue.Add(m) + + // msg := &irc.Message{} + // msg.Command = "JOIN" + // msg.Params = []string{ + // fmt.Sprintf("#%s", ch), + // } + // client.WriteMessage(msg) +} + +// LeaveChannel - +func LeaveChannel(ch string) { + if len(ch) == 0 { + return + } + + if indexOf(channels, ch) == -1 { + return + } + + m := &MsgObj{ + Command: "PART", + Params: []string{ + fmt.Sprintf("#%s", ch), + }, + } + queue.Add(m) +} + +func runQueue() { + for { + if !queue.IsEmpty() { + m := queue.Get() + msg := &irc.Message{} + msg.Command = m.Command + msg.Params = m.Params + err := client.WriteMessage(msg) + if err == nil { + if m.Command == "JOIN" { + + } else if m.Command == "PART" { + + } + } + } + time.Sleep(time.Microsecond * 1500) + } +} + +func ircHandle(c *irc.Client, m *irc.Message) { + +} + +func indexOf(c []string, data string) int { + if len(c) == 0 { + return -1 + } + for k, v := range c { + if v == data { + return k + } + } + return -1 }