mirror of
https://codeberg.org/SafeTwitch/safetwitch-backend.git
synced 2024-12-23 05:32:59 -05:00
105 lines
2.3 KiB
Go
105 lines
2.3 KiB
Go
package chat
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"log"
|
|
"net/url"
|
|
"strings"
|
|
|
|
"github.com/gorilla/websocket"
|
|
)
|
|
|
|
var u = url.URL{Scheme: "wss", Host: "irc-ws.chat.twitch.tv:443", Path: "/"}
|
|
var conn, _, err = websocket.DefaultDialer.Dial(u.String(), nil)
|
|
|
|
// If the connection is ready to subscribe to channels
|
|
var connectionReady = false
|
|
var streamersFollowing = map[string]bool{}
|
|
|
|
func BeginTwitchChatConnection() {
|
|
log.Println("Connecting to Twitch IRC")
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
defer conn.Close()
|
|
|
|
// Authenticate with server
|
|
err = sendMessage("CAP REQ :twitch.tv/membership twitch.tv/tags twitch.tv/commands")
|
|
err = sendMessage("PASS none")
|
|
err = sendMessage("NICK justinfan333333333333")
|
|
if err != nil {
|
|
log.Printf("Failed to send message: %v", err)
|
|
}
|
|
|
|
// Follow streamers
|
|
for streamer := range streamersFollowing {
|
|
sendMessage("JOIN #" + streamer)
|
|
}
|
|
|
|
// Continue to listen for incoming messages from the server.
|
|
for {
|
|
_, msg, err := conn.ReadMessage()
|
|
if err != nil {
|
|
log.Printf("Failed to read message: %v", err)
|
|
break
|
|
}
|
|
|
|
parseMessage(string(msg))
|
|
RemoveUnusedStreamers()
|
|
|
|
fmt.Println(ClientHandler.FindClientsByStreamer("dino_xx"))
|
|
|
|
//fmt.Println("Received message from server:", string(msg))
|
|
}
|
|
}
|
|
|
|
func sendMessage(msg string) error {
|
|
return conn.WriteMessage(websocket.TextMessage, []byte(msg))
|
|
}
|
|
|
|
func parseMessage(msg string) error {
|
|
if !connectionReady && strings.Contains(msg, "001") {
|
|
connectionReady = true
|
|
log.Println("Authenticated with Twitch IRC!")
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func FollowStreamer(streamerName string) error {
|
|
err := sendMessage("JOIN #" + strings.ToLower(streamerName))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
streamersFollowing[streamerName] = true
|
|
|
|
return nil
|
|
}
|
|
|
|
func SendMessage(msg string) error {
|
|
if connectionReady {
|
|
return conn.WriteMessage(websocket.TextMessage, []byte(msg))
|
|
}
|
|
|
|
return errors.New("connection not ready")
|
|
}
|
|
|
|
// function to check and remove unused streamers from server map
|
|
func RemoveUnusedStreamers() {
|
|
for streamer := range streamersFollowing {
|
|
found := false
|
|
// iterate over each client and their streamer map
|
|
for client, _ := range ClientHandler {
|
|
if client.FollowingStreamers[streamer] == true {
|
|
found = true
|
|
break
|
|
}
|
|
}
|
|
if !found {
|
|
// remove streamer from server map
|
|
delete(streamersFollowing, streamer)
|
|
}
|
|
}
|
|
}
|