-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraphManager.js
More file actions
633 lines (491 loc) · 18.7 KB
/
graphManager.js
File metadata and controls
633 lines (491 loc) · 18.7 KB
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
var util = require('util');
// Models to interface with Mongo DataBase
var userModel = require("./models/userModel.js").userModel;
var gameModel = require("./models/gameModel.js").gameModel;
// staticManager to convert Champ_ID to Champ_Name
var staticManager = require("./staticApiManager.js");
// Needs to be removed, simulatenous requests will screw this up
var offSet;
// Moment to modify dates to specific timezones
var moment = require('moment-timezone');
/**
* getGraph() passes to specific graph Function
* based on graphOptions.graphType
*
* @param {String} userName The name of the user in lowercase
* @param {String} serverName The server the user is on
* @param {Object} graphOption Contains user's time offSet and holds start and end date's, generated on client's timezone for 7 Day line & pie
* @param {Object} responder So we can send data back to client who made req
*/
var getGraph = function getGraph(userName, serverName, graphOptions,
responder) {
// Set offset
offSet = graphOptions.userOffSet;
if (graphOptions.graphType == "today") {
getUserThenGraph(userName, serverName, graphOptions, todayGraph,
responder);
} else if (graphOptions.graphType == "championDaysGraph") {
getUserThenGraph(userName, serverName, graphOptions, championDaysGraph, responder);
} else if (graphOptions.graphType == "daysGraph") {
getUserThenGraph(userName, serverName, graphOptions, daysGraph, responder);
} else if (graphOptions.graphType == "allGraph") {
getUserThenGraph(userName, serverName, graphOptions, allGraph, responder);
} else if (graphOptions.graphType == "yearGraph") {
getUserThenGraph(userName, serverName, graphOptions, yearGraph, responder);
} else if (graphOptions.graphType == "positionPieGraph") {
getUserThenGraph(userName, serverName, graphOptions, positionPieGraph, responder);
} else {
responder.status(404).send(
"We have an error m8 that graphType doesn't exist");
}
}
/**
* getUserThenGraph() gets user data from database
* Based on graphFunctionName passes userData to specified graph function
*
* @param {String} userName The name of the user in lowercase
* @param {String} serverName The server the user is on
* @param {Object} graphOption Contains user's time offSet and holds start and end date's, generated on client's timezone for 7 Day line & pie
* @param {Object} responder So we can send data back to client who made req
*/
function getUserThenGraph(userName, serverName, graphOptions, graphFunctionName, responder) {
// Query mongodb for user with name and server
userModel.findOne({"summonerName":userName, "server":serverName}).exec(function (err, userData) {
if (err) responder.status(500).send("Error: graphManager+getUser -" + err);
if(userData !== null){
// User Found
// Check if user has some data for graphing (25 is default lastMatchID)
// When updating a users game lastMatchId is updated to a much higher number
if(userData.lastMatchId[0] > 25){
graphFunctionName(null, userData, graphOptions, responder);
} else {
// Let client know that this user is new, attempt to re-request data
responder.send("User found, but no data found (Please wait)");
}
} else {
// Invalid summonerName given
responder.status(404).send("Adding new user, please wait");
}
});
}
/**
* championDaysGraph() gets games for user
* Between dates given
* Passes gameData found to analyzeChampionDaysGraph()
*
* @param {String} err For error information ???
* @param {Object} userData Contains _id
* @param {Object} responder So we can send data back to client who made req
**/
function championDaysGraph(err, userData, graphOptions, responder){
var now = moment().utcOffset(graphOptions.userOffSet*-1);
// Date's made by clientside, already in there timezone
var startDate = graphOptions.startDate;
var endDate = graphOptions.endDate;
// Query Mongo DB
gameModel.find(
{$and: [{"userId":userData._id},
{dateTime: {$gt: startDate, $lt: endDate}}]
}).sort(
{dateTime: -1}
).exec(function (err, res) {
if(err) responder.status(500).send("Error - " + err);
// Pass found games to analysis function
analyzeChampionDaysGraph(null, res, userData, responder);
});
}
/**
* analyzeChampionDaysGraph() Calculates how many times a given user has
* played a champion in the time period specified in graphOptions
* Usually 7 Days
*
* @param {String} err Contains
* @param {Array} gameData Contains multiple game's each with data about the
* game, (DateGame, GameDuration, Match_ID, ect (See gameModel))
* @param {Object} userData Details about this user (_id,
* summonerId, summonerName, summonerServer, see userModel for more info)
* @param {Object} responder So we can send data back to client who made req
**/
function analyzeChampionDaysGraph(err, gameData, userData, responder){
// Store Id's of champion's found here
var championIds = [];
// Store duration of game's played for champion
var championGameCounts = [];
var championWinCounts = [];
// Iterate for each game
gameData.forEach(function(game){
if(championIds.indexOf(game.champion) > -1){
// This champion is already in the list, so add to previous duration
var champIdIndex = championIds.indexOf(game.champion);
var duration = Math.round(game.duration / 3600 * 100) / 100;
championGameCounts[champIdIndex] = Math.round(
(championGameCounts[champIdIndex] + duration) * 100) / 100;
if(game.isWin){
championWinCounts[champIdIndex][0] += 1;
} else {
championWinCounts[champIdIndex][1] += 1;
}
} else {
// This champion is not in the list, add it
championIds.push(game.champion);
// Find What index to push duration to
var champIdIndex = championIds.indexOf(game.champion);
var duration = Math.round(game.duration / 3600 * 100) / 100;
championGameCounts[champIdIndex] = duration;
if(game.isWin){
// champion W/L
championWinCounts[champIdIndex] = [1,0];
} else {
// champion W/L
championWinCounts[champIdIndex] = [0,1];
}
}
});
// Convert list of champ ID's to champ Names
var championNames = staticManager.getChampNames(championIds);
// Store Champion Names & Champion Durations in object
var championPieInfo = {
data: championGameCounts,
labels: championNames,
winData: championWinCounts};
// Send Names and Counts to client, so it can draw a pritty graph
responder.send(championPieInfo);
}
/****
* Gets all games between two dates
* Groups by position played
* Passed data found to analyzer function
*
****/
function positionPieGraph(err, userData, graphOptions, responder){
var startDate = new Date(graphOptions.startDate);
var endDate = new Date(graphOptions.endDate);
gameModel.aggregate([
// Only use games from this user
{ $match : { $and: [{ userId : userData._id},
{dateTime: {$gt: startDate, $lt: endDate}}]
}
},
{ $group : {
// Group by position
_id : {
position : "$position"
},
totalGames : { $sum: 1}}
}
], function(err,res){
if(err) console.log(err);
analyzePositionPieGraph(res, responder);
});
}
function analyzePositionPieGraph(data, responder){
var graphData = [];
// Convert data given to format for graphing
data.forEach(function(position){
var positionName = null;
var positionGames = position.totalGames;
if(position._id.position == 1){
positionName = "Top";
} else if(position._id.position == 2){
positionName = "Mid";
} else if(position._id.position == 3){
positionName = "Jungle";
} else if(position._id.position == 4){
positionName = "Bottom";
}
if(positionName !== null){
graphData.push({name: positionName, y: positionGames});
}
});
graphData.sort(function(a,b){return b.y - a.y});
responder.send(graphData);
}
/**
*
* daysGraph() gets games for user
* Between dates given
* Passes gameData found to analyzeGamesDaysGraph()
*
* @param {String} err Holds error information
* @param {Object} userData Details about this user (_id,
* summonerId, summonerName, summonerServer, see userModel for more info)
* @param {Object} graphOptions Details for graphing (userOffset,
* startDate, endDate)
* @param {Object} responder So we can send data back to client who made req
*
**/
function daysGraph(err, userData, graphOptions, responder){
// Date's made by clientside, already in there timezone
var startDate = graphOptions.startDate;
var endDate = graphOptions.endDate;
// Query Mongo DB for all games between specified dates
gameModel.find({
$and: [{"userId":userData._id},
{dateTime: {$gt: startDate, $lt: endDate}}]
}).sort(
{dateTime: -1}
).exec(
function (err, res){
if(err) responder.status(500).send("Error - " + err);
// Pass found games to analysis function
analyzeGamesDaysGraph(
null, res, graphOptions, userData, startDate, endDate, responder);
});
}
/**
*
* analyzeGamesDaysGraph() Calculates time played each day,
* Between two dates in the clients timezone
* Usually 7 Days
*
* @param {String} (err) Contains error information
* @param {Array} (gameData) Contains multiple game's each with data about
* the game, (DateGame, GameDuration, Match_ID, ect (See gameModel))
* @param {Object} (userData) Details about this user (_id,
* summonerId, summonerName, summonerServer, see userModel for more info)
* @param {Date} (startDate) Details dateFrom for date range
* @param {Date} (endDate) Details dateTo for date range
* @param {Object} (responder) So we can send data back to client who made req
**/
function analyzeGamesDaysGraph(err, gameData, graphOptions, userData, startDate, endDate, responder){
// Get # Datapoints in graph
var daysBetween = getHoursBetween(startDate, endDate) / 24;
// Get startdate in clients timezone
var startDate = moment(startDate).utcOffset(graphOptions.userOffSet*-1);
// tempGraphData is in minutes
var tempGraphData = [];
// The first label is the first day
var tempDateLabel = startDate;
// Initalise array of 0's for data
for(var i=0;i<daysBetween;i++){
tempGraphData.push(0);
}
// Loop over each game
gameData.forEach(function(game){
// set gameTime to client's timezone
var a = moment(game.dateTime).utcOffset(graphOptions.userOffSet*-1);
// Get what datapoint this is (gameDate - startDate)
var daysFromStartDate = Math.floor(getHoursBetween(startDate, moment(a).format()) / 24);
// Log actual minutes to specified datapoint
var duration = Math.round(game.duration / 60);
tempGraphData[daysFromStartDate] += duration;
});
// Load label and data into object
var graphInfo = {data: tempGraphData}
// push object (label + data) to client
responder.send(graphInfo);
}
/**
*
* todayGraph() given a user will get all the game's they've played in there
* timezone today. Passes game's found to analyzeGamesTodayGraph()
*
* @param {String} (err) Contains error infromation
* @param {Object} (userData) Details about this user (_id,
* summonerId, summonerName, summonerServer, see userModel for more info)
* @param {Object} (graphOptions) Details for graphing (userOffset,
* startDate, endDate)
* @param {Object} (responder) So we can send data back to client who made req
*
**/
function todayGraph(err, userData, graphOptions, responder){
// Get first minute of today in client's timezone
var todayFirstMin = graphOptions.fromDate;
// Get last minute of today in client's timezone
var todayLastMin = graphOptions.toDate;
// Query Mongo DB for all games between specified dates
gameModel.find(
{$and:
[{"userId":userData._id},
{dateTime: {$gt: todayFirstMin, $lt: todayLastMin}}
]
}).sort({
dateTime: -1
}).exec(
function (err, res){
if(err) responder.status(500).send("Error - " + err);
analyzeGamesTodayGraph(userData, graphOptions, res, responder);
});
}
/**
* analyzeGamesTodayGraph() Given a list of games will slice them into each our hour so we can out put to a graph
*
*
* @param {Object} (userData) Details about this user (_id,
summonerId, summonerName, summonerServer, see userModel for more info)
* @param {Object} (graphOptions) Details for graphing (userOffset,
startDate, endDate)
* @param {Array} (gameData) Contains multiple game's each with data about
the game, (DateGame, GameDuration, Match_ID, ect (See gameModel))
* @param {Object} (responder) So we can send data back to client who made req
*
**/
function analyzeGamesTodayGraph(userData, graphOptions, gameData, responder){
// Each point represents a time today (Client's Today)
// Each value represents duration (in mins)
var tempGraphData = [];
for(var i=0;i<24;i++){
tempGraphData.push(0);
}
// Iterate over each game
gameData.forEach(function(game){
// Get game time in client's timezone
var gameDate = moment(game.dateTime).utcOffset(graphOptions.userOffSet*-1);
var hour = moment(gameDate).hours();
var duration = Math.round(game.duration / 60);
tempGraphData[hour] += duration;
});
// Send data to client for graphing
responder.send(tempGraphData);
}
/**
*
* allGraph() grabs all the games the user has played, grouping them by day
* in client's timzone
* Will select earliest game's date and graph from that date to the current
* date (for the client)
*
* @param {String} (err) Contains error information ???
* @param {Object} (userData) Details about this user (_id,
* summonerId, summonerName, summonerServer, see userModel for more info)
* @param {Object} (graphOptions) Details for graphing (userOffset,
* startDate, endDate)
* @param {Object} (responder) So we can send data back to client who made req
*
**/
function allGraph(err, userData, graphOptions, responder){
// Get all games from this user
gameModel.aggregate([
// Only use games from this user
{ $match : { userId : userData._id}},
// Sync game time's to users timezone
{ $project : {
gameTimeLocal: { $subtract : [ "$dateTime", userData.offset*1000*60] } ,
duration : "$duration"}
},
{ $group : {
// Group by date
_id : {
year: { $year : "$gameTimeLocal" },
month: { $month : "$gameTimeLocal" },
day: { $dayOfMonth : "$gameTimeLocal" }
},
totalSeconds : { $sum: "$duration"}}
},
{ $sort: {_id: 1} }],
function (err, res){
// If there is an error output it to console
if(err) console.log("Error - " + err);
// If games found, pass to analyzeAllGraph
analyzeAllGraph(userData, res, graphOptions, responder);
})
}
/**
*
* analyzeAllGraph() Given a list of dates with corresponding durations in
* seconds, Generates an array of ata, each point is a date
* value of point is duration in hours
*
* @param {Object} (userData) Details about this user (_id,
* summonerId, summonerName, summonerServer, ect (see userModel))
* @param {Array} (gameData) Contains multiple game's each with data about
* the game, (DateGame, GameDuration, Match_ID, ect (See gameModel))
* @param {Object} (graphOptions) Details for graphing (userOffset,
* startDate, endDate)
* @param {Object} (responder) So we can send data back to client who made req
*
**/
function analyzeAllGraph(userData, gameData, graphOptions, responder){
// Get date in epoch UTC for first game played
var firstGame = gameData[0];
var firstGameDates = firstGame._id
var firstGameDate = Date.UTC(firstGameDates.year, firstGameDates.month-1, firstGameDates.day);
// Get date in epoch UTC for client's current time zone
var clientNowDate = Date.UTC(graphOptions.clientYear, graphOptions.clientMonth-1, graphOptions.clientDay);
// Milliseconds in a day for getting the days between two dates
var oneDay = 24*60*60*1000;
// totalDaysBetween firstGameDate and Now + 1
var totalDataPoints = Math.round(Math.abs((
firstGameDate - clientNowDate)/(oneDay))) + 1;
var allGraphDataPoints = [];
// Initalize all points to 0
for(var i = 0; i < totalDataPoints; i++){
allGraphDataPoints[i] = 0;
}
// Loop over each game
gameData.forEach(function(game){
var dateInfo = game._id;
// -1 from gameDateObjects, as it is in standard month format 1 = january, where Date.UTC wants format 0 = january
var gameDate = Date.UTC(dateInfo.year, dateInfo.month-1, dateInfo.day);
// Get datapoint number (days since firstGameDate of this gameDate)
var daysFromStartDate = Math.round(Math.abs((firstGameDate - gameDate)/(oneDay)));
// Log actual minutes to specified datapoint
var durationHours = Math.round(game.totalSeconds / 60) / 60;
// Round to 2 dp
durationHours = Math.round(durationHours * 100) / 100;
allGraphDataPoints[daysFromStartDate] = durationHours;
});
var graphInfo = {
// highchart needs inital date for labels
firstGameDateYear : firstGameDates.year,
firstGameDateMonth : firstGameDates.month,
firstGameDateDay : firstGameDates.day,
dataPoints : allGraphDataPoints
}
// Output graph to client for graphing
responder.send(graphInfo);
}
function yearGraph(err, userData, graphOptions, responder){
var startDate = new Date(graphOptions.year,0,0);
var endDate = new Date(graphOptions.year,11,31,23,59);
gameModel.aggregate([
// Only use games from this user
{ $match : { $and: [{ userId : userData._id},
{dateTime: {$gt: startDate, $lt: endDate}}]
}
},
{ $group : {
// Group by month
_id : {
month: { $month : "$dateTime" },
champion: "$champion"
},
totalSeconds : { $sum: "$duration"}}
},
{ $group : {
// Group by month first
_id : "$_id.month",
champion : {
"$push": {
"champion": "$_id.champion",
"count": "$totalSeconds"
},
},
totalSeconds : { $sum: "$totalSeconds"}}
}
], function(err,res){
if(err) console.log(err);
// Send data found back to client
responder.send(res);
//console.log(util.inspect(res, false, null));
});
}
/**
*
* getHoursbetween() Gets hours between two dates objects
*
* @param {Date} (dateOne) First date
* @param {Date} (dateTwo) Second date
*
* @return {Number} (hours) Hours between the two dates
*
**/
function getHoursBetween(dateOne,dateTwo){
dateOne = new Date(dateOne);
dateTwo = new Date(dateTwo);
var hours = Math.abs(dateOne.getTime() - dateTwo.getTime()) / (60*60*1000);
return hours;
}
module.exports = {
getGraph: getGraph
}