tome_matrix/dealer.go

231 lines
5.8 KiB
Go

package main
import (
"fmt"
"log"
"maunium.net/go/mautrix"
"maunium.net/go/mautrix/event"
"maunium.net/go/mautrix/id"
)
type Dealer struct {
RoomsList map[id.RoomID]*Match
PlayerRooms map[id.UserID]id.RoomID
Client *mautrix.Client
QueueRoom id.RoomID
HomeserverDomain string
}
func (d *Dealer) ConnectToMatrix(homeserver, uname, passwd string) {
log.Println("Logging into", homeserver, "as", uname)
client, err := mautrix.NewClient(homeserver, "", "")
if err != nil {
panic(err)
}
client.Store = NewLazyMemStore("dealer_state")
_, err = client.Login(&mautrix.ReqLogin{
Type: "m.login.password",
Identifier: mautrix.UserIdentifier{Type: mautrix.IdentifierTypeUser, User: uname},
Password: passwd,
StoreCredentials: true,
})
if err != nil {
panic(err)
}
fmt.Println("Login successful")
d.Client = client
}
func (d *Dealer) RegisterHandlers() {
syncer := d.Client.Syncer.(*mautrix.DefaultSyncer)
syncer.OnEventType(event.StateMember, func(source mautrix.EventSource, evt *event.Event) {
if evt.Sender == d.Client.UserID {
return
}
if evt.RoomID == d.QueueRoom {
d.QueueEvent(evt)
return
}
proom, ok := d.PlayerRooms[evt.Sender]
if ok {
log.Printf("membership event for player room %v", proom)
if evt.Content.AsMember().Membership.IsLeaveOrBan() {
delete(d.PlayerRooms, evt.Sender)
return
}
}
if evt.Content.AsMember().IsDirect {
//intention to create player room
if evt.Content.AsMember().Membership.IsInviteOrJoin() {
d.PlayerRooms[evt.Sender] = evt.RoomID
_, err := d.Client.JoinRoomByID(evt.RoomID)
if err != nil {
panic(err)
}
} else if evt.Content.AsMember().Membership.IsLeaveOrBan() {
delete(d.PlayerRooms, evt.Sender)
}
return
}
match, ok := d.RoomsList[evt.RoomID]
if !ok {
log.Printf("received membership event for non active game: %v", evt)
return
}
if evt.Sender != match.P1 || evt.Sender != match.P2 || evt.Sender != d.Client.UserID {
log.Println("membership event for non player")
return
}
gameRoom := d.Client.Store.LoadRoom(evt.RoomID)
match.JoinOrLeave(gameRoom, evt)
})
syncer.OnEventType(event.EventMessage, func(source mautrix.EventSource, evt *event.Event) {
playerRoom, ok := d.PlayerRooms[evt.Sender]
if ok {
log.Printf("received direct message in room %v", playerRoom)
return
}
match, ok := d.RoomsList[evt.RoomID]
if !ok {
log.Println("received message event for non active game")
return
}
if !match.IsPlayer(evt.Sender) {
log.Println("ignoring message event from non player")
return
}
//parse as game command
resp := match.ParseAction(evt.Content.AsMessage().Body)
if resp.Private {
//respond privately
dm, ok := d.PlayerRooms[evt.Sender]
if !ok {
log.Println("tried to send private message to player without room")
return
}
_, err := d.Client.SendText(dm, resp.Body)
if err != nil {
panic(err)
}
} else {
_, err := d.Client.SendText(evt.RoomID, resp.Body)
if err != nil {
panic(err)
}
}
})
}
func (d *Dealer) SetupRooms(domain string) {
room := "#tomequeue:" + domain
// try creating the room first
res, createErr := d.Client.CreateRoom(&mautrix.ReqCreateRoom{
Preset: "public_chat",
Visibility: "public",
RoomAliasName: "tomequeue",
})
if createErr != nil {
//okay let's try joining the room first
res, err := d.Client.JoinRoom(room, "", nil)
if err != nil {
log.Println("unable to create or join queue room")
log.Printf("Create err: %v", createErr)
panic(err)
}
log.Printf("succesfully joined %v", res.RoomID)
d.QueueRoom = res.RoomID
return
}
resJoin, err := d.Client.JoinRoomByID(res.RoomID)
if err != nil {
log.Println("error joined recently created queue room")
panic(err)
}
log.Printf("succesfully created and joined %v", resJoin.RoomID)
d.QueueRoom = resJoin.RoomID
//load player rooms
joinedResp, err := d.Client.JoinedRooms()
if err != nil {
panic(err)
}
for _, r := range joinedResp.JoinedRooms {
tags, err := d.Client.GetTags(r)
if err != nil {
continue
}
_, ok := tags.Tags["tome_player_room"]
if !ok {
continue
}
memberListResp, err := d.Client.JoinedMembers(r)
if err != nil {
continue
}
keys := make([]id.UserID, 0, len(memberListResp.Joined))
for k := range memberListResp.Joined {
keys = append(keys, k)
}
if len(keys) != 2 {
log.Printf("tagged player room %v has more then 2 members")
continue
}
for _, k := range keys {
if k != d.Client.UserID {
d.PlayerRooms[k] = r
}
}
}
}
func (d *Dealer) NewMatch(p1, p2 id.UserID) *Match {
//creates a new matrix room for the match
match := NewMatch()
roomname := fmt.Sprintf("tome_match_%v", match.ID)
createRes, err := d.Client.CreateRoom(&mautrix.ReqCreateRoom{
Preset: "public",
RoomAliasName: roomname,
Invite: []id.UserID{p1, p2},
})
if err != nil {
log.Println("error creating matrix room for match")
panic(err)
}
match.MatrixRoom = createRes.RoomID
match.P1 = p1
match.P2 = p2
match.Dealer = d.Client.UserID
d.RoomsList[createRes.RoomID] = match
return match
}
func (d *Dealer) QueueEvent(evt *event.Event) {
mem := evt.Content.AsMember()
if mem.Membership == event.MembershipJoin {
log.Printf("Player %v has queued", evt.Sender)
_, ok := d.PlayerRooms[evt.Sender]
if !ok {
//open up DM with player
createRes, err := d.Client.CreateRoom(&mautrix.ReqCreateRoom{
Preset: "private_chat",
Invite: []id.UserID{evt.Sender},
IsDirect: true,
})
if err != nil {
log.Println("error creating matrix room for player")
panic(err)
}
d.PlayerRooms[evt.Sender] = createRes.RoomID
err = d.Client.AddTag(createRes.RoomID, "tome_player_room", 0.0)
if err != nil {
panic(err)
}
}
} else if mem.Membership.IsLeaveOrBan() {
log.Printf("Player %v has dequeued", evt.Sender)
}
return
}