-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
331 lines (273 loc) · 8.83 KB
/
server.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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
package main
import (
"database/sql"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"time"
"github.com/gorilla/websocket"
_ "github.com/lib/pq"
)
// Globals
var (
isHeroku = checkHeroku()
configuration = loadConfig()
db = initDB()
swears = loadProfanity("en")
)
var roomConnectionMap = make(map[string][]*websocket.Conn)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true
},
}
func createRoomHandler(w http.ResponseWriter, r *http.Request) {
// generate the room string
roomString := randString(4)
// generate a secret to share with the creator
roomSecret := randString(32)
// insert the new room
queryString := "INSERT INTO rooms(room_code, secret, start_time) VALUES($1, $2, now())"
stmt, err := db.Prepare(queryString)
if err != nil {
failWithStatusCode(err, http.StatusText(http.StatusInternalServerError), w, http.StatusInternalServerError)
return
}
_, err = stmt.Exec(roomString, roomSecret)
if err != nil {
failWithStatusCode(err, http.StatusText(http.StatusInternalServerError), w, http.StatusInternalServerError)
return
}
fmt.Println("Creating room with code " + roomString + ".")
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, roomSecret+","+roomString)
}
func joinRoomHandler(w http.ResponseWriter, r *http.Request) {
// upgrade to a websocket
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
failWithStatusCode(err, http.StatusText(http.StatusBadRequest), w, http.StatusBadRequest)
return
}
messageType, p, err := conn.ReadMessage()
if err != nil {
failWithStatusCode(err, "Failed to handshake", w, http.StatusInternalServerError)
return
}
// Check DB if room exists
var code string
err = db.QueryRow("SELECT room_code FROM rooms WHERE room_code = $1", string(p)).Scan(&code)
if err == sql.ErrNoRows || err != nil {
// Room does not exist
returnmsg := []byte("Room " + string(p) + " does not exist.")
err = conn.WriteMessage(messageType, returnmsg)
if err != nil {
fmt.Println("error message broke bad lol")
return
}
fmt.Println("Room " + string(p) + " does not exist.")
return
}
fmt.Println("room code received: " + string(p) + ", " + string(messageType))
// Add this new socket to the room-sockets map
roomConnectionMap[string(p)] = append(roomConnectionMap[string(p)], conn)
// get list of questions for current room
QuestionsList := getRoom(string(p))
// broadcast updated question list to all clients in room
for _, socket := range roomConnectionMap[string(p)] {
// send questions DB stuff for code
err := socket.WriteJSON(QuestionsList)
if err != nil {
fmt.Println("Failed to send through websocket lol. Err: " + err.Error())
return
}
fmt.Println("Broadcasting questions for room " + string(p) + ".")
}
}
func voteHandler(w http.ResponseWriter, r *http.Request) {
// unmarhall the question id
decoder := json.NewDecoder(r.Body)
req := struct {
QuestionID int
RoomCode string
}{0, ""}
err := decoder.Decode(&req)
if err != nil {
failWithStatusCode(err, http.StatusText(http.StatusBadRequest), w, http.StatusBadRequest)
return
}
queryString := "UPDATE questions SET votes = votes + 1 WHERE q_id = $1"
stmt, err := db.Prepare(queryString)
if err != nil {
failWithStatusCode(err, http.StatusText(http.StatusInternalServerError), w, http.StatusInternalServerError)
return
}
_, err = stmt.Exec(req.QuestionID)
if err != nil {
failWithStatusCode(err, http.StatusText(http.StatusInternalServerError), w, http.StatusInternalServerError)
return
}
var QuestionText string
var QuestionVotes int
db.QueryRow("SELECT text, votes FROM questions WHERE q_id = $1", req.QuestionID).Scan(&QuestionText, &QuestionVotes)
// create and return Question struct of new question
question := Question{}
question.QID = req.QuestionID
question.Text = QuestionText
question.Votes = QuestionVotes
question.Hidden = false
// broadcast new question to all clients in room
for _, socket := range roomConnectionMap[req.RoomCode] {
// send questions DB stuff for code
err := socket.WriteJSON(question)
if err != nil {
failWithStatusCode(err, "Failed to send through websocket.", w, http.StatusInternalServerError)
return
}
fmt.Println("Broadcasting new question for room " + req.RoomCode + ".")
}
}
func askQuestionHandler(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
req := struct {
QuestionText string
RoomCode string
}{"", ""}
// get question text and room from request
err := decoder.Decode(&req)
if err != nil {
failWithStatusCode(err, http.StatusText(http.StatusBadRequest), w, http.StatusBadRequest)
return
}
if profane(req.QuestionText) {
failWithStatusCode(err, http.StatusText(http.StatusBadRequest), w, http.StatusBadRequest)
fmt.Println("bad word detected: " + req.QuestionText)
return
}
// add new question to DB
queryString := "INSERT INTO questions(room_code, text, votes) VALUES($1, $2, 0) RETURNING q_id"
var QID int
err = db.QueryRow(queryString, req.RoomCode, req.QuestionText).Scan(&QID)
if err != nil {
failWithStatusCode(err, http.StatusText(http.StatusInternalServerError), w, http.StatusInternalServerError)
return
}
fmt.Printf("code: %s, text: %s\n", req.RoomCode, req.QuestionText)
// create and return Question struct of new question
question := Question{}
question.QID = QID
question.Text = req.QuestionText
question.Votes = 0
question.Hidden = false
// broadcast new question to all clients in room
for _, socket := range roomConnectionMap[req.RoomCode] {
// send questions DB stuff for code
err := socket.WriteJSON(question)
if err != nil {
failWithStatusCode(err, "Failed to send through websocket.", w, http.StatusInternalServerError)
return
}
fmt.Println("Broadcasting new question for room " + req.RoomCode + ".")
}
}
func hideHandler(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
req := struct {
QuestionID int
RoomCode string
Secret string
}{0, "", ""}
err := decoder.Decode(&req)
if err != nil {
failWithStatusCode(err, http.StatusText(http.StatusBadRequest), w, http.StatusBadRequest)
}
queryString := "UPDATE questions SET hide = NOT hide" //toggle hidden status
stmt, err := db.Prepare(queryString)
if err != nil {
failWithStatusCode(err, http.StatusText(http.StatusInternalServerError), w, http.StatusInternalServerError)
return
}
_, err = stmt.Exec(req.QuestionID)
if err != nil {
failWithStatusCode(err, http.StatusText(http.StatusInternalServerError), w, http.StatusInternalServerError)
return
}
var QuestionText string
var QuestionVotes int
db.QueryRow("SELECT text, votes FROM questions WHERE q_id = $1", req.QuestionID).Scan(&QuestionText, &QuestionVotes)
// create and return Question struct of new question
question := Question{}
question.QID = req.QuestionID
question.Text = QuestionText
question.Votes = QuestionVotes
question.Hidden = true
// broadcast new question to all clients in room
for _, socket := range roomConnectionMap[req.RoomCode] {
// send questions DB stuff for code
err := socket.WriteJSON(question)
if err != nil {
failWithStatusCode(err, "Failed to send through websocket.", w, http.StatusInternalServerError)
return
}
fmt.Println("Broadcasting new question for room " + req.RoomCode + ".")
}
}
func loadConfig() Configuration {
configuration := Configuration{}
if !isHeroku {
file, err := os.Open("conf.json")
failOnError(err, "Config json not found. Make sure it is present.")
decoder := json.NewDecoder(file)
err = decoder.Decode(&configuration)
if err != nil {
fmt.Println("error:", err)
}
}
return configuration
}
func initDB() *sql.DB {
psqlInfo := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", configuration.DB.Host, configuration.DB.Port, configuration.DB.User, configuration.DB.Pass, configuration.DB.DbName)
db, err := sql.Open("postgres", psqlInfo)
if isHeroku {
db, err = sql.Open("postgres", os.Getenv("DATABASE_URL"))
}
failOnError(err, "Failed to open Postgres")
for i := 0; i < 5; i++ {
time.Sleep(time.Duration(i) * time.Second)
if err = db.Ping(); err == nil {
break
}
log.Println(err)
}
if err != nil {
failGracefully(err, "Failed to open Postgres")
}
err = db.Ping()
if err != nil {
failGracefully(err, "Failed to Ping Postgres")
} else {
fmt.Println("Connected to DB")
}
return db
}
func main() {
port := os.Getenv("PORT")
if port == "" {
port = ":8080"
} else {
port = ":" + port
}
fmt.Printf("Listening on port: %s\n", port)
fs := http.FileServer(http.Dir("dist"))
http.Handle("/", fs)
http.HandleFunc("/createRoom", createRoomHandler)
http.HandleFunc("/joinRoom", joinRoomHandler)
http.HandleFunc("/askQuestion", askQuestionHandler)
http.HandleFunc("/vote", voteHandler)
http.HandleFunc("/hide", hideHandler)
http.ListenAndServe(port, nil)
}