-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
3011 lines (2876 loc) · 128 KB
/
app.js
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//Note: This project was created before I fully understood modules and proper project structure
//#region Setting Up Packages
const express = require("express"),
//#region Basic Requires
app = express(),
path = require("path"),
mongoose = require("mongoose"),
methodOverride = require("method-override"),
expressSanitizer = require("express-sanitizer"),
passport = require("passport"), //only if doing authentication
flash = require("connect-flash"), //used to send flash messages
localStrategy = require("passport-local"), //only if doing authentication
session = require('express-session'),
MongoStore = require('connect-mongo')(session),
//#endregion
//#region Model Requires
User = require("./models/user"),
Problem = require("./models/problem"),
Deal = require("./models/deal"),
Game = require("./models/game"),
GameIncomplete = require("./models/gameIncomplete"),
//#endregion
//#region Socket.io Requires
http = require("http"), //creating http instance
server = http.createServer(app), //creating a server instance to pass to io
socketio = require("socket.io"), //passing server instance to io
io = socketio(server), //creating io instance from server
// io = socketio(server, {pingTimeout: 30000}), //creating io instance from server
//#endregion
//#region Routes
playRoutes = require("./routes/play"),
siteRoutes = require("./routes/site"),
miscRoutes = require("./routes/misc"),
//#endregion
// stripe = require('stripe')(process.env.STRIPE_SECRET_KEY_HERE), //used for payment processing; probably would go inside a route
//#region Helper Requires
userUtils = require("./helpers/users"),
roomUtils = require("./helpers/rooms"),
gameUtils = require("./helpers/games"),
helpers = require("./helpers/helpers"),
autoPlayCard = require("./helpers/autoPlay"),
constants = require("./helpers/constants"),
seed = require("./helpers/seed");
//#endregion
seed.run(); //TODO: CAN REMOVE THIS WHEN DEPLOYING
require('dotenv').config();
//#region Starting Server to Listen
const port = process.env.PORT || 3009;
server.listen(port, process.env.IP, function () {
console.log(`Starting server port ${port}...`);
});
//#endregion
//#region Configuring Express
//tell express to serve files in 'public' (put main.css and main.js in here)
app.use(express.static(path.join(__dirname, "public")));
app.set("view engine", "ejs"); //default extension to use for res.render calls
app.use(methodOverride("_method"));
//in version 4.17.1 and above of express, bodyParser is part of express.
app.use(express.urlencoded({ extended: true }));
app.use(expressSanitizer());
app.use(flash());
app.use(express.json());
//#endregion
//#region Authentication Setup
app.use(
session({
secret:
"#(kdjf9ndKDJ#JkmDfJdUH@)k**3KDmLS(#ldkd.zldk{}{201ndnw93uKSDKEIDKVMC<EPZKMCMCNDJ",
resave: false,
saveUninitialized: false,
store: new MongoStore({ mongooseConnection: mongoose.connection })
})
);
app.use(passport.initialize());
app.use(passport.session());
passport.use(new localStrategy(User.authenticate()));
//encodes User class/model and puts into session
passport.serializeUser(User.serializeUser());
//decodes User class/model and removes from session
passport.deserializeUser(User.deserializeUser());
//#endregion
//#region Storing global variables
app.use(function (req, res, next) {
//'res.locals' is where vars accessible to all templates are stored
//add as many 'res.locals.var' as you want
//put at end of setup section otherwise it won't grab passport-added user info
res.locals.currentUser = req.user;
res.locals.errorMessage = req.flash("error");
res.locals.successMessage = req.flash("success");
next();
});
//#endregion
//importing router routes from '/router'; ADD REQUIRE ABOVE (./routes/name.js)
app.use(playRoutes);
app.use(miscRoutes);
app.use(siteRoutes); //this is where the * and other routes not related to models go; must come last
app.use((req, res) => {
res.render('404', {page: req.originalUrl});
})
app.use(function (err, req, res, next ) {
//Custom error handler
const {status = 500, message = 'Something went wrong...'} = err;
res.status(status).send(message);
// next(err);
});
app.set('hasSentTheme', {});
//#region Mongoose Setup
mongoose.set("useFindAndModify", false);
const dbName = "Bridge";
const portNumber = 27017;
let mongoDbURL = `mongodb+srv://admin:${process.env.mongoDBPassword}@cluster0.3trbv.mongodb.net/${dbName}?retryWrites=true&w=majority`;
// app.use(express({
// store: new MongoStore({ url: mongoDbURL})
// }));
if (constants.mode === constants.modes.playing) mongoDbURL = `mongodb+srv://admin:${process.env.mongoDBPassword}@cluster0.3trbv.mongodb.net/${dbName}?retryWrites=true&w=majority`;
else mongoDbURL = "mongodb://localhost:" + portNumber + "/" + dbName
mongoose.connect(mongoDbURL, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log(`Connected to ${dbName} collection in MongoDB!`))
.catch((error) => console.log(error.message));
//#endregion
//#endregion
//#region Socket IO
io.on("connection", (socket) => {
//#region Handling Disconnections/Refreshes
socket.binary(false).on("disconnect", () => {
try {
console.log('disconnect event-------------------------------------');
const leavingUser = userUtils.getUser(socket.id);
const user = userUtils.removeUser(socket.id);
if (!user) return null;
if (leavingUser && user.status === constants.statuses.inLobby) {
resetLobby(leavingUser, user);
}
else if (leavingUser && user.status === constants.statuses.playingBridge) {
resetBridge(leavingUser);
}
} catch (error) {
console.error('error =', error);
}
});
function resetBridge(leavingUser) {
try {
console.log('resetBridge----------------------------------------------------');
const game = gameUtils.getGame(leavingUser.room);
if (!game) return;
gameUtils.removeUserFromReadyToContinue(leavingUser);
gameUtils.removeUserFromGame(leavingUser);
} catch (error) {
console.error('error =', error);
}
}
function resetLobby(leavingUser, user) {
try {
console.log('resetLobby----------------------------------------------------');
//#region remove user from all arrays in room
roomUtils.removeUserFromRoom(socket.binary(false).binary(false).id, leavingUser.room);
roomUtils.resetUsersReadyandWhoMadeSeatingChoices(leavingUser.room);
roomUtils.removeCompletionStates(socket.id, leavingUser.room);
roomUtils.resetArrays(leavingUser.room);
//#endregion
//#region hides seating in room if user left rather than refreshed
const roomBeingLeft = roomUtils.getRoom(leavingUser.room);
if (roomBeingLeft && roomBeingLeft.users.length < 4) {
socket.binary(false).to(leavingUser.room).emit("reset");
}
//#endregion
//#region Sending Other Clients Leave Msg and Updating roomUsers
if (!roomBeingLeft || !roomBeingLeft.users) return
const usersNeeded = 4 - roomBeingLeft.users.length;
io.binary(false).to(user.room).emit("message",formatMessage(
constants.botName,
`${user.username} has left the lobby. Mode set to 'Normal'. Seating available again when ${usersNeeded} more ${usersNeeded > 1 ? 'people join' : 'person joins'}.`
)
);
io.binary(false).to(user.room).emit("roomUsers", {
room: user.room,
users: userUtils.getUsernamesOfUsersInRoom(user.room),
});
//#endregion
//#region Reset Seating in all Clients in Room
const roomSeating = roomUtils.resetRoom(leavingUser.room);
if (roomSeating) {
io.binary(false).to(leavingUser.room).emit("refresh");
io.binary(false).to(leavingUser.room).emit("sendSeatingToClient", {
seating: roomSeating.seating,
});
socket.binary(false).to(leavingUser.room).emit("resetButtons");
}
//#endregion
} catch (error) {
console.error('error =', error);
}
}
//#endregion
//#region Room Stuff
socket.binary(false).on('startLobby', async ({username, room, password }) => {
try{
if (username === undefined || username === null || room === undefined || room === null) return null;
if (room.match(/[^a-zA-Z0-9]/) || !room.match(/[a-zA-Z]{1}[a-zA-Z0-9]{0,9}/)) return socket.binary(false).emit('invalidLobbyName', {room});
if (room.match(/\s+/i)) return null;
if (typeof password === 'string') password = password.trim();
const foundUser = await userUtils.isRegisteredUser(username);
if (!foundUser) {
return socket.binary(false).emit("userNotFound", { username, room });
}
//#region Rejoining a Game in Session
const game = gameUtils.getGame(room);
if (game) {
for (const direction in game.seating) {
if (game.seating.hasOwnProperty(direction)) {
const usernameInSeating = game.seating[direction];
if (usernameInSeating === username) {
console.log('password =', password);
console.log('game.room.password =', game.room.password);
if (password === game.room.password || game.room.password.trim() === '') {
const spot = direction;
const socketId = game.originalSocketIds[username];
return socket.binary(false).emit('rejoinGame', {username, room, password, spot, socketId});
}
else {
return socket.binary(false).emit('incorrectPassword', {username, room});
}
}
}
}
}
//#endregion
//#region Joining a Lobby if It exists is insession otherwise create
//#region Creating a New Lobby if Empty Lobby Exists
let roomToJoin = roomUtils.getRoom(room);
if (roomToJoin && roomToJoin.users && roomToJoin.users.length <= 0) {
roomToJoin = roomUtils.roomCreation(socket.id, roomToJoin.name, roomToJoin.password);
}
//#endregion
if (roomToJoin) {
const usersNeeded = 4 - (roomToJoin.users.length + 1);
const roomPassword = roomUtils.getRoomPassword(room);
if (usersNeeded < 0) {
socket.binary(false).emit("roomFull", { username, room });
}
else if ((typeof password === 'string' && password.trim() === roomPassword) || roomPassword === '') {
console.log('joining with password =', password);
const user = await userUtils.userJoin(socket.id, username, room);
if (user) {
//#region Join Room and Send Users in Room to Clients
roomUtils.joinRoom(socket.id, room);
sendValuesToClients(roomToJoin, socket.id);
socket.binary(false).join(room);
socket.binary(false).emit("joinLobby");
socket.binary(false).emit(
"message",
formatMessage(
constants.botName,
`Welcome to A#Maj Bridge ${user.username}! ${
usersNeeded > 0
? `When ${usersNeeded + 1} ${usersNeeded === 1 ? ' more person joins the lobby,' : ' more people join the lobby,'} you may begin the game.`
: constants.fullRoomMsg
}`
)
);
socket.binary(false).to(room).emit(
"message",
formatMessage(constants.botName, `${user.username} has joined the lobby.`)
);
const usernames = userUtils.getUsernamesOfUsersInRoom(room);
io.binary(false).in(room).emit("roomUsers", {
room,
users: usernames,
});
//#endregion
//#region Check Ready To Start
if (usersNeeded === 0) {
try {
// if (roomToJoin.shouldCountHonors) setBiddingValue({room, value: true, valueChanged: 'shouldCountHonors', shouldHide: false})
const incompleteGame = await findGameIncomplete(usernames);
socket.binary(false).in(room).emit("message",formatMessage(constants.botName, constants.fullRoomMsg));
io.binary(false).to(room).emit("showSeating", {isIncompleteGame: !!incompleteGame, immediatelyLoadSavedGame: constants.immediatelyLoadSavedGame, shouldCountHonors: roomToJoin.shouldCountHonors});
io.binary(false).in(room).emit("message",formatMessage(constants.botName, constants.getIncompleteGameFoundMsg(new Date(incompleteGame.startDate))));
} catch (error) {
console.log('error getting Incomplete Game------------------------------------------------');
console.log(error);
}
} else {
socket.binary(false).to(room).emit(
"message",
formatMessage(
constants.botName,
`You will be able to start when ${usersNeeded} more ${usersNeeded === 1 ? 'person joins.' : 'people join.'}`
)
);
}
//#endregion
}
else {
socket.binary(false).emit("userNotFound", {username, room});
}
}
else {
socket.binary(false).emit("incorrectPassword", { username, room });
}
}
else {
roomUtils.roomCreation(socket.id, room, password);
socket.binary(false).emit("joinLobby");
roomUtils.removeUserFromRoom(socket.id, room);
const publicRoomCount = roomUtils.getPublicRoomCount();
if (publicRoomCount < constants.maxRoomsToLoad) {
const connectedClients = Object.keys(io.of('/').clients().connected);
for (let i = 0; i < connectedClients.length; i++) {
const socketId = connectedClients[i];
sendRoomsToClientEmitterEvent(socketId);
}
}
}
//#endregion
} catch (error) {
console.error('error =', error);
}
});
socket.binary(false).on("getRooms", () => {
try {
console.log('getRooms event-------------------------------------');
sendRoomsToClientEmitterEvent();
} catch (error) {
console.error('error =', error);
}
});
socket.binary(false).on("chatMessage", ({ username, room, msg }) => {
try{
console.log('chatMessage event-------------------------------------');
let members = null;
if (io.sockets.adapter.rooms[room]) {
members = io.sockets.adapter.rooms[room].sockets;
}
if (members) {
const users = userUtils.getRoomUsers(room);
let userId = null;
//get user id from username
for (let i = 0; i < users.length; i++) {
const user = users[i];
if (user.username === username) {
userId = user.socketId;
break;
}
}
//only send msg if userId is in room
for (const key in members) {
if (members.hasOwnProperty(key)) {
if (key === userId) {
io.binary(false).to(room).emit("message", formatMessage(username, msg));
break;
}
}
}
}
} catch (error) {
console.error('error =', error);
}
});
socket.binary(false).on("roomLeave", ({ room }) => {
try {
console.log('roomLeave event-------------------------------------');
//check if room is empty and removes if true
roomUtils.removeUserSeatingChoice(socket.id, room);
const removedUser = roomUtils.removeUserFromRoom(socket.id, room);
let usersInRoom = null;
if (io.sockets.adapter.rooms[room]) {
usersInRoom = io.sockets.adapter.rooms[room].length - 1;
} else {
usersInRoom = 0;
}
if (usersInRoom <= 0) {
//delete room from rooms
roomUtils.removeRoom(room);
}
socket.binary(false).to(room).emit("resetSeating");
} catch (error) {
console.error('error =', error);
}
});
function sendRoomsToClientEmitterEvent(socketId) {
try {
console.log('sendRoomsToClientEmitterEvent----------------------------------------------------');
if (socketId) return io.binary(false).emit('sendRoomsToClient', {
rooms: roomUtils.getTenPublicRooms(),
gamesInSession: gameUtils.gamesInSession,
});
socket.binary(false).emit("sendRoomsToClient", {
rooms: roomUtils.getTenPublicRooms(),
gamesInSession: gameUtils.gamesInSession,
});
} catch (error) {
console.error('error =', error);
}
}
function removeSpaces(string) {
try {
if (string === undefined || string === null) return '';
return string.replace(' ', '_');
} catch (error) {
console.error('error =', error);
}
}
function sendValuesToClients(room, joiningSocketId) {
try {
if (room === undefined || room === null) return null;
const userObj = userUtils.getUser(joiningSocketId);
const setHonorsAutomatically = userObj.preferences.setHonorsAutomatically;
if (setHonorsAutomatically === true) room.shouldCountHonors = true;
console.log('room.shouldCountHonors =', room.shouldCountHonors);
const values = {
biddingTimerDurationValue: room.biddingTimerDurationValue,
cardPlayTimerDurationValue: room.cardPlayTimerDurationValue,
shouldCountHonors: setHonorsAutomatically === true ? true : room.shouldCountHonors,
northSouthAbove: room.northSouthAbove,
northSouthBelow: room.northSouthBelow,
northSouthVulnerable: room.northSouthVulnerable,
eastWestAbove: room.eastWestAbove,
eastWestBelow: room.eastWestBelow,
eastWestVulnerable: room.eastWestVulnerable,
dealer: room.dealer,
continueFromIncomplete: room.continueFromIncomplete,
}
io.binary(false).in(room).emit('sendValuesToClient', {values});
io.binary(false).to(joiningSocketId).emit('sendValuesToClient', {values});
} catch (error) {
console.error('error =', error);
}
}
//#endregion
//#region Seating Arrangment Stuff
socket.binary(false).on("getSeating", ({ room }) => {
try{
console.log('getSeating event-------------------------------------');
//get seating for room
socket.binary(false).emit("sendSeatingToClient", { seating: roomUtils.getSeating(room) });
} catch (error) {
console.error('error =', error);
}
});
socket.binary(false).on("resetSpot", ({ room, spot }) => {
try {
console.log('resetSpot event-------------------------------------');
roomUtils.removeUserSeatingChoice(socket.id, room);
const updatedSeating = roomUtils.resetSeatingSpot(room, spot);
console.log('updatedSeating =', updatedSeating);
if (updatedSeating !== -1) {
io.binary(false).to(room).emit("resetStartButton");
io.binary(false).to(room).emit("sendSeatingToClient", { seating: updatedSeating });
}
} catch (error) {
console.error('error =', error);
}
});
socket.binary(false).on("chooseSpot", ({ username, room, spot, desiredSpot }) => {
try {
console.log('chooseSpot event-------------------------------------');
roomUtils.setUserSeatingChoice(socket.id, room);
const roomWhereSpotChosen = roomUtils.setSeatingSpot(username, room, spot);
if (desiredSpot !== "") {
roomUtils.resetSeatingSpots(username, room, spot, desiredSpot);
}
socket.binary(false).emit("resetDesiredSpot", { value: spot });
io.binary(false).to(room).emit("sendSeatingToClient", {
seating: roomUtils.getSeating(room),
});
//#region enable start button if the 4 users in the room are the users that have picked spots
if (roomWhereSpotChosen !== -1) {
if (roomWhereSpotChosen.usersWhoMadeSeatingChoice.length === 4) {
shouldEnableStart = true;
for (let i = 0; i < roomWhereSpotChosen.users.length; i++) {
const userInRoom = roomWhereSpotChosen.users[i];
if (
!roomWhereSpotChosen.usersWhoMadeSeatingChoice.includes(userInRoom)
) {
shouldEnableStart = false;
break;
}
}
if (shouldEnableStart) {
io.binary(false).to(room).emit("enableStartButton");
}
}
}
else {
gameUtils.removeGame(room);
return socket.binary(false).emit("notInSession", { room, type: "lobby", code: "2" });
}
//#endregion
} catch (error) {
console.error('error =', error);
}
});
socket.binary(false).on("startButtonPress", ({room, username}) => {
try {
console.log('startButtonPress event-------------------------------------');
socket.binary(false).emit("message",formatMessage(constants.botName, `You have pressed start.`));
socket.binary(false).to(room).emit('message', formatMessage(constants.botName, `${username} has pressed start.`))
socket.binary(false).to(room).emit('sendReadyToStart', {username});
const roomWhereStartButtonPressed = roomUtils.setUserReady(socket.id, room);
if (roomWhereStartButtonPressed !== -1) {
if (roomWhereStartButtonPressed.usersReady.length === 4) {
const seatingLegit = checkSeating(roomWhereStartButtonPressed);
if (typeof seatingLegit === 'object') roomWhereStartButtonPressed.seating = seatingLegit;
const scoresLegit = checkScoring(roomWhereStartButtonPressed);
if (seatingLegit && scoresLegit) {
startBidding(room, roomWhereStartButtonPressed);
}
else if (!seatingLegit) {
emitReloadLobby(roomWhereStartButtonPressed.name, `There was an issue with the seating arrangement. Please try again.`)
}
else if (!scoresLegit) {
emitReloadLobby(roomWhereStartButtonPressed.name, `There was an issue with the starting scores. Please try again.`)
}
}
} else {
gameUtils.removeGame(room);
return socket.binary(false).emit("notInSession", { room, type: "lobby", code: "3" });
}
} catch (error) {
console.error('error =', error);
}
});
function emitReloadLobby(roomName, msg){
try {
console.log('emitReloadLobby----------------------------------------------------');
io.binary(false).in(roomName).emit("reload", formatMessage("Error Bot", msg));
} catch (error) {
console.error('error =', error);
}
}
socket.binary(false).on('seatingButtonPress', ({room}) => {
try {
console.log('seatingButtonPress event-------------------------------------');
roomUtils.resetArrays(room);
socket.binary(false).to(room).emit('toggleSeatingButtonEvent');
io.binary(false).to(room).emit("sendSeatingToClient", { seating: constants.getDefaultSeating() });
io.binary(false).to(room).emit("refresh");
} catch (error) {
console.error('error =', error);
}
});
socket.binary(false).on('biddingValueChange', ({room, value, valueChanged, shouldHide}) => {
setBiddingValue({room, value, valueChanged, shouldHide})
});
function setBiddingValue({room, value, valueChanged, shouldHide}) {
try {
console.log('biddingValueChange event-------------------------------------');
roomUtils.resetUsersReadyandWhoMadeSeatingChoices(room);
const roomToGet = roomUtils.getRoom(room);
if (!roomToGet) return null;
value = convertToBoolean(value);
const currentValue = JSON.parse(JSON.stringify(roomToGet[valueChanged]));
const startValueSent = value;
if (!isNaN(parseInt(value)) && typeof parseInt(value) === 'number' && typeof(value) === 'string' && !value.match(/none/i)) roomToGet[valueChanged] = parseInt(value);
else roomToGet[valueChanged] = value;
console.log('roomToGet =', roomToGet);
io.binary(false).in(room).emit('timerValueUpdate', {value, valueChanged, shouldHide});
let valueChangedMsg = '';
let unit = 'seconds';
// console.log('valueChanged =', valueChanged);
switch (valueChanged.toLowerCase()) {
case 'biddingtimerdurationvalue':
valueChangedMsg = 'bidding timer value';
break;
case 'cardplaytimerdurationvalue':
valueChangedMsg = 'play timer value';
break;
case 'northsouthabove':
valueChangedMsg = 'NS above score';
unit = 'points';
break;
case 'northsouthbelow':
valueChangedMsg = 'NS below score';
unit = 'points';
break;
case 'northsouthvulnerable':
valueChangedMsg = 'NS vulnerable status';
value = 'Yes';
unit = '';
break;
case 'eastwestabove':
valueChangedMsg = 'EW above score';
unit = 'points';
break;
case 'eastwestbelow':
valueChangedMsg = 'EW below score';
unit = 'points';
break;
case 'eastwestvulnerable':
valueChangedMsg = 'EW vulnerable status';
value = 'Yes';
unit = '';
break;
case 'dealer':
valueChangedMsg = 'dealer';
unit = '';
value = `'${value}'`;
break;
case 'shouldcounthonors':
valueChangedMsg = "'Count Honors' state";
unit = '';
value = `'${value ? "Yes" : "No"}'`;
break;
case 'continuefromincomplete':
valueChangedMsg = "'Load Incomplete Game' state";
unit = '';
value = `'${value ? "Yes" : "No"}'`;
break;
}
// console.log('currentValue =', currentValue);
// console.log('value =', value);
// console.log('startValueSent =', startValueSent);
if ((typeof currentValue === 'number' && parseInt(currentValue) !== parseInt(value))
|| (value ==='none' && currentValue !== value)
|| (valueChanged === 'shouldCountHonors' && startValueSent !== currentValue)
|| valueChanged === 'continueFromIncomplete'
) {
io.binary(false).in(room).emit("message",
formatMessage(constants.botName, `'${userUtils.getUser(socket.id).username}' changed the ${valueChangedMsg} to ${value} ${unit}.`));
}
} catch (error) {
console.error('error =', error);
}
}
//#endregion
//#region Bidding Stuff
//#region Triggered On Client Load of Bid.ejs
socket.binary(false).on('getClientPreferences', async ({username}) => {
console.log('getClientPreferences event-------------------------------------');
if (!username) return socket.binary(false).emit("notInSession", { room, type: "game", code: "6.5" });
try {
const userObj = await User.findOne({username});
socket.binary(false).emit('sendPreferencesToClient', {preferences: userObj.preferences});
} catch (error) {
socket.emit('userNotFound', {username, room});
}
});
socket.binary(false).on("updateSocketIdAfterRedirect", ({ username, room }) => {
try {
console.log('updateSocketIdAfterRedirect event-------------------------------------');
const game = gameUtils.getGame(room);
if (!checkInSession(game, room, 'game', '22.5', socket.id)) return;
socket.binary(false).join(room);
for (let i = 0; i < game.userObjs.length; i++) {
const userObj = game.userObjs[i];
if (username && userObj.username === username){
userObj.status = constants.statuses.playingBridge;
userObj.socketId = socket.id;
userUtils.addUserObj(userObj);
if(game && game.users) game.users[username] = userObj.socketId;
break;
}
}
const lastDeal = gameUtils.getLastDeal(game);
if (lastDeal.agreeWithClaim.claimAmount !== null) {
lastDeal.agreeWithClaim = constants.getNewAgreeWithClaim();
io.binary(false).in(game.name).emit('closeClaim', {isAccepted: false});
}
} catch (error) {
console.error('error =', error);
}
});
socket.binary(false).on("getContractsFromServer", () => {
console.log('getContractsFromServer event-------------------------------------');
try {
socket.binary(false).emit("sendContractsToClient", {
contractsFromServer: constants.contracts,
});
} catch (error) {
console.error('error =', error);
}
});
socket.binary(false).on("getHand", ({ username, room, originalSocketId}) => {
try {
console.log('getHand event-------------------------------------');
const game = gameUtils.getGame(room);
if (!checkInSession(game, room, 'game', '23.5', socket.id)) return;
let socketIdInGame;
if (game.users && game.users[username]) socketIdInGame = game.users[username];
else {
for (let i = 0; i < game.userObjs.length; i++) {
const userObj = game.userObjs[i];
if (userObj.username === username) socketIdInGame = userObj.socketId;
}
}
if (game) {
return socket.binary(false).emit("sendHandToClient", {
handFromServer: gameUtils.getHandForSocketID(game, game.originalSocketIds[username]),
dealer: gameUtils.getDealer(game),
});
}
else {
return socket.binary(false).emit("handNotFound", { username, room });
}
} catch (error) {
console.error('error =', error);
}
});
socket.binary(false).on('getScoring', ({room}) => {
try {
console.log('getScoring event-------------------------------------');
const game = gameUtils.getGame(room);
if (!checkInSession(game, room, 'game', '7', socket.id)) return;
socket.binary(false).emit('sendScoringToClient', {scoring: gameUtils.getScoring(game)});
} catch (error) {
console.error('error =', error);
}
});
socket.binary(false).on("getGameState", ({username, room, originalSocketId }) => {
try {
console.log('getGameState event-------------------------------------');
const game = gameUtils.getGame(room);
if (game) {
console.log('game.gameState =', game.gameState);
if (game.gameState === constants.gameStates.bidding || game.gameState === constants.gameStates.waitingToContinueToPlaying) {
loadBidding(game, socket.id);
delete game.usersReadyToContinue[username];
emitUsersReadyToContinue(game);
}
else if (game.gameState === constants.gameStates.playing) {
loadPlaying(game, socket.id, originalSocketId);
game.usersReadyToContinue = {};
}
else if (game.gameState === constants.gameStates.dealSummary) {
console.log('dealSummary refresh------------------------------------------------------');
socket.binary(false).emit('sendSeatingToClientInBid', {seating: game.seating, dealer: gameUtils.getDealer(game), biddingTimerDurationValue: game.room.biddingTimerDurationValue});
emitDealComplete({game, socketId: socket.id});
emitUsersReadyToContinue(game);
}
else if (game.isGameOver) {
sendGameOver(game, true);
}
}
else {
gameUtils.removeGame(room);
return socket.binary(false).emit("notInSession", { room, type: "game", code: "8" });
}
} catch (error) {
console.error('error =', error);
}
});
//#endregion
socket.binary(false).on("sendBidToServer", async ({ username, bid, room, spot, imgHTML }) => {
try {
console.log('sendBidToServer event-------------------------------------');
//#region Initialization
const contracts = constants.contracts;
let game = gameUtils.getGame(room);
const userMakingBid = userUtils.getUser(socket.id);
if (!game || !userMakingBid || !contracts) {
gameUtils.removeGame(room);
return socket.binary(false).emit("notInSession", { room, type: "game", code: "9" });
}
if (game.gameState === constants.gameStates.playing) return null;
if (userMakingBid.username !== gameUtils.getNextBidder(game)) socket.binary(false).emit("cheatPrevention", { type: "invalidBidder" })
const indexOfBid = bid.match(/double/i) || bid.toLowerCase() === "pass" ? -1 : contracts.findIndex((contract) => contract === bid);
if (indexOfBid < -1 || indexOfBid > 34 || imgHTML.match(/script/i) || imgHTML.match(/style/i)) return socket.binary(false).emit("cheatPrevention", { type: "invalidBid" });
//#endregion
//#region Getting indexOfCurrentHighBid
let indexOfCurrentHighBid;
const lastBid = gameUtils.getLastContractBid(game);
if (lastBid) {
indexOfCurrentHighBid = contracts.findIndex(
(contract) => contract === lastBid
);
} else {
indexOfCurrentHighBid = -1;
}
//#endregion
//#region Checking Bid Against Current High Bid and Responding
const nextBidder = gameUtils.getNextBidder(game);
if (((userMakingBid && (indexOfBid > indexOfCurrentHighBid || indexOfBid === -1))) && userMakingBid.username === nextBidder) {
const isValidBid = getIsValidBid(game, bid, username);
if (isValidBid === true) {
gameUtils.makeBid(game, bid);
saveGameIncompleteBidding(game);
io.binary(false).in(room).emit("updateOtherClientsAfterBid", {
bid: gameUtils.getLastBid(game),
nextBidder: gameUtils.getNextBidder(game),
imgHTML,
});
if (gameUtils.dealIsABust(game)) {
//redeal hands and send hand to each player
const spammingFound = gameUtils.checkForSpamming(game);
if (spammingFound) {
io.binary(false).in(game.name).emit('notInSession', {room, type: "spamming", code: "10"});
return gameUtils.removeGame(game.name);
}
gameUtils.createNewDeal(game);
const userObjs = userUtils.getRoomUsers(game.name);
const dealer = gameUtils.getDealer(game);
io.binary(false).in(game.name).emit("newDeal", {
dealer,
contractsFromServer: constants.contracts,
});
for (let i = 0; i < userObjs.length; i++) {
//updating clients with new hand and dealer
const userObj = userObjs[i];
io.binary(false).to(userObj.socketId).emit("sendHandToClient", {
handFromServer: gameUtils.getHandForSocketID(game, userObj.socketId),
});
io.binary(false).to(userObj.socketId).emit("sendSeatingToClient", {
seating: null,
dealer: gameUtils.getDealer(game),
});
}
game.redealCount += 1;
game.room.usernameOfCurrentBidder = dealer;
return saveGameIncompleteBidding(game);
}
else if (gameUtils.isbiddingFinished(game)) {
gameUtils.setContractAndDeclarer(game);
io.binary(false).in(game.name).emit('showContinueButton', {seating: null, exposedHandName: gameUtils.getExposedHandName(game)});
console.log('setting game state to waitingToContinueToPlaying------------------------------------------------');
game.gameState = constants.gameStates.waitingToContinueToPlaying;
saveGameIncompleteBidding(game, true);
}
else {
const bids = gameUtils.getLastDeal(game).bids;
io.binary(false).in(game.name).emit("disableUpToLastBid", {bids});
io.binary(false).in(game.name).emit("validBid");
sendIsAllowedToMakeBid(userUtils.getUserId(gameUtils.getNextBidder(game)), game, bids);
game.room.usernameOfCurrentBidder = nextBidder;
}
}
else {
socket.binary(false).emit("cheatPrevention", { type: "invalidBid" });
}
}
else if (indexOfBid <= indexOfCurrentHighBid) {
socket.binary(false).emit("cheatPrevention", { type: "invalidBid" });
}
//#endregion
} catch (error) {
console.error('error =', error);
}
});
socket.binary(false).on('getBidding', ({room}) => {
try {
console.log('getBidding event-------------------------------------');
const lastDeal = gameUtils.getLastDeal(room);
if (!lastDeal) return [];
socket.binary(false).emit('sendBiddingToClient', {bidding: lastDeal.bids, shouldResetTable: false});
} catch (error) {
console.error('error =', error);
}
});
socket.binary(false).on('readyToContinueToPlaying', ({username, room}) => {
try {
console.log('readyToContinueToPlaying------------------------------------------------');
if (username === undefined || username === null || room === undefined || room === null) return;
const game = gameUtils.getGame(room);
if (!checkInSession(game, room, 'game', '12.5', socket.id)) return;
if (game.usersReadyToContinue && game.usersReadyToContinue[username] === true) return;
if (game.usersReadyToContinue) {
const exposedHandname = gameUtils.getExposedHandName(game);
game.usersReadyToContinue[exposedHandname] = true;
}
const usersInRoom = Object.values(game.seating);
if (game.usersReadyToContinue && usersInRoom.indexOf(username) > -1) game.usersReadyToContinue[username] = true;
emitUsersReadyToContinue(game);
if (Object.size(game.usersReadyToContinue) !== 4) return;
if (Object.size(game.usersReadyToContinue) > 4) {
game.usersReadyToContinue = {};
return io.binary(false).in(game.name).emit('resetContinueToPlayingButton');
}
for (let i = 0; i < usersInRoom.length; i++) {
const userInRoom = usersInRoom[i];
if (game.usersReadyToContinue[userInRoom] === null) return;
}
startPlaying(game);
game.usersReadyToContinue = {};
saveGameIncompletePlaying(game);
} catch (error) {
console.error('error =', error);
}
});
socket.binary(false).on('timesUpBidding', ({room}) => {
try {
console.log('timesUpBidding event-------------------------------------');
//TODO: need to finish
const game = gameUtils.getGame(room);
if (!game || !game.room) return null;
game.room.timesUpComplete = true;
game.room.usernameOfCurrentPlayer = null;
} catch (error) {
console.error('error =', error);
}
});
function startNewGame(roomName, room, usersInRoom) {
try {
console.log('startNewGame------------------------------------------------');
const newGame = gameUtils.createNewGame(room);
if (!checkInSession(newGame, roomName, 'game', '4', socket.id)) return;
gameUtils.createNewDeal(newGame, true);
newGame.userObjs = JSON.parse(JSON.stringify(usersInRoom));
for (let i = 0; i < newGame.userObjs.length; i++) {
const userObj = newGame.userObjs[i];
newGame.roundWinSounds[userObj.username] = userObj.preferences.sound.roundWon;
}
console.log('newGame.roundWinSounds =', newGame.roundWinSounds);
createGameIncompleteDocumentInMongoDB(newGame);
} catch (error) {
console.error('error =', error);
}
}
async function startBidding(roomName, room) {
try {
console.log('startBidding----------------------------------------------------');
const usersInRoom = userUtils.getRoomUsers(roomName);
//#region Creating New Game of Loading Incomplete One
if (room) {
if (room.continueFromIncomplete === true) {
const usernames = [];
for (let i = 0; i < usersInRoom.length; i++) {
const userObj = usersInRoom[i];
usernames.push(userObj.username);
}
//#region Loading gameIncomplete
try {
const incompleteGame = await findGameIncomplete(usernames);
if (incompleteGame.name !== roomName) {
const oldName = incompleteGame.name;
incompleteGame.name = roomName;
incompleteGame.room.name = roomName;
const incompleteRoom = incompleteGame.room;
await GameIncomplete.updateOne({
name: oldName,
seating: {
north: incompleteGame.seating.north,
south: incompleteGame.seating.south,
east: incompleteGame.seating.east,
west: incompleteGame.seating.west,
},
}, {
name: roomName,
room: incompleteRoom,
});
}
updateUserObjs(incompleteGame, roomName);
updateUserPreferences(incompleteGame);
if (incompleteGame && !incompleteGame.users) incompleteGame.users = {};
if (incompleteGame && !incompleteGame.usersReadyToContinue) incompleteGame.usersReadyToContinue = {};
if (incompleteGame) {
if (gameUtils.gamesInSession.includes(incompleteGame.name)) incompleteGame.name += '-2';
gameUtils.games[incompleteGame.name] = incompleteGame;
gameUtils.gamesInSession.push(incompleteGame.name);
}
else startNewGame (roomName, room, usersInRoom);
} catch (error) {
console.log('error getting IncompleteGame in startbidding------------------------------------------------');
console.log(error);
}
//#endregion
}
else {