-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
315 lines (282 loc) · 10.2 KB
/
server.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
/**
* Created by arved on 06.03.15.
*/
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var equal = require('deep-equal');
var path = require('path');
var request = require('request');
var _ = require('underscore');
var mongoose = require('mongoose');
// Server keeps track of the last JSON get
var lastRequestJSON = [];
var apiAdresses = require('./lib/apiAdresses');
var constants = require('./lib/constants');
var testBets = require('./lib/test/testBets');
var matches = [];
var betsMatchMap = {};
var currentMatchDay;
var serverPort = process.argv[2] || 3000;
var fakeServerAddress = "http://localhost:3001";
mongoose.connect('mongodb://localhost/test');
// Connect with Mongo DB
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
console.log('Connected');
});
// Make betTable Schema
var betTable = new mongoose.Schema({
team1Goals: Number,
team2Goals: Number,
username: String,
userId: Number,
matchId: Number,
amount: Number,
index: Number,
// Adding the time of bet here (By Mongoose instead of sending from client side)
time: {
type: Date,
default: Date.now
}
});
var userTable = new mongoose.Schema({
username: String,
userId: Number
});
// Get betTable to call save or find function
var BetDB = mongoose.model('BetDB', betTable);
var UserDB = mongoose.model('UserDB', userTable);
// Universal callback function to debug everything on console
var callback = function (err, data) {
if (err)
return console.error(err);
else
console.log(data);
}
request(fakeServerAddress + apiAdresses.CURRENT_MATCHDAY, function (error, response, body) {
if (!error && response.statusCode == 200) {
var responseFromServer = JSON.parse(response.body);
console.log(responseFromServer.GroupName);
currentMatchDay = responseFromServer.GroupOrderId;
} else {
console.log(error);
console.log('Error connecting to fake server \n Unable to fetch current match day');
}
});
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.sendfile('index.html');
});
io.on('connection', function (socket) {
sendAllMatches(lastRequestJSON);
var resultsInterval = setInterval(function () {
request(fakeServerAddress + apiAdresses.MATCH_DATA_OF_DAY + currentMatchDay, function (error, response, body) {
// check if connected
if(typeof response === 'undefined'){
return
}
var listOfAllMatches = JSON.parse(response.body);
if (!_.isEqual(listOfAllMatches, lastRequestJSON)) {
// Calculate the order of bets for every match
var listOfAllBets = [];
lastRequestJSON = _.clone(listOfAllMatches);
listOfAllMatches.forEach(function (match) {
// get only the names, and the amount of money, they have won
var namesInOrder = _.map(calculateOrderOfBets(match), function (bet) {
return {
matchId: bet.matchId,
userId: bet.userId,
username: bet.username,
reward: bet.amount,
amount: bet.amount,
team1Goals: bet.team1Goals,
team2Goals: bet.team2Goals
};
});
if (namesInOrder.length > 0) {
namesInOrder[0].reward = 1.5 * namesInOrder[0].reward;
for (var i = 1; i < namesInOrder.length; i++) {
namesInOrder[i].reward = 0;
}
}
betsMatchMap[String(match.matchId)] = namesInOrder;
listOfAllBets.push(namesInOrder);
// console.log(listOfAllBets);
// TODO: Send listOfAllBets
match.bets = namesInOrder;
console.log("match Info Changed!");
io.emit("matchInfoChanged", match);
});
//console.log(lastRequestJSON);
}
});
}, constants.REFRESH_RATE_IN_SECONDS * 1000);
socket.on('login', function (user) {
UserDB.find({
username: user.username
}, function (err, data) {
if (data.length == 1) {
socket.emit('loggedIn', data[0]);
} else {
newUser = {
username: user.username,
userId: Math.floor((Math.random() * 100000) + 1)
};
var newAccount = new UserDB(newUser);
newAccount.save(function (err) {
if (err)
console.log(err);
else {
socket.emit('loggedIn', newUser);
}
});
}
});
});
/*
socket.on('getAllData', function(socket){
var allData = _.map(lastRequestJSON, _.clone);;
for(var i = 0; i < lastRequestJSON.length; i++){
allData[i].bets = betsMatchMap[String(allData[i].matchId)];
}
io.emit("send all matches", allData);
});
*/
socket.on('place bet', function (betDetails) {
if (validateBet(betDetails)) {
BetDB.find({
userId: betDetails.userId,
matchId: betDetails.matchId
}, function (err, data) {
if (data.length >= 1) {
//Send error to client
console.log('you already bet');
socket.emit('failureBet', {errorMessage : "You have already bet on this event!", index: betDetails.index});
} else {
var newBet = new BetDB(betDetails);
newBet.save(function (err) {
if (err)
console.log(err);
else {
addBet(betDetails);
io.emit('show bet', betDetails);
}
});
}
});
} else {
console.log('Invalidate');
// Send error to client
}
//addBet(betDetails);
});
socket.on('disconnect', function () {
clearInterval(resultsInterval);
});
});
// Function to validate bet JSON obtained from client side
function validateBet(betDetails) {
if (typeof betDetails.team1Goals === 'undefined'
|| typeof betDetails.team2Goals === 'undefined'
|| typeof betDetails.userId === 'undefined')
return false;
else {
if (typeof betDetails.team1Goals === 'number'
|| typeof betDetails.team2Goals === 'number'
|| typeof betDetails.userId === 'number') {
if (betDetails.team1Goals < 0 || betDetails.team2Goals < 0 || betDetails.userId < 0)
return false;
else
return true;
}
else
return false;
}
}
// Sends the list of matches and bets to client side
function sendAllMatches(lastRequestJSON) {
console.log("lastRequest"+JSON.stringify(lastRequestJSON));
var allData = _.clone(lastRequestJSON);
for(var i = 0; i < lastRequestJSON.length; i++){
allData[i].bets = betsMatchMap[String(allData[i].matchId)];
}
console.log(JSON.stringify(allData));
io.emit("send all matches", allData);
}
/**
*
* @param match: JSON of match
*/
function calculateOrderOfBets(match) {
// List of bets on this match
var bets = betsMatchMap[String(match.matchId)];
var currentMatchResult = match.MatchResults[0];
if (typeof bets === 'undefined') {
return [];
}
// List of bets for every possible outcome
var betsTeam1Win = [];
var betsTeam2Win = [];
var betsTied = [];
bets.forEach(function (bet) {
if (bet.team1Goals > bet.team2Goals) {
betsTeam1Win.push(bet);
} else if (bet.team1Goals === bet.team2Goals) {
betsTied.push(bet);
} else {
betsTeam2Win.push(bet);
}
});
// calculate the order
if (currentMatchResult.PointsTeam1 > currentMatchResult.PointsTeam2) {
return calculateBetsOrder(betsTeam1Win, currentMatchResult).concat(calculateBetsOrder(betsTeam2Win.concat(betsTied), currentMatchResult));
} else if (currentMatchResult.PointsTeam1 === currentMatchResult.PointsTeam2) {
return calculateBetsOrder(betsTied, currentMatchResult).concat(calculateBetsOrder(betsTeam2Win.concat(betsTeam1Win), currentMatchResult));
} else {
return calculateBetsOrder(betsTeam2Win, currentMatchResult).concat(calculateBetsOrder(betsTeam1Win.concat(betsTied), currentMatchResult));
}
}
function calculateBetsOrder(bets, currentMatchResult) {
// calculate the goal difference
var goalDiffMap = _.map(bets, function (bet) {
var diffGoals = Math.abs(bet.team1Goals - currentMatchResult.PointsTeam1) + Math.abs(bet.team2Goals - currentMatchResult.PointsTeam2);
return {
bet: bet,
diffGoals: diffGoals
};
});
var sortedGoalDiffMap = _.sortBy(goalDiffMap, 'diffGoals');
return _.map(sortedGoalDiffMap, function (obj) {
return obj.bet;
});
}
/**
* betsMatchApp provides an easy lookup for bets on match sorted by matchId
*
* @param New bet which should be added to betsMatchMao
*/
function addBet(bet) {
if (typeof betsMatchMap[String(bet.matchId)] === 'undefined') {
betsMatchMap[String(bet.matchId)] = [];
}
betsMatchMap[String(bet.matchId)].push(bet);
}
/**
* init method is called on startup of server
*/
function init() {
for (var i = 0; i < testBets.bets.length; i++) {
addBet(testBets.bets[i]);
}
BetDB.remove({}, function(err){
console.log("collection removed");
});
console.log(JSON.stringify(betsMatchMap));
}
http.listen(serverPort, function () {
console.log('listening on port:' + serverPort);
init();
});