aboutsummaryrefslogtreecommitdiff
path: root/internal/net/server.go
blob: e5761a22eeae74ed2afd53926546e3440f2f23f1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
package net

import (
	"bufio"
	"fmt"
	"log"
	"net"
	"strings"
)

type SessionState int

const (
	StateAccountName       SessionState = iota
	StatePassword
	StateNewAccountPass
	StateNewAccountConfirm
	StateMenu
	StateNewCharName
	StateNewCharConfirm
	StateRenameAccount
	StateRenameChar
	StateRenameCharName
	StateDeleteChar
	StatePurgeAccount
	StateGame
	StateChangeDescription
)

type Session struct {
	Conn        net.Conn
	Reader      *bufio.Reader
	State       SessionState
	Account     *AccountEntry
	Player      interface{} // *player.Player once character is selected
	PendingChar  string     // char being renamed/deleted
	PendingPass  string     // first password during signup
	Disconnecting bool
	DisconnectTicks int
}

type AccountEntry struct {
	Name         string
	PasswordHash string
	Characters   []string
}

type Server struct {
	listener net.Listener
	hub      *Hub
}

type Hub struct {
	sessions  map[*Session]bool
	rooms     map[int]map[*Session]bool
	onRemove  func(*Session)
}

func NewHub() *Hub {
	return &Hub{
		sessions: make(map[*Session]bool),
		rooms:    make(map[int]map[*Session]bool),
	}
}

func (h *Hub) OnRemove(cb func(*Session)) {
	h.onRemove = cb
}

func (h *Hub) Add(s *Session) {
	h.sessions[s] = true
}

func (h *Hub) Remove(s *Session) {
	if s.Player != nil && s.State == StateGame && !s.Disconnecting {
		s.Disconnecting = true
		s.DisconnectTicks = 10
		return
	}
	h.HardRemove(s)
}

func (h *Hub) HardRemove(s *Session) {
	delete(h.sessions, s)
	for _, room := range h.rooms {
		delete(room, s)
	}
	if h.onRemove != nil {
		h.onRemove(s)
	}
}

func (h *Hub) EnterRoom(s *Session, roomID int) {
	h.LeaveRoom(s)
	if h.rooms[roomID] == nil {
		h.rooms[roomID] = make(map[*Session]bool)
	}
	h.rooms[roomID][s] = true
}

func (h *Hub) LeaveRoom(s *Session) {
	for _, room := range h.rooms {
		delete(room, s)
	}
}

func (h *Hub) AllSessions() []*Session {
	var out []*Session
	for s := range h.sessions {
		out = append(out, s)
	}
	return out
}

func (h *Hub) PlayersInRoom(roomID int) []*Session {
	var out []*Session
	if room, ok := h.rooms[roomID]; ok {
		for s := range room {
			out = append(out, s)
		}
	}
	return out
}

func NewServer(addr string) (*Server, error) {
	l, err := net.Listen("tcp", addr)
	if err != nil {
		return nil, err
	}
	return &Server{listener: l, hub: NewHub()}, nil
}

func (s *Server) Hub() *Hub {
	return s.hub
}

func (s *Server) ListenAndServe(handler func(*Session, string)) error {
	for {
		conn, err := s.listener.Accept()
		if err != nil {
			return err
		}
		session := &Session{
			Conn:   conn,
			Reader: bufio.NewReader(conn),
			State:  StateAccountName,
		}
		s.hub.Add(session)
		go s.handleSession(session, handler)
	}
}

func (s *Server) handleSession(session *Session, handler func(*Session, string)) {
	defer func() {
		if r := recover(); r != nil {
			log.Printf("session panic: %v", r)
		}
		s.hub.Remove(session)
		session.Conn.Close()
	}()

	_, _ = session.Conn.Write([]byte("\033[2J\033[H")) // clear screen

	welcomeart := `
 ,       3333333 333  333 333 3333333  3333333                        
   |       33!   33!  333 33! 33!  333 33!  333     ':.       +       
  -+-   *  3!!   3!3!3!3! !!3 3!3!!3!  3!3  !3!      '::._          * 
   |       !!:   !!:  !!! !!: !!: :!!  !!:  !!!        '._)           
            :     :   : : :    :   : : :: :  :                 ,      
       .                            *              ,                  
 ,             welcome to third collapse      .                   *   
                                                                      
 3333333  333333  333  ,   333       333333  3333333   333333 33333333
 !33      33!  333 33!      33!      33!  333 33!  333 !33     33!    
 !3!      3!3  !3! 3!!      3!!   +  3!3!3!3! 3!33!3!   !33!!  3!!!:! 
 :!!      !!:  !!! !!:      !!:      !!:  !!! !!:          !:! !!:    
 :: :: :  : :. :  : ::.: : : ::.: :  :   : :  :       ::.: :  : :: :::


`

	session.Write(welcomeart)
	session.Write("ACCOUNT NAME> ")

	for {
		line, err := session.Reader.ReadString('\n')
		if err != nil {
			log.Printf("session read error: %v", err)
			return
		}
		line = strings.TrimSpace(line)
		handler(session, line)
	}
}

func (sess *Session) Write(msg string) {
	_, _ = sess.Conn.Write([]byte(msg))
}

func (sess *Session) WriteLine(msg string) {
	_, _ = sess.Conn.Write([]byte(msg + "\r\n"))
}

func (sess *Session) WriteLines(lines ...string) {
	for _, l := range lines {
		sess.WriteLine(l)
	}
}

func (sess *Session) Writef(format string, args ...interface{}) {
	sess.Write(fmt.Sprintf(format, args...))
}