Merge pull request #276 from Jorys-Paulin/js-cleaning

A console update
This commit is contained in:
R. Aidan Campbell 2017-09-03 16:56:09 -07:00 committed by GitHub
commit 3f7e3aa10b
4 changed files with 108 additions and 115 deletions

View File

@ -317,7 +317,7 @@ var common = (function() {
function updateStatus(opt_message) { function updateStatus(opt_message) {
if (opt_message) { if (opt_message) {
statusText = opt_message; statusText = opt_message;
console.log('common.js: ' + statusText); console.log('%c[updateStatus, common.js]', 'color: gray;', statusText);
} }
var statusField = document.getElementById('statusField'); var statusField = document.getElementById('statusField');
if (statusField) { if (statusField) {

View File

@ -157,13 +157,13 @@ function beginBackgroundPollingOfHost(host) {
} }
function stopBackgroundPollingOfHost(host) { function stopBackgroundPollingOfHost(host) {
console.log('stopping background polling of server: ' + host.toString()); console.log('%c[index.js, backgroundPolling]', 'color: green;', 'Stopping background polling of host ' + host.serverUid + '\n', host, host.toString()); //Logging both object (for console) and toString-ed object (for text logs)
window.clearInterval(activePolls[host.serverUid]); window.clearInterval(activePolls[host.serverUid]);
delete activePolls[host.serverUid]; delete activePolls[host.serverUid];
} }
function snackbarLog(givenMessage) { function snackbarLog(givenMessage) {
console.log(givenMessage); console.log('%c[index.js, snackbarLog]', 'color: green;', givenMessage);
var data = { var data = {
message: givenMessage, message: givenMessage,
timeout: 2000 timeout: 2000
@ -172,7 +172,7 @@ function snackbarLog(givenMessage) {
} }
function snackbarLogLong(givenMessage) { function snackbarLogLong(givenMessage) {
console.log(givenMessage); console.log('%c[index.js, snackbarLog]', 'color: green;', givenMessage);
var data = { var data = {
message: givenMessage, message: givenMessage,
timeout: 5000 timeout: 5000
@ -187,26 +187,24 @@ function updateBitrateField() {
function moduleDidLoad() { function moduleDidLoad() {
if(!myUniqueid) { if(!myUniqueid) {
console.log("Failed to get uniqueId. We should have already generated one. Regenerating..."); console.warn('%c[index.js, moduleDidLoad]', 'color: green;', 'Failed to get uniqueId. We should have already generated one. Regenerating...');
myUniqueid = uniqueid(); myUniqueid = uniqueid();
storeData('uniqueid', myUniqueid, null); storeData('uniqueid', myUniqueid, null);
} }
if(!pairingCert) { // we couldn't load a cert. Make one. if(!pairingCert) { // we couldn't load a cert. Make one.
console.log("Failed to load local cert. Generating new one"); console.warn('%c[index.js, moduleDidLoad]', 'color: green;', 'Failed to load local cert. Generating new one');
sendMessage('makeCert', []).then(function (cert) { sendMessage('makeCert', []).then(function (cert) {
storeData('cert', cert, null); storeData('cert', cert, null);
pairingCert = cert; pairingCert = cert;
console.log("Generated new cert."); console.info('%c[index.js, moduleDidLoad]', 'color: green;', 'Generated new cert:', cert);
}, function (failedCert) { }, function (failedCert) {
console.log('ERROR: failed to generate new cert!'); console.error('%c[index.js, moduleDidLoad]', 'color: green;', 'Failed to generate new cert! Returned error was: \n', failedCert);
console.log('Returned error was: ' + failedCert);
}).then(function (ret) { }).then(function (ret) {
sendMessage('httpInit', [pairingCert.cert, pairingCert.privateKey, myUniqueid]).then(function (ret) { sendMessage('httpInit', [pairingCert.cert, pairingCert.privateKey, myUniqueid]).then(function (ret) {
restoreUiAfterNaClLoad(); restoreUiAfterNaClLoad();
}, function (failedInit) { }, function (failedInit) {
console.log('ERROR: failed httpInit!'); console.error('%c[index.js, moduleDidLoad]', 'color: green;', 'Failed httpInit! Returned error was: ', failedInit);
console.log('Returned error was: ' + failedInit);
}); });
}); });
} }
@ -214,8 +212,7 @@ function moduleDidLoad() {
sendMessage('httpInit', [pairingCert.cert, pairingCert.privateKey, myUniqueid]).then(function (ret) { sendMessage('httpInit', [pairingCert.cert, pairingCert.privateKey, myUniqueid]).then(function (ret) {
restoreUiAfterNaClLoad(); restoreUiAfterNaClLoad();
}, function (failedInit) { }, function (failedInit) {
console.log('ERROR: failed httpInit!'); console.error('%c[index.js, moduleDidLoad]', 'color: green;', 'Failed httpInit! Returned error was: ', failedInit);
console.log('Returned error was: ' + failedInit);
}); });
} }
} }
@ -224,7 +221,7 @@ function moduleDidLoad() {
function pairTo(nvhttpHost, onSuccess, onFailure) { function pairTo(nvhttpHost, onSuccess, onFailure) {
if(!pairingCert) { if(!pairingCert) {
snackbarLog('ERROR: cert has not been generated yet. Is NaCl initialized?'); snackbarLog('ERROR: cert has not been generated yet. Is NaCl initialized?');
console.log("User wants to pair, and we still have no cert. Problem = very yes."); console.warn('%c[index.js]', 'color: green;', 'User wants to pair, and we still have no cert. Problem = very yes.');
onFailure(); onFailure();
return; return;
} }
@ -232,7 +229,7 @@ function pairTo(nvhttpHost, onSuccess, onFailure) {
nvhttpHost.pollServer(function (ret) { nvhttpHost.pollServer(function (ret) {
if (!nvhttpHost.online) { if (!nvhttpHost.online) {
snackbarLog('Failed to connect to ' + nvhttpHost.hostname + '! Are you sure the host is on?'); snackbarLog('Failed to connect to ' + nvhttpHost.hostname + '! Are you sure the host is on?');
console.log(nvhttpHost.toString()); console.error('%c[index.js]', 'color: green;', 'Host declared as offline:', nvhttpHost, nvhttpHost.toString()); //Logging both the object and the toString version for text logs
onFailure(); onFailure();
return; return;
} }
@ -252,7 +249,7 @@ function pairTo(nvhttpHost, onSuccess, onFailure) {
pairingDialog.close(); pairingDialog.close();
}); });
console.log('sending pairing request to ' + nvhttpHost.hostname + ' with random number ' + randomNumber); console.log('%c[index.js]', 'color: green;', 'Sending pairing request to ' + nvhttpHost.hostname + ' with random number' + randomNumber);
nvhttpHost.pair(randomNumber).then(function (paired) { nvhttpHost.pair(randomNumber).then(function (paired) {
if (!paired) { if (!paired) {
if (nvhttpHost.currentGame != 0) { if (nvhttpHost.currentGame != 0) {
@ -260,8 +257,7 @@ function pairTo(nvhttpHost, onSuccess, onFailure) {
} else { } else {
$('#pairingDialogText').html('Error: failed to pair with ' + nvhttpHost.hostname + '.'); $('#pairingDialogText').html('Error: failed to pair with ' + nvhttpHost.hostname + '.');
} }
console.log('failed API object: '); console.log('%c[index.js]', 'color: green;', 'Failed API object:', nvhttpHost, nvhttpHost.toString()); //Logging both the object and the toString version for text logs
console.log(nvhttpHost.toString());
onFailure(); onFailure();
return; return;
} }
@ -271,9 +267,8 @@ function pairTo(nvhttpHost, onSuccess, onFailure) {
onSuccess(); onSuccess();
}, function (failedPairing) { }, function (failedPairing) {
snackbarLog('Failed pairing to: ' + nvhttpHost.hostname); snackbarLog('Failed pairing to: ' + nvhttpHost.hostname);
console.log('pairing failed, and returned ' + failedPairing); console.error('%c[index.js]', 'color: green;', 'Pairing failed, and returned:', failedPairing);
console.log('failed API object: '); console.error('%c[index.js]', 'color: green;', 'Failed API object:', nvhttpHost, nvhttpHost.toString()); //Logging both the object and the toString version for text logs
console.log(nvhttpHost.toString());
onFailure(); onFailure();
}); });
}); });
@ -417,10 +412,10 @@ function stylizeBoxArt(freshApi, appIdToStylize) {
// show the app list // show the app list
function showApps(host) { function showApps(host) {
if(!host || !host.paired) { // safety checking. shouldn't happen. if(!host || !host.paired) { // safety checking. shouldn't happen.
console.log('Moved into showApps, but `host` did not initialize properly! Failing.'); console.log('%c[index.js, showApps]', 'color: green;', 'Moved into showApps, but `host` did not initialize properly! Failing.');
return; return;
} }
console.log(host); console.log('%c[index.js, showApps]', 'color: green;', 'Current host object:', host, host.toString()); //Logging both object (for console) and toString-ed object (for text logs)
$('#quitCurrentApp').show(); $('#quitCurrentApp').show();
$("#gameList .game-container").remove(); $("#gameList .game-container").remove();
@ -464,9 +459,7 @@ function showApps(host) {
} }
}, function (failedPromise) { }, function (failedPromise) {
console.log('Error! Failed to retrieve box art for app ID: ' + app.id + '. Returned value was: ' + failedPromise) console.log('%c[index.js, showApps]', 'color: green;', 'Error! Failed to retrieve box art for app ID: ' + app.id + '. Returned value was: ' + failedPromise, '\n Host object:', host, host.toString());
console.log('failed host object: ');
console.log(host.toString());
if ($('#game-' + app.id).length === 0) { if ($('#game-' + app.id).length === 0) {
// double clicking the button will cause multiple box arts to appear. // double clicking the button will cause multiple box arts to appear.
@ -489,9 +482,7 @@ function showApps(host) {
}, function (failedAppList) { }, function (failedAppList) {
$('#naclSpinner').hide(); $('#naclSpinner').hide();
console.log('Failed to get applist from host: ' + host.hostname); console.log('%c[index.js, showApps]', 'color: green;', 'Failed to get applist from host: ' + host.hostname, '\n Host object:', host, host.toString());
console.log('failed host object: ');
console.log(host.toString());
}); });
showAppsMode(); showAppsMode();
@ -499,7 +490,7 @@ function showApps(host) {
// set the layout to the initial mode you see when you open moonlight // set the layout to the initial mode you see when you open moonlight
function showHostsAndSettingsMode() { function showHostsAndSettingsMode() {
console.log('entering show hosts and settings mode.'); console.log('%c[index.js]', 'color: green;', 'Entering "Show apps and hosts" mode');
$("#main-navigation").show(); $("#main-navigation").show();
$(".nav-menu-parent").show(); $(".nav-menu-parent").show();
$("#externalAudioBtn").show(); $("#externalAudioBtn").show();
@ -514,7 +505,7 @@ function showHostsAndSettingsMode() {
} }
function showAppsMode() { function showAppsMode() {
console.log("entering show apps mode."); console.log('%c[index.js]', 'color: green;', 'Entrering "Show apps" mode');
$('#backIcon').show(); $('#backIcon').show();
$("#main-navigation").show(); $("#main-navigation").show();
$("#main-content").children().not("#listener, #loadingSpinner, #naclSpinner").show(); $("#main-content").children().not("#listener, #loadingSpinner, #naclSpinner").show();
@ -537,8 +528,8 @@ function showAppsMode() {
// if the given app is already running, just resume it. // if the given app is already running, just resume it.
function startGame(host, appID) { function startGame(host, appID) {
if(!host || !host.paired) { if(!host || !host.paired) {
console.log('attempted to start a game, but `host` did not initialize properly. Failing!'); console.error('%c[index.js, startGame]', 'color: green;', 'Attempted to start a game, but `host` did not initialize properly. Host object: ', host);
return; return;
} }
// refresh the server info, because the user might have quit the game. // refresh the server info, because the user might have quit the game.
@ -555,11 +546,11 @@ function startGame(host, appID) {
$('#cancelQuitApp').off('click'); $('#cancelQuitApp').off('click');
$('#cancelQuitApp').on('click', function () { $('#cancelQuitApp').on('click', function () {
quitAppDialog.close(); quitAppDialog.close();
console.log('closing app dialog, and returning'); console.log('[index.js, startGame]','color: green;', 'Closing app dialog, and returning');
}); });
$('#continueQuitApp').off('click'); $('#continueQuitApp').off('click');
$('#continueQuitApp').on('click', function () { $('#continueQuitApp').on('click', function () {
console.log('stopping game, and closing app dialog, and returning'); console.log('[index.js, startGame]','color: green;', 'Stopping game, and closing app dialog, and returning');
stopGame(host, function () { stopGame(host, function () {
// please oh please don't infinite loop with recursion // please oh please don't infinite loop with recursion
startGame(host, appID); startGame(host, appID);
@ -569,10 +560,7 @@ function startGame(host, appID) {
return; return;
}, function (failedCurrentApp) { }, function (failedCurrentApp) {
console.log('ERROR: failed to get the current running app from host!'); console.error('[index.js, startGame]','color: green;', 'Failed to get the current running app from host! Returned error was:' + failedCurrentApp, '\n Host object:', host, host.toString());
console.log('Returned error was: ' + failedCurrentApp);
console.log('failed host object: ');
console.log(host.toString());
return; return;
}); });
return; return;
@ -583,7 +571,7 @@ function startGame(host, appID) {
var streamHeight = $('#selectResolution').data('value').split(':')[1]; var streamHeight = $('#selectResolution').data('value').split(':')[1];
// we told the user it was in Mbps. We're dirty liars and use Kbps behind their back. // we told the user it was in Mbps. We're dirty liars and use Kbps behind their back.
var bitrate = parseInt($("#bitrateSlider").val()) * 1000; var bitrate = parseInt($("#bitrateSlider").val()) * 1000;
console.log('startRequest:' + host.address + ":" + streamWidth + ":" + streamHeight + ":" + frameRate + ":" + bitrate); console.log('%c[index.js, startGame]','color:green;', 'startRequest:' + host.address + ":" + streamWidth + ":" + streamHeight + ":" + frameRate + ":" + bitrate);
var rikey = generateRemoteInputKey(); var rikey = generateRemoteInputKey();
var rikeyid = generateRemoteInputKeyId(); var rikeyid = generateRemoteInputKeyId();
@ -596,8 +584,7 @@ function startGame(host, appID) {
sendMessage('startRequest', [host.address, streamWidth, streamHeight, frameRate, sendMessage('startRequest', [host.address, streamWidth, streamHeight, frameRate,
bitrate.toString(), rikey, rikeyid.toString(), host.appVersion]); bitrate.toString(), rikey, rikeyid.toString(), host.appVersion]);
}, function (failedResumeApp) { }, function (failedResumeApp) {
console.log('ERROR: failed to resume the app!'); console.eror('%c[index.js, startGame]', 'color:green;', 'Failed to resume the app! Returned error was' + failedResumeApp);
console.log('Returned error was: ' + failedResumeApp);
return; return;
}); });
} }
@ -614,8 +601,7 @@ function startGame(host, appID) {
sendMessage('startRequest', [host.address, streamWidth, streamHeight, frameRate, sendMessage('startRequest', [host.address, streamWidth, streamHeight, frameRate,
bitrate.toString(), rikey, rikeyid.toString(), host.appVersion]); bitrate.toString(), rikey, rikeyid.toString(), host.appVersion]);
}, function (failedLaunchApp) { }, function (failedLaunchApp) {
console.log('ERROR: failed to launch app with appID: ' + appID); console.error('%c[index.js, launchApp]','color: green;','Failed to launch app width id: ' + appID + '\nReturned error was: ' + failedLaunchApp);
console.log('Returned error was: ' + failedLaunchApp);
return; return;
}); });
@ -624,7 +610,7 @@ function startGame(host, appID) {
} }
function playGameMode() { function playGameMode() {
console.log("entering play game mode"); console.log('%c[index.js, playGameMode]', 'color:green;', 'Entering play game mode');
isInGame = true; isInGame = true;
$("#main-navigation").hide(); $("#main-navigation").hide();
@ -667,12 +653,12 @@ function stopGameWithConfirmation() {
quitAppDialog.showModal(); quitAppDialog.showModal();
$('#cancelQuitApp').off('click'); $('#cancelQuitApp').off('click');
$('#cancelQuitApp').on('click', function () { $('#cancelQuitApp').on('click', function () {
console.log('closing app dialog, and returning'); console.log('%c[index.js, stopGameWithConfirmation]', 'color:green;', 'Closing app dialog, and returning');
quitAppDialog.close(); quitAppDialog.close();
}); });
$('#continueQuitApp').off('click'); $('#continueQuitApp').off('click');
$('#continueQuitApp').on('click', function () { $('#continueQuitApp').on('click', function () {
console.log('stopping game, and closing app dialog, and returning'); console.log('%c[index.js, stopGameWithConfirmation]', 'color:green;', 'Stopping game, and closing app dialog, and returning');
stopGame(api); stopGame(api);
quitAppDialog.close(); quitAppDialog.close();
}); });
@ -702,21 +688,16 @@ function stopGame(host, callbackFunction) {
stylizeBoxArt(host, runningApp.id); stylizeBoxArt(host, runningApp.id);
if (typeof(callbackFunction) === "function") callbackFunction(); if (typeof(callbackFunction) === "function") callbackFunction();
}, function (failedRefreshInfo2) { }, function (failedRefreshInfo2) {
console.log('ERROR: failed to refresh server info!'); console.error('%c[index.js, stopGame]', 'color:green;', 'Failed to refresh server info! Returned error was:' + failedRefreshInfo + ' and failed server was:', host, host.toString());
console.log('Returned error was: ' + failedRefreshInfo2);
console.log('failed server was: ' + host.toString());
}); });
}, function (failedQuitApp) { }, function (failedQuitApp) {
console.log('ERROR: failed to quit app!'); console.error('%c[index.js, stopGame]', 'color:green;', 'Failed to quit app! Returned error was:' + failedQuitApp);
console.log('Returned error was: ' + failedQuitApp);
}); });
}, function (failedGetApp) { }, function (failedGetApp) {
console.log('ERROR: failed to get app ID!'); console.error('%c[index.js, stopGame]', 'color:green;', 'Failed to get app ID! Returned error was:' + failedRefreshInfo);
console.log('Returned error was: ' + failedRefreshInfo);
}); });
}, function (failedRefreshInfo) { }, function (failedRefreshInfo) {
console.log('ERROR: failed to refresh server info!'); console.error('%c[index.js, stopGame]', 'color:green;', 'Failed to refresh server info! Returned error was:' + failedRefreshInfo);
console.log('Returned error was: ' + failedRefreshInfo);
}); });
} }
@ -761,7 +742,7 @@ function saveRemoteAudio() {
// checking the new state // checking the new state
setTimeout(function() { setTimeout(function() {
var remoteAudioState = $("#remoteAudioEnabledSwitch").parent().hasClass('is-checked'); var remoteAudioState = $("#remoteAudioEnabledSwitch").parent().hasClass('is-checked');
console.log('saving remote audio state : ' + remoteAudioState); console.log('%c[index.js, saveRemoteAudio]', 'color: green;', 'Saving remote audio state : ' + remoteAudioState);
storeData('remoteAudio', remoteAudioState, null); storeData('remoteAudio', remoteAudioState, null);
}, 100); }, 100);
} }
@ -797,7 +778,7 @@ function updateDefaultBitrate() {
} }
function onWindowLoad(){ function onWindowLoad(){
console.log('Window loaded.'); console.log('%c[index.js]', 'color: green;', 'Moonlight\'s main window loaded');
// don't show the game selection div // don't show the game selection div
$('#gameSelection').css('display', 'none'); $('#gameSelection').css('display', 'none');
@ -869,7 +850,7 @@ function onWindowLoad(){
revivedHost.hostname = hosts[hostUID].hostname; revivedHost.hostname = hosts[hostUID].hostname;
addHostToGrid(revivedHost); addHostToGrid(revivedHost);
} }
console.log('Loaded previously connected hosts.'); console.log('%c[index.js]', 'color: green;', 'Loaded previously connected hosts');
}); });
} }
} }

