This repository was archived by the owner on Aug 21, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
307 lines (255 loc) · 7.45 KB
/
main.go
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
package main
import (
"github.com/caarlos0/env/v5"
"github.com/gorilla/websocket"
"gopkg.in/mgo.v2/bson"
"fmt"
"math/rand"
"net/http"
"time"
)
type (
Config struct {
DbHost string `env:"DB_HOST" envDefault:"127.0.0.1"`
DbPort string `env:"DB_PORT" envDefault:"27017"`
DbName string `env:"DB_NAME" envDefault:"spyfall"`
DbGameCollection string `env:"DB_GAME_COLLETION" envDefault:"games"`
DbPlayerCollection string `env:"DB_PLAYER_COLLECTION" envDefault:"players"`
DbLocationCollection string `env:"DB_LOC_COLLECTION" envDefault:"locations"`
HTTPAddr string `env:"HTTP_ADDRESS" envDefault:"0.0.0.0"`
HTTPPort string `env:"HTTP_PORT" envDefault:"80"`
HTTPDir string `env:"HTTP_DIR" envDefault:"public"`
}
UserConnection struct {
Player PlayerEntry
Game GameEntry
}
)
var (
dbConn DatabaseConnection
errorOther = "OTHER_ERROR"
errorGameExists = "GAME_EXISTS_ERROR"
errorGameNotFound = "GAME_NOT_FOUND_ERROR"
errorGameNotRemoved = "GAME_NOT_REMOVED_ERROR"
errorGameInProgress = "GAME_IN_PROGRESS"
errorUsernameExists = "PLAYER_EXISTS_ERROR"
errorPlayerNotFound = "PLAYER_NOT_FOUND_ERROR"
errorPlayerNotRemoved = "PLAYER_NOT_REMOVED_ERROR"
errorNoGameCode = "NO_GAME_CODE_ERROR"
errorNoUsername = "NO_USERNAME_ERROR"
errorCodeExists = "GAME_EXISTS_ERROR"
errorInvalidUserName = "INVALID_USER_NAME_ERROR"
//
connectedPlayers = make(map[bson.ObjectId][]*websocket.Conn) //Map the game's id to an array of websocket connections
players = make(map[*websocket.Conn]bson.ObjectId) //Map the player's connection to their id
connections = make(map[bson.ObjectId]*websocket.Conn) //Map the player's id to their connection
//
)
/*
TODO:
- When someone creates a game, they are not added to the players collection
- When the last player leaves a game, the game is not deleted
- Test getGame to see what it returns when no game exists
- Add handler for disconnections
*/
func main() {
cfg := Config{}
if err := env.Parse(&cfg); err != nil {
fmt.Println(err)
}
fmt.Println("Attempting to connect to database at: " + cfg.DbHost + ":" + cfg.DbPort)
var err error
dbConn, err = dbConnect(DbOptions{
Server: cfg.DbHost + ":" + cfg.DbPort,
Database: cfg.DbName,
GameCollection: cfg.DbGameCollection,
PlayerCollection: cfg.DbPlayerCollection,
LocationCollection: cfg.DbLocationCollection,
})
if err != nil {
fmt.Println(err)
fmt.Println("Unable to connect to database. Shutting down.")
}
fmt.Println("Sucessfully connected to database.")
http.Handle("/", http.FileServer(http.Dir(cfg.HTTPDir)))
http.HandleFunc("/api", func(w http.ResponseWriter, r *http.Request) {
s, err := newSocketRouter(w, r)
if err != nil {
fmt.Println(err)
}
s.addRoute("createGame", createGame)
//s.addRoute("destroyGame", destroyGame)
s.addRoute("joinGame", joinGame)
s.addRoute("leaveGame", leaveGame)
s.addRoute("startGame", startGame)
s.addRoute("stopGame", stopGame)
s.addDisconnect(func(ctx SocketContext) {
})
s.handleRoutes()
})
fmt.Println("Listening for connections on port: " + cfg.HTTPPort)
http.ListenAndServe(":"+cfg.HTTPPort, nil)
}
func createGame(ctx SocketContext) SocketResponse {
username := ctx.Data["username"].(string)
socketResponse := SocketResponse{
Type: ctx.Type,
}
if username == "" {
socketResponse.Error = &ResponseError{
Code: errorInvalidUserName,
Desc: "The username: \"" + username + "\" is invalid.",
}
return socketResponse
}
game, err := dbConn.addGame()
if err != nil {
socketResponse.Error = &ResponseError{
Code: errorOther,
Desc: err.Error(),
}
return socketResponse
}
ctx.Prop["code"] = game.Code
return joinGame(ctx)
}
// To be removed in favor of destroying a game after all players leave
/*
func destroyGame(ctx SocketContext) SocketResponse {
responseData := ResponseData{Sucess: true}
player, err := dbConn.getPlayer(players[ctx.Connection])
if err != nil {
responseData.Sucess = false
responseData.Error = ResponseError{
Code: errorOther,
Desc: err.Error(),
}
return SocketResponse{
Type: ctx.Type,
Data: responseData,
}
}
responseData.Code = gameCodes[player.Game]
responseData.Username = player.Username
err = dbConn.delGame(player.Game)
if err != nil {
if err.Error() == errorGameNotFound {
responseData.Error = ResponseError{
Code: err.Error(),
Desc: "Game: " + responseData.Code + " not found in the database.",
}
} else {
responseData.Error = ResponseError{
Code: errorOther,
Desc: err.Error(),
}
}
return SocketResponse{
Type: ctx.Type,
Data: responseData,
}
}
for _, ctx := range connectedPlayers[player.Game] {
ctx.WriteJSON()
}
delete(connectedPlayers, player.Game) //TODO: Add a function here to inform the connected sockets that the game is removed
return leaveGame(ctx)
}
*/
func joinGame(ctx SocketContext) SocketResponse {
code, ok := ctx.Prop["code"].(string)
if !ok {
code = ctx.Data["code"].(string)
}
username := ctx.Data["username"].(string)
socketResponse := SocketResponse{
Type: ctx.Type,
ResponseData: &ResponseData{
Code: code,
Username: username,
},
}
gid, ok := gameIds[code]
if !ok {
socketResponse.Error = &ResponseError{
Code: errorGameNotFound,
Desc: "Game '" + code + "' was not found. Is the game code correct?",
}
return socketResponse
}
player, err := dbConn.addPlayer(username, gid)
if err != nil {
switch err.Error() {
case errorGameInProgress:
socketResponse.Error = &ResponseError{
Code: err.Error(),
Desc: "Cannot join a game that is currently in progress.",
}
case errorUsernameExists:
socketResponse.Error = &ResponseError{
Code: err.Error(),
Desc: "Player with the username: " + username + " already exists in game: " + code + ".",
}
default:
socketResponse.Error = &ResponseError{
Code: errorOther,
Desc: err.Error(),
}
}
return socketResponse
}
//Broadcast to all players that a player has joined
connectedPlayers[gid] = append(connectedPlayers[gid], ctx.Connection)
connections[player.ID] = ctx.Connection
players[ctx.Connection] = player.ID
return socketResponse
}
func leaveGame(ctx SocketContext) SocketResponse {
socketResponse := SocketResponse{
Type: ctx.Type,
}
player, err := dbConn.getPlayer(players[ctx.Connection])
if err != nil {
socketResponse.Error = &ResponseError{
Code: errorOther,
Desc: err.Error(),
}
return socketResponse
}
socketResponse.ResponseData = &ResponseData{
Code: gameCodes[player.Game],
Username: player.Username,
}
err = dbConn.delPlayer(player.ID)
if err != nil {
socketResponse.Error = &ResponseError{
Code: errorOther,
Desc: err.Error(),
}
return socketResponse
}
delete(connections, player.ID) //TODO: Add a function here to inform the connected websockets which are in this game that a player disconnected
delete(players, ctx.Connection)
return socketResponse
}
func startGame(ctx SocketContext) SocketResponse {
return SocketResponse{}
}
func stopGame(ctx SocketContext) SocketResponse {
return SocketResponse{}
}
func generateCode() string {
var letter = []rune("abcdefghijklmnopqrstuvwxyz")
rand.Seed(time.Now().UnixNano())
b := make([]rune, 6)
for i := range b {
b[i] = letter[rand.Intn(len(letter))]
}
return string(b)
}
func notNil(test interface{}) interface{} {
if test != nil {
return test
}
return ""
}