2017-04-15 05:35:29 +00:00
|
|
|
package twitchpubsub
|
|
|
|
|
|
|
|
import (
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/gorilla/websocket"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"strings"
|
|
|
|
"errors"
|
|
|
|
"encoding/json"
|
|
|
|
"sync"
|
2017-04-24 02:00:25 +00:00
|
|
|
"log"
|
2017-04-15 05:35:29 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
Ping = "PING"
|
|
|
|
Pong = "PONG"
|
|
|
|
Message = "MESSAGE"
|
|
|
|
Response = "RESPONSE"
|
|
|
|
|
|
|
|
TwitchUrl = "wss://pubsub-edge.twitch.tv"
|
|
|
|
)
|
|
|
|
|
|
|
|
type twitchMessage struct {
|
|
|
|
Type string `json:"type"`
|
|
|
|
Nonce string `json:"nonce,omitempty"`
|
|
|
|
Error string `json:"error,omitempty"`
|
|
|
|
Data struct {
|
|
|
|
Topic string
|
|
|
|
Message string
|
|
|
|
} `json:"data"`
|
|
|
|
}
|
|
|
|
|
|
|
|
type twitchListen struct {
|
|
|
|
Type string `json:"type"`
|
|
|
|
Nonce string `json:"nonce"`
|
|
|
|
Data *twitchListenData `json:"data"`
|
|
|
|
}
|
|
|
|
|
|
|
|
type twitchListenData struct {
|
|
|
|
Topics []string `json:"topics"`
|
|
|
|
AuthToken string `json:"auth_token,omitempty"`
|
|
|
|
}
|
|
|
|
|
|
|
|
type TwitchPubSub struct {
|
|
|
|
sync.RWMutex
|
|
|
|
|
|
|
|
wsConn *websocket.Conn
|
|
|
|
wsMutex sync.RWMutex
|
|
|
|
|
2017-04-24 02:00:25 +00:00
|
|
|
debug bool
|
|
|
|
|
2017-04-15 05:35:29 +00:00
|
|
|
// Event handlers
|
|
|
|
handlersMu sync.RWMutex
|
|
|
|
handlers map[string][]*eventHandlerInstance
|
|
|
|
onceHandlers map[string][]*eventHandlerInstance
|
|
|
|
|
|
|
|
// Responses
|
2017-04-16 19:07:27 +00:00
|
|
|
listening chan interface{}
|
2017-04-15 05:35:29 +00:00
|
|
|
responseCh chan *twitchMessage
|
|
|
|
|
|
|
|
SubscribedTopics []string
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewTwitchPubSub() *TwitchPubSub {
|
|
|
|
t := &TwitchPubSub{
|
|
|
|
responseCh: make(chan *twitchMessage),
|
|
|
|
}
|
|
|
|
|
|
|
|
return t
|
|
|
|
}
|
|
|
|
|
2017-04-24 02:00:25 +00:00
|
|
|
func (t *TwitchPubSub) EnableDebug() {
|
|
|
|
t.debug = true
|
|
|
|
}
|
|
|
|
|
2017-04-15 05:35:29 +00:00
|
|
|
func (t *TwitchPubSub) Open() error {
|
|
|
|
t.Lock()
|
|
|
|
defer t.Unlock()
|
|
|
|
|
2017-04-24 02:00:25 +00:00
|
|
|
if t.debug {
|
|
|
|
log.Println("Opening connection to", TwitchUrl)
|
|
|
|
}
|
|
|
|
|
2017-04-15 05:35:29 +00:00
|
|
|
c, _, err := websocket.DefaultDialer.Dial(TwitchUrl, nil)
|
|
|
|
|
|
|
|
if err != nil {
|
2017-04-24 02:00:25 +00:00
|
|
|
if t.debug {
|
|
|
|
log.Println("error opening connection:", err)
|
|
|
|
}
|
2017-04-15 05:35:29 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
t.wsConn = c
|
|
|
|
|
2017-04-16 19:07:27 +00:00
|
|
|
t.listening = make(chan interface{})
|
|
|
|
|
|
|
|
go t.reader(t.wsConn, t.listening)
|
|
|
|
go t.pinger(t.wsConn, t.listening)
|
2017-04-15 05:35:29 +00:00
|
|
|
|
|
|
|
if len(t.SubscribedTopics) > 0 {
|
|
|
|
return t.listen(t.SubscribedTopics)
|
|
|
|
} else {
|
|
|
|
return t.wsConn.WriteJSON(&twitchMessage{Type: Ping})
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (t *TwitchPubSub) Close() error {
|
2017-04-16 19:07:27 +00:00
|
|
|
if t.listening != nil {
|
|
|
|
close(t.listening)
|
|
|
|
t.listening = nil
|
|
|
|
}
|
|
|
|
|
2017-04-15 05:35:29 +00:00
|
|
|
if t.wsConn != nil {
|
|
|
|
// To cleanly close a connection, a client should send a close
|
|
|
|
// frame and wait for the server to close the connection.
|
|
|
|
t.wsConn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
|
|
|
|
|
|
|
|
time.Sleep(1 * time.Second)
|
|
|
|
|
|
|
|
t.wsConn.Close()
|
|
|
|
|
|
|
|
t.wsConn = nil
|
|
|
|
}
|
|
|
|
|
|
|
|
t.Unlock()
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (t *TwitchPubSub) reconnect() error {
|
|
|
|
wait := time.Duration(1)
|
|
|
|
|
|
|
|
for {
|
2017-04-24 02:00:25 +00:00
|
|
|
if t.debug {
|
|
|
|
log.Println("Reconnecting")
|
|
|
|
}
|
|
|
|
|
2017-04-15 05:35:29 +00:00
|
|
|
err := t.Open()
|
|
|
|
|
|
|
|
if err == nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2017-04-24 02:00:25 +00:00
|
|
|
if t.debug {
|
|
|
|
log.Println("Unable to reconnect")
|
|
|
|
}
|
|
|
|
|
2017-04-15 05:35:29 +00:00
|
|
|
<-time.After(wait * time.Second)
|
|
|
|
wait *= 2
|
|
|
|
|
|
|
|
if wait > 600 {
|
|
|
|
wait = 600
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (t *TwitchPubSub) Listen(topics []string) error {
|
|
|
|
err := t.listen(topics)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
// Update topic list
|
|
|
|
t.SubscribedTopics = append(t.SubscribedTopics, topics...)
|
|
|
|
}
|
|
|
|
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
func (t *TwitchPubSub) listen(topics []string) error {
|
2017-04-24 02:00:25 +00:00
|
|
|
if t.debug {
|
|
|
|
log.Println("Attempting to listen to topics", topics)
|
|
|
|
}
|
|
|
|
|
2017-04-15 05:35:29 +00:00
|
|
|
nonce := strings.Replace(uuid.New().String(), "-", "", -1)
|
|
|
|
|
|
|
|
t.wsMutex.Lock()
|
|
|
|
t.wsConn.WriteJSON(&twitchListen{
|
|
|
|
Type: "LISTEN",
|
|
|
|
Nonce: nonce,
|
|
|
|
Data: &twitchListenData{Topics: topics},
|
|
|
|
})
|
|
|
|
t.wsMutex.Unlock()
|
|
|
|
|
|
|
|
msg := <- t.responseCh
|
|
|
|
|
|
|
|
if msg.Nonce != nonce {
|
|
|
|
// Something is wrong, concurrent access?
|
|
|
|
return errors.New("Unexpected nonce")
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(msg.Error) > 0 {
|
|
|
|
return errors.New(msg.Error)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (t *TwitchPubSub) Unlisten(topics []string) error {
|
|
|
|
nonce := strings.Replace(uuid.New().String(), "-", "", -1)
|
|
|
|
|
|
|
|
for i := 0; i < len(topics); i++ {
|
|
|
|
for x := 0; x < len(t.SubscribedTopics); x++ {
|
|
|
|
if t.SubscribedTopics[x] == topics[i] {
|
|
|
|
t.SubscribedTopics = append(t.SubscribedTopics[:x], t.SubscribedTopics[x+1:]...)
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
t.wsMutex.Lock()
|
|
|
|
t.wsConn.WriteJSON(&twitchListen{
|
|
|
|
Type: "UNLISTEN",
|
|
|
|
Nonce: nonce,
|
|
|
|
Data: &twitchListenData{Topics: topics},
|
|
|
|
})
|
|
|
|
t.wsMutex.Unlock()
|
|
|
|
|
|
|
|
msg := <- t.responseCh
|
|
|
|
|
|
|
|
if msg.Nonce != nonce {
|
|
|
|
// Something is wrong, concurrent access?
|
|
|
|
return errors.New("Unexpected nonce")
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(msg.Error) > 0 {
|
|
|
|
return errors.New(msg.Error)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2017-04-16 19:07:27 +00:00
|
|
|
func (t *TwitchPubSub) reader(wsConn *websocket.Conn, listening <-chan interface{}) {
|
2017-04-15 05:35:29 +00:00
|
|
|
for {
|
|
|
|
var message twitchMessage
|
|
|
|
err := t.wsConn.ReadJSON(&message)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
t.RLock()
|
|
|
|
sameConnection := t.wsConn == wsConn
|
|
|
|
t.RUnlock()
|
|
|
|
|
2017-04-24 02:00:25 +00:00
|
|
|
if t.debug {
|
|
|
|
log.Println("Unexpected error", err, "- attempting to reconnect")
|
|
|
|
}
|
|
|
|
|
2017-04-15 05:35:29 +00:00
|
|
|
if sameConnection {
|
|
|
|
t.Close()
|
|
|
|
t.reconnect()
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2017-04-16 19:07:27 +00:00
|
|
|
select {
|
|
|
|
case <-listening:
|
|
|
|
return
|
|
|
|
default:
|
|
|
|
if message.Type == Pong {
|
|
|
|
// PONG!
|
|
|
|
} else if message.Type == Message {
|
|
|
|
var data interface{}
|
|
|
|
|
|
|
|
if err := json.Unmarshal([]byte(message.Data.Message), &data); err != nil {
|
|
|
|
continue
|
|
|
|
}
|
2017-04-15 05:35:29 +00:00
|
|
|
|
2017-04-16 19:07:27 +00:00
|
|
|
if strings.Index(message.Data.Topic, "video-playback") == 0 {
|
|
|
|
m := data.(map[string]interface{})
|
|
|
|
ch := message.Data.Topic[strings.Index(message.Data.Topic, ".") + 1:]
|
|
|
|
ty := m["type"].(string)
|
|
|
|
server_time := time.Unix(int64(m["server_time"].(float64)), 0)
|
|
|
|
|
|
|
|
if ty == "viewcount" {
|
|
|
|
go t.handle(ty, &ViewerCount{Channel: ch, Viewers: int(m["viewers"].(float64)), ServerTime: server_time})
|
|
|
|
} else if ty == "stream-up" {
|
|
|
|
go t.handle(ty, &StreamUp{Channel: ch, ServerTime: server_time})
|
|
|
|
} else if ty == "stream-down" {
|
|
|
|
go t.handle(ty, &StreamDown{Channel: ch, ServerTime: server_time})
|
|
|
|
}
|
2017-04-15 05:35:29 +00:00
|
|
|
}
|
2017-04-16 19:07:27 +00:00
|
|
|
} else if message.Type == Response {
|
|
|
|
t.responseCh <- &message
|
|
|
|
} else if message.Type == reconnectEventType {
|
|
|
|
go t.handle(message.Type, &Reconnect{})
|
|
|
|
t.reconnect()
|
2017-04-15 05:35:29 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-04-16 19:07:27 +00:00
|
|
|
func (t *TwitchPubSub) pinger(wsConn *websocket.Conn, listening <-chan interface{}) {
|
2017-04-15 05:35:29 +00:00
|
|
|
ticker := time.NewTicker(150 * time.Second)
|
|
|
|
defer ticker.Stop()
|
|
|
|
|
|
|
|
for {
|
2017-04-24 02:00:25 +00:00
|
|
|
if t.debug {
|
|
|
|
log.Println("Sending ping")
|
|
|
|
}
|
2017-04-15 05:35:29 +00:00
|
|
|
t.wsMutex.Lock()
|
2017-04-16 19:07:27 +00:00
|
|
|
err := wsConn.WriteJSON(&twitchMessage{Type: Ping})
|
2017-04-15 05:35:29 +00:00
|
|
|
t.wsMutex.Unlock()
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
2017-04-16 19:07:27 +00:00
|
|
|
|
|
|
|
select {
|
|
|
|
case <-ticker.C:
|
|
|
|
// continue loop and send heartbeat
|
|
|
|
case <-listening:
|
|
|
|
return
|
|
|
|
}
|
2017-04-15 05:35:29 +00:00
|
|
|
}
|
|
|
|
}
|