View File

@ -1,11 +1,18 @@
var callbacks = {} var callbacks = {}
var callbacks_ids = 1; var callbacks_ids = 1;
/**
* var sendMessage - Sends a message with arguments to the NaCl module
*
* @param {String} method A named method
* @param {(String|Array)} params An array of options or a signle string
* @return {void} The NaCl module calls back trought the handleMessage method
*/
var sendMessage = function(method, params) { var sendMessage = function(method, params) {
return new Promise(function(resolve, reject) { return new Promise(function(resolve, reject) {
var id = callbacks_ids++; var id = callbacks_ids++;
callbacks[id] = {'resolve': resolve, 'reject': reject}; callbacks[id] = {'resolve': resolve, 'reject': reject};
common.naclModule.postMessage({ common.naclModule.postMessage({
'callbackId': id, 'callbackId': id,
'method': method, 'method': method,
@ -14,14 +21,20 @@ var sendMessage = function(method, params) {
}); });
} }
/**
* handleMessage - Handles messages from the NaCl module
*
* @param {Object} msg An object given by the NaCl module
* @return {void}
*/
function handleMessage(msg) { function handleMessage(msg) {
if (msg.data.callbackId && callbacks[msg.data.callbackId]) { // if it's a callback, treat it as such if (msg.data.callbackId && callbacks[msg.data.callbackId]) { // if it's a callback, treat it as such
callbacks[msg.data.callbackId][msg.data.type](msg.data.ret); callbacks[msg.data.callbackId][msg.data.type](msg.data.ret);
delete callbacks[msg.data.callbackId] delete callbacks[msg.data.callbackId]
} else { // else, it's just info, or an event } else { // else, it's just info, or an event
console.log(msg.data); console.log('%c[messages.js, handleMessage]', 'color:gray;', 'Message data: ', msg.data)
if(msg.data === 'streamTerminated') { // if it's a recognized event, notify the appropriate function if(msg.data === 'streamTerminated') { // if it's a recognized event, notify the appropriate function
$('#loadingSpinner').css('display', 'none'); // This is a fallback for RTSP handshake failing, which immediately terminates the stream. $('#loadingSpinner').css('display', 'none'); // This is a fallback for RTSP handshake failing, which immediately terminates the stream.
$('body').css('backgroundColor', '#282C38'); $('body').css('backgroundColor', '#282C38');
api.refreshServerInfo().then(function (ret) { // refresh the serverinfo to acknowledge the currently running app api.refreshServerInfo().then(function (ret) { // refresh the serverinfo to acknowledge the currently running app

View File

@ -32,7 +32,7 @@ String.prototype.toHex = function() {
} }
function NvHTTP(address, clientUid, userEnteredAddress = '') { function NvHTTP(address, clientUid, userEnteredAddress = '') {
console.log(this); console.log('%c[utils.js, NvHTTP Object]', 'color: gray;', this);
this.address = address; this.address = address;
this.paired = false; this.paired = false;
this.currentGame = 0; this.currentGame = 0;
@ -95,7 +95,7 @@ NvHTTP.prototype = {
// try HTTPS first // try HTTPS first
return sendMessage('openUrl', [ 'https://' + givenAddress + ':47984' + '/serverinfo?' + this._buildUidStr(), false]).then(function(ret) { return sendMessage('openUrl', [ 'https://' + givenAddress + ':47984' + '/serverinfo?' + this._buildUidStr(), false]).then(function(ret) {
if (!this._parseServerInfo(ret)) { // if that fails if (!this._parseServerInfo(ret)) { // if that fails
console.log('Failed to parse serverinfo from HTTPS, falling back to HTTP'); console.log('%c[utils.js, utils.js, refreshServerInfoAtAddress]', 'color: gray;', 'Failed to parse serverinfo from HTTPS, falling back to HTTP');
// try HTTP as a failover. Useful to clients who aren't paired yet // try HTTP as a failover. Useful to clients who aren't paired yet
return sendMessage('openUrl', [ 'http://' + givenAddress + ':47989' + '/serverinfo?' + this._buildUidStr(), false]).then(function(retHttp) { return sendMessage('openUrl', [ 'http://' + givenAddress + ':47989' + '/serverinfo?' + this._buildUidStr(), false]).then(function(retHttp) {
return this._parseServerInfo(retHttp); return this._parseServerInfo(retHttp);
@ -165,7 +165,7 @@ NvHTTP.prototype = {
this.refreshServerInfoAtAddress(this.userEnteredAddress).then(function(successUserEntered) { this.refreshServerInfoAtAddress(this.userEnteredAddress).then(function(successUserEntered) {
onSuccess(this.userEnteredAddress); onSuccess(this.userEnteredAddress);
}.bind(this), function(failureUserEntered) { }.bind(this), function(failureUserEntered) {
console.log('WARN! Failed to contact host: ' + this.hostname + '\r\n' + this.toString()); console.warn('%c[utils.js, utils.js, selectServerAddress]', 'color: gray;', 'Failed to contact host ' + this.hostname, this);
onFailure(); onFailure();
}.bind(this)); }.bind(this));
}.bind(this)); }.bind(this));
@ -194,7 +194,7 @@ NvHTTP.prototype = {
_prepareForStorage: function() { _prepareForStorage: function() {
this._memCachedBoxArtArray = {}; this._memCachedBoxArtArray = {};
}, },
_parseServerInfo: function(xmlStr) { _parseServerInfo: function(xmlStr) {
$xml = this._parseXML(xmlStr); $xml = this._parseXML(xmlStr);
$root = $xml.find('root'); $root = $xml.find('root');
@ -207,9 +207,8 @@ NvHTTP.prototype = {
// if we received a UID that isn't the one we expected, fail. // if we received a UID that isn't the one we expected, fail.
return false; return false;
} }
console.log('parsing server info: '); console.log('%c[utils.js, _parseServerInfo]', 'color:gray;', 'Parsing server info:', $root);
console.log($root);
this.paired = $root.find("PairStatus").text().trim() == 1; this.paired = $root.find("PairStatus").text().trim() == 1;
this.currentGame = parseInt($root.find("currentgame").text().trim(), 10); this.currentGame = parseInt($root.find("currentgame").text().trim(), 10);
@ -245,44 +244,44 @@ NvHTTP.prototype = {
if ($root.find("state").text().trim().endsWith("_SERVER_AVAILABLE")) { if ($root.find("state").text().trim().endsWith("_SERVER_AVAILABLE")) {
this.currentGame = 0; this.currentGame = 0;
} }
return true; return true;
}, },
getAppById: function (appId) { getAppById: function (appId) {
return this.getAppList().then(function (list) { return this.getAppList().then(function (list) {
var retApp = null; var retApp = null;
list.some(function (app) { list.some(function (app) {
if (app.id == appId) { if (app.id == appId) {
retApp = app; retApp = app;
return true; return true;
} }
return false; return false;
}); });
return retApp; return retApp;
}); });
}, },
getAppByName: function (appName) { getAppByName: function (appName) {
return this.getAppList().then(function (list) { return this.getAppList().then(function (list) {
var retApp = null; var retApp = null;
list.some(function (app) { list.some(function (app) {
if (app.title == appName) { if (app.title == appName) {
retApp = app; retApp = app;
return true; return true;
} }
return false; return false;
}); });
return retApp; return retApp;
}); });
}, },
getAppListWithCacheFlush: function () { getAppListWithCacheFlush: function () {
return sendMessage('openUrl', [this._baseUrlHttps + '/applist?' + this._buildUidStr(), false]).then(function (ret) { return sendMessage('openUrl', [this._baseUrlHttps + '/applist?' + this._buildUidStr(), false]).then(function (ret) {
$xml = this._parseXML(ret); $xml = this._parseXML(ret);
@ -290,14 +289,14 @@ NvHTTP.prototype = {
if ($root.attr("status_code") != 200) { if ($root.attr("status_code") != 200) {
// TODO: Bubble up an error here // TODO: Bubble up an error here
console.log('applist request failed: ' + $root.attr("status_code")); console.error('%c[utils.js, utils.js, getAppListWithCacheFlush]', 'color: gray;', 'Applist request failed', $root.attr("status_code"));
return []; return [];
} }
var rootElement = $xml.find("root")[0]; var rootElement = $xml.find("root")[0];
var appElements = rootElement.getElementsByTagName("App"); var appElements = rootElement.getElementsByTagName("App");
var appList = []; var appList = [];
for (var i = 0, len = appElements.length; i < len; i++) { for (var i = 0, len = appElements.length; i < len; i++) {
appList.push({ appList.push({
title: appElements[i].getElementsByTagName("AppTitle")[0].innerHTML.trim(), title: appElements[i].getElementsByTagName("AppTitle")[0].innerHTML.trim(),
@ -306,7 +305,7 @@ NvHTTP.prototype = {
} }
this._memCachedApplist = appList; this._memCachedApplist = appList;
return appList; return appList;
}.bind(this)); }.bind(this));
}, },
@ -314,7 +313,7 @@ NvHTTP.prototype = {
getAppList: function () { getAppList: function () {
if (this._memCachedApplist) { if (this._memCachedApplist) {
return new Promise(function (resolve, reject) { return new Promise(function (resolve, reject) {
console.log('returning memory cached app list'); console.log('%c[utils.js, utils.js]', 'color: gray;', 'Returning memory-cached apps list');
resolve(this._memCachedApplist); resolve(this._memCachedApplist);
return; return;
}.bind(this)); }.bind(this));
@ -327,12 +326,12 @@ NvHTTP.prototype = {
// this is inefficient, but works well. // this is inefficient, but works well.
warmBoxArtCache: function () { warmBoxArtCache: function () {
if (!this.paired) { if (!this.paired) {
console.log('not warming box art cache from unpaired host.'); console.log('%c[utils.js, warmBoxArtCache]', 'color: grey;', 'Not warming box art cache for unpaired host');
return; return;
} }
if (Object.keys(this._memCachedBoxArtArray).length != 0) { if (Object.keys(this._memCachedBoxArtArray).length != 0) {
console.log('box art cache already warmed.'); console.log('%c[utils.js, warmBoxArtCache]', 'color: grey;', 'Box art cache already warmed');
return; return;
} }
if (chrome.storage) { if (chrome.storage) {
chrome.storage.local.get('boxArtCache', function(JSONCachedBoxArtArray) { chrome.storage.local.get('boxArtCache', function(JSONCachedBoxArtArray) {
@ -343,15 +342,15 @@ NvHTTP.prototype = {
for (var key in storedBoxArtArray) { for (var key in storedBoxArtArray) {
this._memCachedBoxArtArray[key] = _base64ToArrayBuffer(storedBoxArtArray[key]); this._memCachedBoxArtArray[key] = _base64ToArrayBuffer(storedBoxArtArray[key]);
} }
console.log('box art cache warmed.'); console.log('%c[utils.js, warmBoxArtCache]', 'color: grey;', 'Box art cache warmed');
} else { } else {
console.log('WARN: no box art found in storage. Cannot warm cache!'); console.warn('%c[utils.js, warmBoxArtCache]', 'color: grey;', 'No box art found in storage. Cannot warm cache!');
return; return;
} }
}.bind(this)); }.bind(this));
} }
}, },
// returns the box art of the given appID. // returns the box art of the given appID.
// three layers of response time are possible: memory cached (in javascript), storage cached (in chrome.storage.local), and streamed (host sends binary over the network) // three layers of response time are possible: memory cached (in javascript), storage cached (in chrome.storage.local), and streamed (host sends binary over the network)
getBoxArt: function (appId) { getBoxArt: function (appId) {
@ -361,13 +360,13 @@ NvHTTP.prototype = {
if (this._memCachedBoxArtArray[appId] === null) { if (this._memCachedBoxArtArray[appId] === null) {
// This means a previous box art request failed, don't try again // This means a previous box art request failed, don't try again
return new Promise(function (resolve, reject) { return new Promise(function (resolve, reject) {
console.log('returning cached box art failure result'); console.error('%c[utils.js, utils.js, getBoxArt]', 'color: gray;', 'Returning cached box-art failure result')
reject(null); reject(null);
return; return;
}.bind(this)); }.bind(this));
} else if (this._memCachedBoxArtArray[appId] !== undefined) { } else if (this._memCachedBoxArtArray[appId] !== undefined) {
return new Promise(function (resolve, reject) { return new Promise(function (resolve, reject) {
console.log('returning memory cached box art'); console.log('%c[utils.js, utils.js, getBoxArt]', 'color: gray;', 'Returning memory-cached box-art');
resolve(this._memCachedBoxArtArray[appId]); resolve(this._memCachedBoxArtArray[appId]);
return; return;
}.bind(this)); }.bind(this));
@ -392,7 +391,7 @@ NvHTTP.prototype = {
// if we already have it, load it. // if we already have it, load it.
if (storedBoxArtArray[appId] !== undefined && Object.keys(storedBoxArtArray).length !== 0 && storedBoxArtArray[appId].constructor !== Object) { if (storedBoxArtArray[appId] !== undefined && Object.keys(storedBoxArtArray).length !== 0 && storedBoxArtArray[appId].constructor !== Object) {
console.log('returning storage cached box art'); console.log('%c[utils.js, getBoxArt]', 'color: gray;', 'Returning strage-cached box art for app: ', appId);
resolve(storedBoxArtArray[appId]); resolve(storedBoxArtArray[appId]);
return; return;
} }
@ -401,7 +400,7 @@ NvHTTP.prototype = {
sendMessage('openUrl', [ sendMessage('openUrl', [
this._baseUrlHttps + this._baseUrlHttps +
'/appasset?'+this._buildUidStr() + '/appasset?'+this._buildUidStr() +
'&appid=' + appId + '&appid=' + appId +
'&AssetType=2&AssetIdx=0', '&AssetType=2&AssetIdx=0',
true true
]).then(function(streamedBoxArt) { ]).then(function(streamedBoxArt) {
@ -416,13 +415,13 @@ NvHTTP.prototype = {
obj['boxArtCache'] = arrayToStore; // storage is in JSON format. JSON does not support binary data. obj['boxArtCache'] = arrayToStore; // storage is in JSON format. JSON does not support binary data.
chrome.storage.local.set(obj, function(onSuccess) {}); chrome.storage.local.set(obj, function(onSuccess) {});
console.log('returning streamed box art'); console.log('%c[utils.js, utils.js, getBoxArt]', 'color: gray;', 'Returning streamed box art');
resolve(streamedBoxArt); resolve(streamedBoxArt);
return; return;
}.bind(this), function(error) { }.bind(this), function(error) {
// Cache the failure but not persistently // Cache the failure but not persistently
this._memCachedBoxArtArray[appId] = null; this._memCachedBoxArtArray[appId] = null;
console.log('box art request failed'); console.error('%c[utils.js, utils.js, getBoxArt]', 'color: gray;', 'Box-art request failed!', error);
reject(error); reject(error);
return; return;
}.bind(this)); }.bind(this));
@ -430,17 +429,17 @@ NvHTTP.prototype = {
}.bind(this)); }.bind(this));
} else { // shouldn't run because we always have chrome.storage, but I'm not going to antagonize other browsers } else { // shouldn't run because we always have chrome.storage, but I'm not going to antagonize other browsers
console.log('WARN: Chrome.storage not detected! Box art will not be saved!'); console.warn('%c[utils.js, utils.js, getBoxArt]', 'color: gray;', 'chrome.storage not detected! Box art will not be saved!');
return sendMessage('openUrl', [ return sendMessage('openUrl', [
this._baseUrlHttps + this._baseUrlHttps +
'/appasset?'+this._buildUidStr() + '/appasset?'+this._buildUidStr() +
'&appid=' + appId + '&appid=' + appId +
'&AssetType=2&AssetIdx=0', '&AssetType=2&AssetIdx=0',
true true
]); ]);
} }
}, },
launchApp: function (appId, mode, sops, rikey, rikeyid, localAudio, surroundAudioInfo) { launchApp: function (appId, mode, sops, rikey, rikeyid, localAudio, surroundAudioInfo) {
return sendMessage('openUrl', [ return sendMessage('openUrl', [
this._baseUrlHttps + this._baseUrlHttps +
@ -457,7 +456,7 @@ NvHTTP.prototype = {
return true; return true;
}); });
}, },
resumeApp: function (rikey, rikeyid) { resumeApp: function (rikey, rikeyid) {
return sendMessage('openUrl', [ return sendMessage('openUrl', [
this._baseUrlHttps + this._baseUrlHttps +
@ -469,7 +468,7 @@ NvHTTP.prototype = {
return true; return true;
}); });
}, },
quitApp: function () { quitApp: function () {
return sendMessage('openUrl', [this._baseUrlHttps + '/cancel?' + this._buildUidStr(), false]) return sendMessage('openUrl', [this._baseUrlHttps + '/cancel?' + this._buildUidStr(), false])
// Refresh server info after quitting because it may silently fail if the // Refresh server info after quitting because it may silently fail if the
@ -477,15 +476,15 @@ NvHTTP.prototype = {
// TODO: We should probably bubble this up to our caller. // TODO: We should probably bubble this up to our caller.
.then(this.refreshServerInfo()); .then(this.refreshServerInfo());
}, },
pair: function(randomNumber) { pair: function(randomNumber) {
return this.refreshServerInfo().then(function () { return this.refreshServerInfo().then(function () {
if (this.paired) if (this.paired)
return true; return true;
if (this.currentGame != 0) if (this.currentGame != 0)
return false; return false;
return sendMessage('pair', [this.serverMajorVersion.toString(), this.address, randomNumber]).then(function (pairStatus) { return sendMessage('pair', [this.serverMajorVersion.toString(), this.address, randomNumber]).then(function (pairStatus) {
return sendMessage('openUrl', [this._baseUrlHttps + '/pair?uniqueid=' + this.clientUid + '&devicename=roth&updateState=1&phrase=pairchallenge', false]).then(function (ret) { return sendMessage('openUrl', [this._baseUrlHttps + '/pair?uniqueid=' + this.clientUid + '&devicename=roth&updateState=1&phrase=pairchallenge', false]).then(function (ret) {
$xml = this._parseXML(ret); $xml = this._parseXML(ret);
@ -495,11 +494,11 @@ NvHTTP.prototype = {
}.bind(this)); }.bind(this));
}.bind(this)); }.bind(this));
}, },
_buildUidStr: function () { _buildUidStr: function () {
return 'uniqueid=' + this.clientUid + '&uuid=' + guuid(); return 'uniqueid=' + this.clientUid + '&uuid=' + guuid();
}, },
_parseXML: function (xmlData) { _parseXML: function (xmlData) {
return $($.parseXML(xmlData.toString())); return $($.parseXML(xmlData.toString()));
}, },