2024-04-06 16:38:14 -06:00
|
|
|
package pnyx
|
|
|
|
|
|
|
|
import (
|
2024-04-08 11:28:52 -06:00
|
|
|
"slices"
|
2024-04-06 16:38:14 -06:00
|
|
|
)
|
|
|
|
|
|
|
|
type ChannelID uint32
|
|
|
|
|
2024-04-08 11:28:52 -06:00
|
|
|
const (
|
|
|
|
RootChannelID ChannelID = 0
|
|
|
|
|
|
|
|
MODE_RAW ModeID = iota
|
|
|
|
|
|
|
|
MODE_COMMAND_DATA byte = 0x00
|
|
|
|
MODE_COMMAND_JOIN = 0x01
|
|
|
|
MODE_COMMAND_LEAVE = 0x02
|
|
|
|
)
|
2024-04-06 16:38:14 -06:00
|
|
|
|
|
|
|
type ModeID uint8
|
|
|
|
type CommandID uint8
|
|
|
|
|
|
|
|
type Channel struct {
|
|
|
|
modes map[ModeID]Mode
|
2024-04-08 11:28:52 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
type SendPacket struct {
|
|
|
|
Packet *Packet
|
|
|
|
Session SessionID
|
2024-04-06 16:38:14 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
type Mode interface {
|
2024-04-08 11:28:52 -06:00
|
|
|
// Process takes incoming packets from a session and returns a list of packets to send
|
|
|
|
Process(*Session, *Packet) []SendPacket
|
|
|
|
}
|
|
|
|
|
|
|
|
func multiplex(session *Session, packet *Packet, sessions []SessionID) []SendPacket {
|
|
|
|
send_packets := make([]SendPacket, len(sessions))
|
|
|
|
for i, session_id := range(sessions) {
|
|
|
|
if session_id == session.ID {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
send_packets[i] = SendPacket{
|
|
|
|
Packet: packet,
|
|
|
|
Session: session_id,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return send_packets
|
|
|
|
}
|
|
|
|
|
|
|
|
type RawMode struct {
|
|
|
|
Sessions []SessionID
|
|
|
|
}
|
|
|
|
|
|
|
|
func(mode *RawMode) Process(session *Session, packet *Packet) []SendPacket {
|
|
|
|
switch packet.Command {
|
|
|
|
case MODE_COMMAND_JOIN:
|
|
|
|
if slices.Contains(mode.Sessions, session.ID) == false {
|
|
|
|
mode.Sessions = append(mode.Sessions, session.ID)
|
|
|
|
}
|
|
|
|
case MODE_COMMAND_LEAVE:
|
|
|
|
idx := slices.Index(mode.Sessions, session.ID)
|
|
|
|
if idx != -1 {
|
|
|
|
mode.Sessions = slices.Delete(mode.Sessions, idx, idx+1)
|
|
|
|
}
|
|
|
|
case MODE_COMMAND_DATA:
|
|
|
|
if slices.Contains(mode.Sessions, session.ID) {
|
|
|
|
new_packet := &Packet{
|
|
|
|
Channel: packet.Channel,
|
|
|
|
Mode: packet.Mode,
|
|
|
|
Command: MODE_COMMAND_DATA,
|
|
|
|
Data: append(session.Peer[:], packet.Data...),
|
|
|
|
}
|
|
|
|
return multiplex(session, new_packet, mode.Sessions)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
2024-04-06 16:38:14 -06:00
|
|
|
}
|