· 5 years ago · Jul 08, 2020, 11:50 AM
1"use strict";
2
3define(["./constants/keyCodes.js", "../lib/axios-0.19.1.min.js"], function(keyCodeName, axios) {
4
5 class LeagueCollector {
6
7 // Resets the collected data
8 resetData() {
9 this._keyLog = []; // Holds captured keystroke data
10 this._eventLog = []; // Holds captured event data
11 this._matchSummary = [];
12 this._matchTimeline = [];
13 this.matchStarted = false; // Resets flag for when player plays multiple matches
14 console.log("Collected Data Reset.")
15 }
16
17 // Appends collected data to the key or event logs
18 appendData(logName, data) {
19
20 // Append in-game time
21 data.localTimestamp = Date.now();
22 data.syncedTimestamp = data.localTimestamp;
23
24 // IF 'key', append to keylog, ELIF append to eventlog
25 if (logName === "key") {
26 this._keyLog.push(data);
27 }
28 else if (logName === "event") {
29 this._eventLog.push(data);
30 }
31 }
32
33 // Initializes values at the beginning of the game
34 handleMatchStart() {
35 if (!this.localMatchStartTime) {
36 this.localMatchStartTime = Date.now(); // Store Local start time
37 console.log("MATCH START EVENT: " + this.localMatchStartTime);
38 this.matchStarted = true;
39 var readyButton = document.getElementById('btnReady');
40
41 if(readyButton.classList.contains('recording') === true)
42 {
43 this.startRecording();
44 overwolf.windows.getMainWindow().minimize();
45 }
46
47 this.getSummonerData(); // Called here to get summoner data to start
48 }
49 }
50
51 // Set filepath names
52 setFilePaths() {
53 let curDate = new Date();
54 // Formatted as YYYY_MM_DD
55 let dateFolder = `${curDate.getFullYear()}_${curDate.getMonth()+1}_${curDate.getDate()}`;
56 // Formatted as 24 hour time, HH_MM_SS
57 let timeFolder = curDate.toLocaleTimeString([], {hour12:false}).replace(/:/g, "_");
58
59 let studyPath = `${overwolf.io.paths.desktop}\\${sessionStorage.getItem("studyCode")}\\${dateFolder}\\${timeFolder}\\`;
60
61 let dispId = sessionStorage.getItem("displayID");
62
63 this.keyLogPath = studyPath + `displayID_${dispId}_keylog.json`;
64 this.eventLogPath = studyPath + `displayID_${dispId}_eventlog.json`;
65 this.matchSummaryPath = studyPath + `displayID_${dispId}_matchsummary.json`;
66 this.matchTimelinePath = studyPath + `displayID_${dispId}_matchtimeline.json`;
67 this.videoPath = studyPath + "video\\";
68
69 // Update UI File Path
70 let uipath = `/Desktop/${sessionStorage.getItem("studyCode")}/${dateFolder}/${timeFolder}/video/`;
71 $("#videoLocation").text(uipath);
72 }
73
74 /**
75 * Check to see if the League of Legends Launcher is running. Sets the summoner name when user logs in to their
76 * League of Legends account.
77 * @param{self} object Reference to LeagueCollector Object for setTimeout polling.
78 */
79 launcherCheck(self) {
80
81 // If launcher was not found yet
82 if (!self._launcherFound) {
83
84 let info = ["summoner_info"]; // Get summoner info from launcher events
85 let launcherId = 10902; // Overwolf id for obtaining LoL Launcher
86
87 // Adds summoner info to the required features overwolf will listen for
88 overwolf.games.launchers.events.setRequiredFeatures(launcherId, info, function (response) {
89 // Check response to see if launcher exists, else poll
90 if (response.success) {
91 // Get the summoner info of the league launcher
92 overwolf.games.launchers.events.getInfo(launcherId, function (response) {
93 // Check for display name. If not found, keep polling
94 if ('display_name' in response.res.summoner_info) {
95 let summonerName = response.res.summoner_info.display_name;
96 sessionStorage.setItem("summonerName", summonerName);
97 self.summonerName = summonerName;
98
99 // Launcher found
100 console.log(`Summoner Name Found! Welcome ${summonerName}!`);
101 // Update status
102 $("#lblStatus").text(`Welcome ${summonerName}!`);
103
104 self._launcherFound = true;
105 }
106 else {
107 // Launcher was found, but user hasn't logged in. Change timeout to 5 sec
108 setTimeout(self.launcherCheck, 5000, self);
109 }
110 });
111 }
112 else {
113 // Check for launcher every 10 seconds
114 setTimeout(self.launcherCheck, 10000, self);
115 }
116 });
117 }
118 }
119
120 constructor() {
121
122 var self = this; // Reference for scoped access
123 this.resetData(); // Creates key and event logs
124 this.summonerName = sessionStorage.getItem("summonerName");
125 this.apiKey = sessionStorage.getItem("riotKey");
126 this.accountId = "";
127 this.encryptedSummonerId = "";
128 this.matchId = "";
129 this.timeElapsed = 0;
130 this.remoteMatchStartTime = 0;
131 this.matchStarted = false; // Indicates whether game has started
132 this.streamId = null; // Stream ID set when recording is started
133
134 // Riot API variables
135 this.baseUrl = "https://na1.api.riotgames.com";
136 this.payload = {headers: {"X-Riot-Token": this.apiKey}};
137
138 // Local filepaths
139 this.setFilePaths();
140
141 // Features we are interested in collecting
142 this.g_interestedInFeatures = [
143 "gep_internal",
144 //"live_client_data",
145 "matchState",
146 "match_info",
147 "death",
148 "respawn",
149 "abilities",
150 "kill",
151 "assist",
152 //"gold",
153 //"minions",
154 "summoner_info",
155 "gameMode",
156 "teams",
157 "level",
158 "announcer"
159 //"damage",
160 //"heal"
161 //"counters"
162 ];
163
164 // ###################### INPUT TRACKING #################################
165
166 // Object to hold key press and mouse actions
167 function KeyAction(key, keyName, press, x, y) {
168 this.keyValue = key; // Integer key value
169 this.keyName = keyName; // Key Name
170 this.press = press; // KeyDown or KeyUp
171 this.mouseX = x; // Screen x coordinates
172 this.mouseY = y; // Screen y coordinates
173 }
174
175 // Listener for mouse presses
176 overwolf.games.inputTracking.onMouseDown.addListener(
177 function(mInput) {
178 // Use 0 for mouse since some mice have programmable buttons
179 var mName = "MOUSE " + mInput.button;
180 var mAction = new KeyAction(0, mName, "keyDown",
181 mInput.x, mInput.y);
182
183 self.appendData("key", mAction);
184 //console.log(JSON.stringify(mInput));
185 }
186 );
187 overwolf.games.inputTracking.onMouseUp.addListener(
188 function(mInput) {
189 // Use 0 for mouse since some mice have programmable buttons
190 var mName = "MOUSE " + mInput.button;
191 var mAction = new KeyAction(0, mName, "keyUp",
192 mInput.x, mInput.y);
193 self.appendData("key", mAction);
194 //console.log(JSON.stringify(mAction));
195 }
196 );
197
198 // Listener for keyboard presses
199 overwolf.games.inputTracking.onKeyDown.addListener(
200 function(kInput) {
201 overwolf.games.inputTracking.getMousePosition(
202 function(mPos) {
203 var kName = keyCodeName[kInput.key] ? keyCodeName[kInput.key] : "";
204 var mouse = mPos.mousePosition;
205 var kAction = new KeyAction(kInput.key, kName, "keyDown",
206 mouse.x, mouse.y);
207 self.appendData("key", kAction);
208 // console.log(JSON.stringify(kAction));
209 }
210 );
211 }
212 );
213 overwolf.games.inputTracking.onKeyUp.addListener(
214 function(kInput) {
215 overwolf.games.inputTracking.getMousePosition(
216 function(mPos) {
217 var kName = keyCodeName[kInput.key] ? keyCodeName[kInput.key] : "";
218 var mouse = mPos.mousePosition;
219 var kAction = new KeyAction(kInput.key, kName, "keyUp",
220 mouse.x, mouse.y);
221 self.appendData("key", kAction);
222 //console.log(JSON.stringify(kAction));
223 }
224 );
225 }
226 );
227 // ###################### END INPUT TRACKING #############################
228
229
230 // ########################START SETUP FUNCTIONS #########################
231
232 // Adds event listeners for in-game events
233 function registerEvents() {
234 // ###################### EVENT TRACKING ###############################
235 // Check if listeners exist
236 if (!self.listenersExist) {
237 console.log("Registering Events");
238 // Listener for event errors
239 overwolf.games.events.onError.addListener(function(info) {
240 console.error("Error: " + JSON.stringify(info));
241 });
242
243 // Listener for "static" data changed (total kills, username, steam-id)
244 // This will also be triggered the first time we register
245 // for events and will contain all the current information
246 overwolf.games.events.onInfoUpdates2.addListener(function(info) {
247
248 self.appendData("event", info);
249 //console.log("Info UPDATE: " + JSON.stringify(info));
250 });
251
252 // Listener for in-game events triggered
253 overwolf.games.events.onNewEvents.addListener(function(event) {
254 var minion_time = Date.now();
255 // Append Data
256 self.appendData("event", event);
257 //console.log("EVENT FIRED: " + JSON.stringify(event));
258
259 // Store minions spawn time (League default is 1:05)
260 if (!self.localMinionSpawnTime) {
261 if ("data" in event.events[0] && event.events[0].data) {
262 let evt = JSON.parse(event.events[0].data)
263 if (evt.name === "minions_spawn") {
264 self.localMinionSpawnTime = minion_time // Store Local start time
265 console.log("MINION SPAWN TIME: " + self.localMinionSpawnTime);
266 }
267
268 // Placed getMatchStart() call here because it got called too often under onGameInfoUpdated()
269 // Riot returns 0 if our getMatchStart() is called too early
270 if (self.remoteMatchStartTime === 0)
271 self.getMatchStart();
272 }
273 }
274
275 });
276
277 // Add property so that listeners don't get added again.
278 self.listenersExist = true;
279 }
280
281 // ###################### END EVENT TRACKING ###########################
282 }
283
284 // Sets the features to be collected
285 function setFeatures() {
286 // Check if features already set
287 if (!overwolf.games.events.featuresReady) {
288
289 overwolf.games.events.setRequiredFeatures(self.g_interestedInFeatures, function(info) {
290 if (info.status === "error")
291 {
292 window.setTimeout(setFeatures, 1000);
293 return;
294 }
295 else {
296 overwolf.games.events.featuresReady = true;
297 console.debug("Required features set!");
298 console.debug(JSON.stringify(info));
299 }
300 }
301 )}
302 }
303
304 // ####################### START RECORDING LISTENERS #####################
305 // Stop streaming listener
306 overwolf.streaming.onStopStreaming.addListener(function(result) {
307 console.log("STOPPED Screen Recording Listener!");
308 console.log(result);
309 });
310
311 // Start streaming listener
312 overwolf.streaming.onStartStreaming.addListener(function(result) {
313 console.log("START Screen Recording Listener!");
314 console.log(result);
315 });
316
317 // Streaming error listener
318 overwolf.streaming.onStreamingError.addListener(function(result) {
319 console.error("STREAMING ERROR");
320 console.log(result);
321 });
322
323 // Streaming warning listener
324 overwolf.streaming.onStreamingWarning.addListener(function(result) {
325 console.log("STREAMING WARNING");
326 console.log(result);
327 });
328 // ####################### END RECORDING LISTENERS #######################
329
330 // ######################### END SETUP FUNCTIONS #########################
331
332 // Listener to see if game started
333 overwolf.games.onGameInfoUpdated.addListener(function (res) {
334
335 if (self.gameLaunched(res)) {
336 //setTimeout(setFeatures, 1000);
337 setFeatures();
338 registerEvents();
339 }
340
341 // For when game is ending, call Riot functions chained under getRiotData()
342 if (res.gameInfo && res.gameInfo.isRunning === false && self.matchStarted === true) {
343 console.log("Game Ended!");
344 // Call sync function when game ends to sync event log
345 self.syncWithMinionSpawn();
346 //collector.getRiotData();
347 }
348
349
350 });
351
352 // Check for launcher
353 this.launcherCheck(this);
354
355 // Check if game is running
356 overwolf.games.getRunningGameInfo(function (res) {
357 if (self.gameRunning(res)) {
358 //setTimeout(setFeatures, 1000);
359 setFeatures();
360 registerEvents();
361 }
362 //console.log("getRunningGameInfo: " + JSON.stringify(res));
363 });
364
365 setFeatures();
366 registerEvents();
367 console.debug("League Collector Created!");
368 } // End LeagueCollector Constructor
369
370
371 // Check if game has been launched
372 gameLaunched(gameInfoResult) {
373 if (!gameInfoResult) {
374 return false;
375 }
376 if (!gameInfoResult.gameInfo) {
377 return false;
378 }
379 if (!gameInfoResult.runningChanged && !gameInfoResult.gameChanged) {
380 return false;
381 }
382 if (!gameInfoResult.gameInfo.isRunning) {
383 return false;
384 }
385 // NOTE: we divide by 10 to get the game class id without it's sequence number
386 if (Math.floor(gameInfoResult.gameInfo.id/10) !== 5426) {
387 return false;
388 }
389
390 console.debug("LoL Launched");
391 // Indicates match has started. Match start event not always accurate
392 this.handleMatchStart();
393 return true;
394
395 }
396
397 // Checks if the game is currently running
398 gameRunning(gameInfo) {
399
400 if (!gameInfo) {
401 return false;
402 }
403 if (!gameInfo.isRunning) {
404 return false;
405 }
406 // NOTE: we divide by 10 to get the game class id without it's sequence number
407 if (Math.floor(gameInfo.id/10) != 5426) {
408 return false;
409 }
410
411 console.debug("LoL running");
412 return true;
413 }
414
415
416
417 // START Riot endpoint methods (formerly handleRiotData.js)
418
419 // For getting AccountID
420 getSummonerData() {
421 //console.log("Called getSummonerData");
422 var base = "https://na1.api.riotgames.com";
423 var endpoint = "lol/summoner/v4/summoners/by-name";
424 var payload = {headers: {"X-Riot-Token": this.apiKey}};
425
426 axios.get(`${base}/${endpoint}/${this.summonerName}`, payload)
427 .then(response => {
428 //console.log("summonerData response: ", response);
429 this.accountId = response.data.accountId;
430 this.encryptedSummonerId = response.data.id;
431 //console.log("this.encryptedSummonerId: ", this.encryptedSummonerId);
432 })
433 .catch(error => {
434 console.error("summonerData error: ", error);
435 console.log("api key used: ", this.apiKey);
436 console.log("this.summonerName", this.summonerName);
437 });
438 }
439
440 /**
441 * Retrieves all endgame data for the most recently played match from Riot
442 * Chains together endpoint calls to get most recent match, then summary data, then timeline data
443 */
444 getRiotData() {
445 // For getting MatchID (called gameId in Riot API)
446 let endpoint = "lol/match/v4/matchlists/by-account";
447 axios.get(`${this.baseUrl}/${endpoint}/${this.accountId}`, this.payload)
448 .then(response => {
449 this.matchId = response.data.matches[0].gameId;
450 console.log ("Got match Id: ", this.matchId);
451 })
452 .then(() => {
453 this.getMatchSummary();
454 })
455 .then(() => {
456 this.getMatchTimeline();
457 })
458 .catch(error => {
459 console.error("getRiotData() error: ", error);
460 console.log("check if accountId empty: ", this.accountId);
461 });
462 }
463
464 /**
465 * Gets match summary data
466 */
467 getMatchSummary() {
468 let endpoint = "lol/match/v4/matches";
469
470 axios.get(`${this.baseUrl}/${endpoint}/${this.matchId}`, this.payload)
471 .then(response => {
472 //console.log("matches response: ", response);
473 this._matchSummary = response;
474
475 overwolf.io.writeFileContents(this.matchSummaryPath,
476 JSON.stringify(response),
477 overwolf.io.enums.eEncoding.UTF8,
478 true,
479 function (fs) {
480 console.log("Writing Match Summary: ", fs)
481 });
482 })
483 .catch(error => {
484 console.error("Match Summary error: ", error);
485 console.log("check if matchId empty: ", this.matchId);
486 });
487 }
488
489 // Gets event data by time
490 getMatchTimeline() {
491 let endpoint = "lol/match/v4/timelines/by-match";
492
493 axios.get(`${this.baseUrl}/${endpoint}/${this.matchId}`, this.payload)
494 .then(response => {
495 //console.log("matchTimelines response: ", response);
496 this._matchTimeline = response;
497
498 overwolf.io.writeFileContents(this.matchTimelinePath,
499 JSON.stringify(response),
500 overwolf.io.enums.eEncoding.UTF8,
501 true,
502 function (fs) {
503 console.log("Writing Match Timeline: ", fs);
504 });
505 })
506 .catch(error => {
507 console.error("matchTimelines error: ", error);
508 console.log("check if matchId empty: ", this.matchId);
509 });
510 }
511
512 getMatchStart() {
513 var endpoint = "lol/spectator/v4/active-games/by-summoner/" + this.encryptedSummonerId;
514
515 axios.get(`${this.baseUrl}/${endpoint}/${this.matchId}`, this.payload)
516 .then(response => {
517 //console.log("matchStart response: ", response);
518 this.remoteMatchStartTime = response.data.gameStartTime;
519 console.log("MatchStart time set: ", this.remoteMatchStartTime);
520 })
521 .catch(error => {
522 console.error("MatchStart Time error: ", error);
523 });
524 }
525 // END Riot endpoint methods
526
527
528////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
529
530 // Writes collected data to a log
531 writeToFile() {
532 console.log("Writing collected data to file...");
533 console.debug("### KeyLog ###");
534 console.debug(JSON.stringify(this._keyLog));
535 console.debug("### EventLog ###");
536 console.debug(JSON.stringify(this._eventLog));
537
538 // Write keylog
539 overwolf.io.writeFileContents(this.keyLogPath,
540 JSON.stringify(this._keyLog),
541 overwolf.io.enums.eEncoding.UTF8,
542 true,
543 function (fs) {
544 console.log("Writing keylog file: " + JSON.stringify(fs));
545 });
546 // Write eventlog
547 overwolf.io.writeFileContents(this.eventLogPath,
548 JSON.stringify(this._eventLog),
549 overwolf.io.enums.eEncoding.UTF8,
550 true,
551 function (fs) {
552 console.log("Writing eventlog file: " + JSON.stringify(fs));
553 });
554 }
555
556
557
558 // ######################## START REPLAY CAPTURING ###########################
559 // Start streaming function
560 startRecording() {
561 console.log(this.videoPath);
562 // Settings to determine how to capture video. Videos stored at C:\Users\Esports Research Lab\Videos\Overwolf\CapturEsports\daniel_testvideos
563 let streamSettings = {
564 "provider": overwolf.streaming.enums.StreamingProvider.VideoRecorder,
565 "settings": {
566 "video": {
567 "fps": 60,
568 "auto_calc_kbps": true, // false
569 "max_kbps": 6000, // orginally 1000
570 "sub_folder_name": this.videoPath //sessionStorage.getItem("studyCode")
571 },
572 "audio": {
573 "mic": {
574 "volume": 100,
575 "enable": true,
576 },
577 "game": {
578 "volume": 90,
579 "enable": true,
580 },
581 },
582 "peripherals": {
583 "capture_mouse_cursor": overwolf.streaming.enums.StreamMouseCursor.gameOnly
584 }
585 }
586 };
587
588
589 // Start overwolf recording
590 overwolf.streaming.start(streamSettings, function(result) {
591
592 if (result.status === "success") {
593 console.log("START VIDEO RECORDING");
594 console.debug(result);
595 self.streamId = result.stream_id;
596 }
597 else {
598 console.error("ERROR START VIDEO RECORDING");
599 console.debug(result);
600 }
601 });
602
603
604 }
605
606 // Stop overwolf recording
607 stopRecording() {
608 overwolf.streaming.stop(self.streamId, function(result) {
609 console.log("STOP VIDEO RECORDING");
610 console.log(result);
611 });
612 }
613
614 // ######################## END REPLAY CAPTURING #############################
615
616 // Creates string of in-game timer relative to game start time.
617 getInGameTime(startTime, newTime) {
618
619 var diff_sec = (newTime - startTime) / 1000;
620 var minutes = Math.floor(diff_sec / 60);
621 var seconds = diff_sec - minutes * 60;
622
623 // Check if min and sec are negative
624 if (minutes < 0 || seconds < 0) {
625 return "00:00:00";
626 }
627 else {
628 // Pad time for pretty format
629 minutes = minutes.toString().padStart(2, "0");
630 // Round seconds to 2 decimal places. Should have value following 00:00
631 seconds = seconds.toFixed(2).padStart(5, "0").replace(".", ":");
632 return minutes + ":" + seconds
633 }
634
635 }
636
637 /**
638 * Returns a time string in ISO format.
639 */
640 getCurrentISOTimeString() {
641 let curDate = new Date();
642 let a = curDate.toLocaleString([], {hour12:false}).split(/\D/);
643 return `${curDate.getFullYear()}-${("0"+(curDate.getMonth()+1)).slice(-2)}-${("0"+curDate.getDate()).slice(-2)}T${a[4]}:${a[5]}:${a[6]}`;
644 }
645
646 // Removes duplicate information from live_client_data fields in event log
647 cleanEventLog() {
648 // Clean live client data
649 console.log("Cleaning event log");
650 this._eventLog = this._eventLog.map(function (data) {
651
652 if ("info" in data) {
653 var info = data["info"];
654
655 if (data["feature"] === "live_client_data") {
656
657 var clientData = info["live_client_data"];
658
659 // Remove duplicate map info
660 if ("game_data" in clientData || "all_players" in clientData) {
661 return null;
662 }
663 // Modify/remove exxtraneous active player info
664 else if ("active_player" in clientData) {
665 let playerData = clientData["active_player"];
666
667 delete playerData["abilities"];
668 delete playerData["fullRunes"];
669
670 data["info"]["live_client_data"]["active_player"] = playerData;
671
672 return data;
673 }
674 }
675 }
676 return data;
677 });
678
679 // Remove null values from map
680 this._eventLog = this._eventLog.filter(function (el) {
681 return el != null;
682 });
683 }
684
685 // Sync time based on minion spawn
686 syncWithMinionSpawn() {
687
688
689 //Check if eventLog/keyLog are empty
690 if(this._eventLog.length < 1 && this._keyLog.length < 1) {
691 alert("No game data recorded. Please play a game first.");
692 return;
693 }
694 //Check if timeInput is empty
695 if(this.remoteMatchStartTime === 0) { // if(timeInput.data[0].value === "") {
696 alert("collector.remoteMatchStartTime not set"); // alert("Please enter a start time to synchronize to.");
697 return;
698 }
699
700
701
702 let localTime = this.localMinionSpawnTime;
703 let remoteTime = parseInt(this.remoteMatchStartTime); // parseInt(timeInput.data[0].value);
704
705
706 console.log("LOCAL START TIME: " + localTime);
707 console.log("REMOTE TIME: " + remoteTime);
708
709 // Add 65 seconds for time sync, minions spawn at 1:05
710 let timeDelta = remoteTime + 65000 - localTime; // How much ahead/behind the client is
711 console.debug("Time Delta:", timeDelta);
712 // Sync data using remote time as the absolute truth
713 this._eventLog.map((event) => {
714 event.syncedTimestamp += timeDelta;
715 event.syncedInGameTime = this.getInGameTime(remoteTime, event.syncedTimestamp);
716 return event;
717 });
718 this._keyLog.map((action) => {
719 action.syncedTimestamp += timeDelta;
720 action.syncedInGameTime = this.getInGameTime(remoteTime, action.syncedTimestamp);
721 return action;
722 });
723
724 // Wrting data to file
725 this.writeToFile();
726
727 //location.href = "thankyou.html";
728 }
729
730 /**
731 * Call to manuall upload data. Bind to a button
732 */
733 manualUploadData() {
734 console.log("Manual RIOT call");
735
736 // Get manually inputted match id
737 let matchID = $("#manualMatchID").val();
738
739 // Confirm submission
740 createConfirmation("Confirmation", `Are you sure this matchID is correct: [${matchID}]?`, (confirm) => {
741
742 // Verify match ID
743 if (confirm && matchID) {
744 this.writeToFile();
745 console.log("Getting Riot Data with matchID: " + matchID);
746
747 // Set Match ID
748 this.matchId = matchID;
749
750 // Save match id to session storage
751 sessionStorage.setItem("matchID", matchID);
752
753 // Disable button
754 $("#btnManualMatch").prop("disabled", true);
755
756 // Get summoner Data
757 let sumEndpoint = "lol/summoner/v4/summoners/by-name";
758
759 axios.get(`${this.baseUrl}/${sumEndpoint}/${this.summonerName}`, this.payload)
760 .then(response => {
761 this.accountId = response.data.accountId;
762 this.encryptedSummonerId = response.data.id;
763 })
764 .then(() => {
765
766 // Get Match Summary
767 let endpoint = "lol/match/v4/matches";
768
769 axios.get(`${this.baseUrl}/${endpoint}/${this.matchId}`, this.payload)
770 .then(response => {
771 //console.log("Match Summary: ", response);
772 // Remove extra metadata
773 delete response["status"];
774 delete response["statusText"];
775 delete response["headers"];
776 delete response["config"];
777 delete response["request"];
778
779
780 this._matchSummary = response;
781
782
783 // Write data to file
784 overwolf.io.writeFileContents(this.matchSummaryPath,
785 JSON.stringify(response), overwolf.io.enums.eEncoding.UTF8, true,
786 function (fs) {
787 console.log("Write Match Summary: ", fs);
788 });
789 })
790 // Get Match Timeline
791 .then(() => {
792 let endpoint = "lol/match/v4/timelines/by-match";
793
794 axios.get(`${this.baseUrl}/${endpoint}/${this.matchId}`, this.payload)
795 .then(response => {
796 //console.log("Match Timeline: ", response);
797 // Remove extra metadata
798 delete response["status"];
799 delete response["statusText"];
800 delete response["headers"];
801 delete response["config"];
802 delete response["request"];
803
804 this._matchTimeline = response;
805
806
807 // Write data to file.
808 overwolf.io.writeFileContents(this.matchTimelinePath,
809 JSON.stringify(response), overwolf.io.enums.eEncoding.UTF8, true,
810 function (fs) {
811 console.log("Write Match Timeline: ", fs);
812 });
813 })
814 // Upload data to Asterix
815 .then(() => {
816
817 let server = sessionStorage.getItem("serverURL") + "/league";
818 let dataPayload = {};
819
820 dataPayload["userID"] = sessionStorage.getItem("userID");
821 dataPayload["displayID"] = sessionStorage.getItem("displayID");
822 dataPayload["matchID"] = this.matchId.toString();
823 dataPayload["matchDate"] = this.getCurrentISOTimeString();
824 dataPayload["keystrokeLog"] = this._keyLog;
825 dataPayload["eventLog"] = this._eventLog;
826 dataPayload["matchSummary"] = this._matchSummary;
827 dataPayload["matchTimeline"] = this._matchTimeline;
828 dataPayload["studyCode"] = sessionStorage.getItem("studyCode");
829
830 axios.post(server, dataPayload)
831 .then(response => {
832
833 console.log(response);
834 // Change button name
835 $("#btnManualMatch").text("Upload Success!")
836 .removeClass("btn-outline-success")
837 .addClass("btn-success");
838
839 })
840 .catch(error => {
841 console.error("error: ", error);
842 $("#btnManualMatch").prop("disabled", false);
843 })
844 })
845 })
846 .catch(error => {
847 console.error("Match error: ", error);
848 createAlertNotification("MatchID Error", `Could not get match ID: ${matchID}`);
849 $("#btnManualMatch").prop("disabled", false);
850 })
851 })
852 .catch(error => {
853 console.error("Manual Riot Call error: ", error);
854 createAlertNotification("API Error", error.toString());
855 $("#btnManualMatch").prop("disabled", false);
856 });
857
858 }
859 else if (matchID <= 0) {
860 createAlertNotification("Bad match ID", "Please double check your match ID!");
861 }
862 });
863 }
864
865
866 }
867 // End of LeagueCollector class
868
869 //let collector = new LeagueCollector(); // Collector class object
870
871
872 return LeagueCollector;
873
874});