ouch-relay/relay.go

119 lines
2.4 KiB
Go
Raw Normal View History

2025-02-26 22:48:32 -05:00
package main
import (
"encoding/json"
"fmt"
"log"
2025-02-26 22:48:32 -05:00
"os"
"sync"
"time"
2025-02-26 22:48:32 -05:00
"git.thc420.dev/blackbeard420/gomirc.git"
2025-02-26 22:48:32 -05:00
"git.thc420.dev/blackbeard420/irc"
)
type Network struct {
Url string `json:"url"`
Nick string `json:"nick"`
Channel string `json:"channel"`
Name string `json:"name"`
RecvOnly bool `json:"recvonly"`
2025-02-26 22:48:32 -05:00
Connection irc.Connection
}
type Config struct {
Networks []Network `json:"networks"`
}
var netmap map[string]*Network
var netmutex sync.Mutex
func main() {
buf, _ := os.ReadFile("config.json")
conf := Config{}
json.Unmarshal(buf, &conf)
netmap = make(map[string]*Network)
wg := sync.WaitGroup{}
for _, n := range conf.Networks {
2025-02-26 22:48:32 -05:00
wg.Add(1)
initRelay(&n)
2025-02-26 22:48:32 -05:00
}
wg.Wait()
}
func initRelay(n *Network) {
log.Printf("Connecting to [%s] %s\n", n.Name, n.Channel)
2025-02-26 22:48:32 -05:00
netmutex.Lock()
defer netmutex.Unlock()
netmap[n.Name] = n
n.Connection = *irc.NewConnection(n.Url, n.Nick, n.Nick, nil, []string{n.Channel})
if !n.RecvOnly {
n.Connection.PrivmsgCallbackEx = handleMessage
n.Connection.JoinCallbackEx = handleJoin
n.Connection.PartCallbackEx = handlePart
n.Connection.QuitCallbackEx = handleQuit
2025-02-26 22:48:32 -05:00
}
go runRelay(n)
2025-02-26 22:48:32 -05:00
}
func deleteRelay(n string) {
2025-02-27 19:09:31 -05:00
netmutex.Lock()
defer netmutex.Unlock()
delete(netmap, n)
}
2025-02-27 19:09:31 -05:00
func runRelay(n *Network) {
n.Connection.Run()
relay(&n.Connection, "Network connection lost, retrying in 15 seconds")
time.Sleep(time.Second * 15)
initRelay(n)
2025-02-27 19:09:31 -05:00
}
func handleMessage(c *irc.Connection, channel, nick, msg string) {
relay(c, fmt.Sprintf("<%s> %s", irc.GetNick(nick), msg))
}
2025-02-27 19:09:31 -05:00
func handleJoin(c *irc.Connection, from, target string) {
relay(c, fmt.Sprintf("<%s> joined %s", irc.GetNick(from), target))
}
2025-02-27 19:09:31 -05:00
func handlePart(c *irc.Connection, from, target, msg string) {
relay(c, fmt.Sprintf("<%s> parted %s %s", irc.GetNick(from), target, msg))
2025-02-27 19:09:31 -05:00
}
func handleQuit(c *irc.Connection, from, msg string) {
relay(c, fmt.Sprintf("<%s> has quit [%s]", irc.GetNick(from), msg))
}
func relay(c *irc.Connection, msg string) {
2025-02-27 19:09:31 -05:00
netmutex.Lock()
defer netmutex.Unlock()
us := getByConn(c)
networkid := gomirc.Grey().Sprintf("[%s]", netmap[us].Name)
2025-02-27 19:09:31 -05:00
for _, n := range netmap {
if n.Name != us {
n.Connection.SendPrivmsg(n.Channel, fmt.Sprintf("%s %s", networkid, msg))
2025-02-27 19:09:31 -05:00
}
}
}
2025-02-26 22:48:32 -05:00
func getByConn(c *irc.Connection) string {
for _, n := range netmap {
if n.Connection.Sock == c.Sock {
return n.Name
}
}
return ""
}