JS updates, courtesy of IntelliJ's recommendations

- Changed from var to let
- cached a few JQuery selectors
- added a few semicolons
- standardized indentation back to spaces
- removed dead code from utils.js
- switched from == to === to eliminate coercion
This commit is contained in:
R. Aidan Campbell 2017-10-07 14:24:21 -07:00
parent e0c4c01e44
commit c6390338e3
2 changed files with 289 additions and 290 deletions

View File

@ -36,9 +36,11 @@ function fullscreenChromeWindow() {
}
function loadWindowState() {
if (!chrome.storage) { return; }
if (!chrome.storage) {
return;
}
chrome.storage.sync.get('windowState', function(item) {
chrome.storage.sync.get('windowState', function (item) {
// load stored window state
windowState = (item && item.windowState)
? item.windowState
@ -51,14 +53,14 @@ function loadWindowState() {
}
function onFullscreened() {
if (!isInGame && windowState == 'normal') {
if (!isInGame && windowState === 'normal') {
storeData('windowState', 'fullscreen', null);
windowState = 'fullscreen';
}
}
function onBoundsChanged() {
if (!isInGame && windowState == 'fullscreen') {
if (!isInGame && windowState === 'fullscreen') {
storeData('windowState', 'normal', null);
windowState = 'normal';
}
@ -72,13 +74,13 @@ function changeUiModeForNaClLoad() {
}
function startPollingHosts() {
for(var hostUID in hosts) {
for (let hostUID in hosts) {
beginBackgroundPollingOfHost(hosts[hostUID]);
}
}
function stopPollingHosts() {
for(var hostUID in hosts) {
for (let hostUID in hosts) {
stopBackgroundPollingOfHost(hosts[hostUID]);
}
}
@ -92,18 +94,18 @@ function restoreUiAfterNaClLoad() {
findNvService(function (finder, opt_error) {
if (finder.byService_['_nvstream._tcp']) {
var ips = Object.keys(finder.byService_['_nvstream._tcp']);
for (var i in ips) {
var ip = ips[i];
let ips = Object.keys(finder.byService_['_nvstream._tcp']);
for (let i in ips) {
let ip = ips[i];
if (finder.byService_['_nvstream._tcp'][ip]) {
var mDnsDiscoveredHost = new NvHTTP(ip, myUniqueid);
mDnsDiscoveredHost.pollServer(function(returneMdnsDiscoveredHost) {
let mDnsDiscoveredHost = new NvHTTP(ip, myUniqueid);
mDnsDiscoveredHost.pollServer(function (returneMdnsDiscoveredHost) {
// Just drop this if the host doesn't respond
if (!returneMdnsDiscoveredHost.online) {
return;
}
if (hosts[returneMdnsDiscoveredHost.serverUid] != null) {
if (hosts[returneMdnsDiscoveredHost.serverUid] !== null) {
// if we're seeing a host we've already seen before, update it for the current local IP.
hosts[returneMdnsDiscoveredHost.serverUid].address = returneMdnsDiscoveredHost.address;
} else {
@ -122,7 +124,7 @@ function beginBackgroundPollingOfHost(host) {
if (host.online) {
$("#hostgrid-" + host.serverUid).removeClass('host-cell-inactive');
// The host was already online. Just start polling in the background now.
activePolls[host.serverUid] = window.setInterval(function() {
activePolls[host.serverUid] = window.setInterval(function () {
// every 5 seconds, poll at the address we know it was live at
host.pollServer(function () {
if (host.online) {
@ -143,7 +145,7 @@ function beginBackgroundPollingOfHost(host) {
}
// Now start background polling
activePolls[host.serverUid] = window.setInterval(function() {
activePolls[host.serverUid] = window.setInterval(function () {
// every 5 seconds, poll at the address we know it was live at
host.pollServer(function () {
if (host.online) {
@ -158,14 +160,14 @@ function beginBackgroundPollingOfHost(host) {
}
function stopBackgroundPollingOfHost(host) {
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]);
delete activePolls[host.serverUid];
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]);
delete activePolls[host.serverUid];
}
function snackbarLog(givenMessage) {
console.log('%c[index.js, snackbarLog]', 'color: green;', givenMessage);
var data = {
let data = {
message: givenMessage,
timeout: 2000
};
@ -174,7 +176,7 @@ function snackbarLog(givenMessage) {
function snackbarLogLong(givenMessage) {
console.log('%c[index.js, snackbarLog]', 'color: green;', givenMessage);
var data = {
let data = {
message: givenMessage,
timeout: 5000
};
@ -187,14 +189,14 @@ function updateBitrateField() {
}
function moduleDidLoad() {
if(!myUniqueid) {
console.warn('%c[index.js, moduleDidLoad]', 'color: green;', 'Failed to get uniqueId. We should have already generated one. Regenerating...');
myUniqueid = uniqueid();
storeData('uniqueid', myUniqueid, null);
if (!myUniqueid) {
console.warn('%c[index.js, moduleDidLoad]', 'color: green;', 'Failed to get uniqueId. We should have already generated one. Regenerating...');
myUniqueid = uniqueid();
storeData('uniqueid', myUniqueid, null);
}
if(!pairingCert) { // we couldn't load a cert. Make one.
console.warn('%c[index.js, moduleDidLoad]', 'color: green;', 'Failed to load local cert. Generating new one');
if (!pairingCert) { // we couldn't load a cert. Make one.
console.warn('%c[index.js, moduleDidLoad]', 'color: green;', 'Failed to load local cert. Generating new one');
sendMessage('makeCert', []).then(function (cert) {
storeData('cert', cert, null);
pairingCert = cert;
@ -205,7 +207,7 @@ function moduleDidLoad() {
sendMessage('httpInit', [pairingCert.cert, pairingCert.privateKey, myUniqueid]).then(function (ret) {
restoreUiAfterNaClLoad();
}, function (failedInit) {
console.error('%c[index.js, moduleDidLoad]', 'color: green;', 'Failed httpInit! Returned error was: ', failedInit);
console.error('%c[index.js, moduleDidLoad]', 'color: green;', 'Failed httpInit! Returned error was: ', failedInit);
});
});
}
@ -213,14 +215,14 @@ function moduleDidLoad() {
sendMessage('httpInit', [pairingCert.cert, pairingCert.privateKey, myUniqueid]).then(function (ret) {
restoreUiAfterNaClLoad();
}, function (failedInit) {
console.error('%c[index.js, moduleDidLoad]', 'color: green;', 'Failed httpInit! Returned error was: ', failedInit);
console.error('%c[index.js, moduleDidLoad]', 'color: green;', 'Failed httpInit! Returned error was: ', failedInit);
});
}
}
// pair to the given NvHTTP host object. Returns whether pairing was successful.
function pairTo(nvhttpHost, onSuccess, onFailure) {
if(!pairingCert) {
if (!pairingCert) {
snackbarLog('ERROR: cert has not been generated yet. Is NaCl initialized?');
console.warn('%c[index.js]', 'color: green;', 'User wants to pair, and we still have no cert. Problem = very yes.');
onFailure();
@ -240,8 +242,8 @@ function pairTo(nvhttpHost, onSuccess, onFailure) {
return;
}
var randomNumber = String("0000" + (Math.random()*10000|0)).slice(-4);
var pairingDialog = document.querySelector('#pairingDialog');
let randomNumber = String("0000" + (Math.random() * 10000 | 0)).slice(-4);
let pairingDialog = document.querySelector('#pairingDialog');
$('#pairingDialogText').html('Please enter the number ' + randomNumber + ' on the GFE dialog on the computer. This dialog will be dismissed once complete');
pairingDialog.showModal();
@ -253,7 +255,7 @@ function pairTo(nvhttpHost, onSuccess, onFailure) {
console.log('%c[index.js]', 'color: green;', 'Sending pairing request to ' + nvhttpHost.hostname + ' with random number' + randomNumber);
nvhttpHost.pair(randomNumber).then(function (paired) {
if (!paired) {
if (nvhttpHost.currentGame != 0) {
if (nvhttpHost.currentGame !== 0) {
$('#pairingDialogText').html('Error: ' + nvhttpHost.hostname + ' is busy. Stop streaming to pair.');
} else {
$('#pairingDialogText').html('Error: failed to pair with ' + nvhttpHost.hostname + '.');
@ -287,13 +289,13 @@ function hostChosen(host) {
api = host;
if (!host.paired) {
// Still not paired; go to the pairing flow
pairTo(host, function() {
showApps(host);
saveHosts();
},
function(){
pairTo(host, function () {
showApps(host);
saveHosts();
},
function () {
startPollingHosts();
});
});
} else {
// When we queried again, it was paired, so show apps.
showApps(host);
@ -303,24 +305,24 @@ function hostChosen(host) {
// the `+` was selected on the host grid.
// give the user a dialog to input connection details for the PC
function addHost() {
var modal = document.querySelector('#addHostDialog');
let modal = document.querySelector('#addHostDialog');
modal.showModal();
// drop the dialog if they cancel
$('#cancelAddHost').off('click');
$('#cancelAddHost').on('click', function() {
$('#cancelAddHost').on('click', function () {
modal.close();
});
// try to pair if they continue
$('#continueAddHost').off('click');
$('#continueAddHost').on('click', function () {
var inputHost = $('#dialogInputHost').val();
var _nvhttpHost = new NvHTTP(inputHost, myUniqueid, inputHost);
let inputHost = $('#dialogInputHost').val();
let _nvhttpHost = new NvHTTP(inputHost, myUniqueid, inputHost);
pairTo(_nvhttpHost, function() {
pairTo(_nvhttpHost, function () {
// Check if we already have record of this host
if (hosts[_nvhttpHost.serverUid] != null) {
if (hosts[_nvhttpHost.serverUid] !== null) {
// Just update the addresses
hosts[_nvhttpHost.serverUid].address = _nvhttpHost.address;
hosts[_nvhttpHost.serverUid].userEnteredAddress = _nvhttpHost.userEnteredAddress;
@ -330,7 +332,7 @@ function addHost() {
addHostToGrid(_nvhttpHost);
}
saveHosts();
}, function() {
}, function () {
snackbarLog('pairing to ' + inputHost + ' failed!');
});
modal.close();
@ -341,10 +343,22 @@ function addHost() {
// host is an NvHTTP object
function addHostToGrid(host, ismDNSDiscovered) {
var outerDiv = $("<div>", {class: 'host-container mdl-card mdl-shadow--4dp', id: 'host-container-' + host.serverUid, role: 'link', tabindex: 0, 'aria-label': host.hostname });
var cell = $("<div>", {class: 'mdl-card__title mdl-card--expand', id: 'hostgrid-' + host.serverUid });
let outerDiv = $("<div>", {
class: 'host-container mdl-card mdl-shadow--4dp',
id: 'host-container-' + host.serverUid,
role: 'link',
tabindex: 0,
'aria-label': host.hostname
});
let cell = $("<div>", {class: 'mdl-card__title mdl-card--expand', id: 'hostgrid-' + host.serverUid});
$(cell).prepend($("<h2>", {class: "mdl-card__title-text", html: host.hostname}));
var removalButton = $("<div>", {class: "remove-host", id: "removeHostButton-" + host.serverUid, role: 'button', tabindex: 0, 'aria-label': 'Remove host ' + host.hostname});
let removalButton = $("<div>", {
class: "remove-host",
id: "removeHostButton-" + host.serverUid,
role: 'button',
tabindex: 0,
'aria-label': 'Remove host ' + host.hostname
});
removalButton.off('click');
removalButton.click(function () {
removeClicked(host);
@ -353,10 +367,10 @@ function addHostToGrid(host, ismDNSDiscovered) {
cell.click(function () {
hostChosen(host);
});
outerDiv.keypress(function(e){
if(e.keyCode == 13) {
hostChosen(host);
}
outerDiv.keypress(function (e) {
if (e.keyCode === 13) {
hostChosen(host);
}
});
$(outerDiv).append(cell);
if (!ismDNSDiscovered) {
@ -368,9 +382,9 @@ function addHostToGrid(host, ismDNSDiscovered) {
}
function removeClicked(host) {
var deleteHostDialog = document.querySelector('#deleteHostDialog');
let deleteHostDialog = document.querySelector('#deleteHostDialog');
document.getElementById('deleteHostDialogText').innerHTML =
' Are you sure you want to delete ' + host.hostname + '?';
' Are you sure you want to delete ' + host.hostname + '?';
deleteHostDialog.showModal();
$('#cancelDeleteHost').off('click');
@ -383,7 +397,6 @@ function removeClicked(host) {
// this means we can re-add the host, and will still be paired.
$('#continueDeleteHost').off('click');
$('#continueDeleteHost').on('click', function () {
var deleteHostDialog = document.querySelector('#deleteHostDialog');
$('#host-container-' + host.serverUid).remove();
delete hosts[host.serverUid]; // remove the host from the array;
saveHosts();
@ -397,24 +410,25 @@ function removeClicked(host) {
// the function was made like this so that we can remove duplicated code, but
// not do N*N stylizations of the box art, or make the code not flow very well
function stylizeBoxArt(freshApi, appIdToStylize) {
if (freshApi.currentGame === appIdToStylize){ // stylize the currently running game
let app_selector = $('#game-' + app.id);
if (freshApi.currentGame === appIdToStylize) { // stylize the currently running game
// destylize it, if it has the not-current-game style
if ($('#game-'+ appIdToStylize).hasClass("not-current-game")) $('#game-'+ appIdToStylize).removeClass("not-current-game");
if (app_selector.hasClass("not-current-game")) $('#game-' + appIdToStylize).removeClass("not-current-game");
// add the current-game style
$('#game-'+ appIdToStylize).addClass("current-game");
app_selector.addClass("current-game");
} else {
// destylize it, if it has the current-game style
if ($('#game-'+ appIdToStylize).hasClass("current-game")) $('#game-'+ appIdToStylize).removeClass("current-game");
if (app_selector.hasClass("current-game")) $('#game-' + appIdToStylize).removeClass("current-game");
// add the not-current-game style
$('#game-'+ appIdToStylize).addClass('not-current-game');
app_selector.addClass('not-current-game');
}
}
// show the app list
function showApps(host) {
if(!host || !host.paired) { // safety checking. shouldn't happen.
console.log('%c[index.js, showApps]', 'color: green;', 'Moved into showApps, but `host` did not initialize properly! Failing.');
return;
if (!host || !host.paired) { // safety checking. shouldn't happen.
console.log('%c[index.js, showApps]', 'color: green;', 'Moved into showApps, but `host` did not initialize properly! Failing.');
return;
}
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();
@ -433,26 +447,39 @@ function showApps(host) {
appList.forEach(function (app) {
host.getBoxArt(app.id).then(function (resolvedPromise) {
let app_selector = $('#game-' + app.id);
// put the box art into the image holder
if ($('#game-' + app.id).length === 0) {
if (app_selector.length === 0) {
// double clicking the button will cause multiple box arts to appear.
// to mitigate this we ensure we don't add a duplicate.
// This isn't perfect: there's lots of RTTs before the logic prevents anything
var imageBlob = new Blob([resolvedPromise], {type: "image/png"});
var outerDiv = $("<div>", {class: 'game-container mdl-card mdl-shadow--4dp', id: 'game-'+app.id, backgroundImage: URL.createObjectURL(imageBlob), role: 'link', tabindex: 0, title: app.title, 'aria-label': app.title });
$(outerDiv).append($("<img \>", {src: URL.createObjectURL(imageBlob), id: 'game-'+app.id, name: app.title }));
$(outerDiv).append($("<div>", {class: "game-title", html: $("<span>", {html: app.title} )}));
let imageBlob = new Blob([resolvedPromise], {type: "image/png"});
let outerDiv = $("<div>", {
class: 'game-container mdl-card mdl-shadow--4dp',
id: 'game-' + app.id,
backgroundImage: URL.createObjectURL(imageBlob),
role: 'link',
tabindex: 0,
title: app.title,
'aria-label': app.title
});
$(outerDiv).append($("<img \>", {
src: URL.createObjectURL(imageBlob),
id: 'game-' + app.id,
name: app.title
}));
$(outerDiv).append($("<div>", {class: "game-title", html: $("<span>", {html: app.title})}));
$("#game-grid").append(outerDiv);
// $("#gameList").append($("<div>", {html:$("<img \>", {src: URL.createObjectURL(imageBlob), id: 'game-'+app.id, name: app.title }), class: 'box-art mdl-cell mdl-cell--3-col'}).append($("<span>", {html: app.title, class:"game-title"})));
$('#game-'+app.id).on('click', function () {
app_selector.on('click', function () {
startGame(host, app.id);
});
$('#game-'+app.id).keypress(function(e){
if(e.keyCode == 13) {
startGame(host, app.id);
}
app_selector.keypress(function (e) {
if (e.keyCode === 13) {
startGame(host, app.id);
}
});
// apply CSS stylization to indicate whether the app is active
@ -460,18 +487,26 @@ function showApps(host) {
}
}, function (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('%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());
if ($('#game-' + app.id).length === 0) {
// double clicking the button will cause multiple box arts to appear.
// to mitigate this we ensure we don't add a duplicate.
// This isn't perfect: there's lots of RTTs before the logic prevents anything
var outerDiv = $("<div>", {class: 'game-container mdl-card mdl-shadow--4dp', id: 'game-'+app.id, backgroundImage: "static/res/no_app_image.png" });
$(outerDiv).append($("<img \>", {src: "static/res/no_app_image.png", id: 'game-'+app.id, name: app.title }));
$(outerDiv).append($("<div>", {class: "game-title", html: $("<span>", {html: app.title} )}));
let outerDiv = $("<div>", {
class: 'game-container mdl-card mdl-shadow--4dp',
id: 'game-' + app.id,
backgroundImage: "static/res/no_app_image.png"
});
$(outerDiv).append($("<img \>", {
src: "static/res/no_app_image.png",
id: 'game-' + app.id,
name: app.title
}));
$(outerDiv).append($("<div>", {class: "game-title", html: $("<span>", {html: app.title})}));
$("#game-grid").append(outerDiv);
$('#game-'+app.id).on('click', function () {
$('#game-' + app.id).on('click', function () {
startGame(host, app.id);
});
@ -528,18 +563,18 @@ function showAppsMode() {
// start the given appID. if another app is running, offer to quit it.
// if the given app is already running, just resume it.
function startGame(host, appID) {
if(!host || !host.paired) {
console.error('%c[index.js, startGame]', 'color: green;', 'Attempted to start a game, but `host` did not initialize properly. Host object: ', host);
return;
if (!host || !host.paired) {
console.error('%c[index.js, startGame]', 'color: green;', 'Attempted to start a game, but `host` did not initialize properly. Host object: ', host);
return;
}
// refresh the server info, because the user might have quit the game.
host.refreshServerInfo().then(function (ret) {
host.getAppById(appID).then(function (appToStart) {
if(host.currentGame != 0 && host.currentGame != appID) {
if (host.currentGame !== 0 && host.currentGame !== appID) {
host.getAppById(host.currentGame).then(function (currentApp) {
var quitAppDialog = document.querySelector('#quitAppDialog');
let quitAppDialog = document.querySelector('#quitAppDialog');
document.getElementById('quitAppDialogText').innerHTML =
currentApp.title + ' is already running. Would you like to quit ' +
currentApp.title + '?';
@ -547,64 +582,59 @@ function startGame(host, appID) {
$('#cancelQuitApp').off('click');
$('#cancelQuitApp').on('click', function () {
quitAppDialog.close();
console.log('[index.js, startGame]','color: green;', 'Closing app dialog, and returning');
console.log('[index.js, startGame]', 'color: green;', 'Closing app dialog, and returning');
});
$('#continueQuitApp').off('click');
$('#continueQuitApp').on('click', function () {
console.log('[index.js, startGame]','color: green;', '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 () {
// please oh please don't infinite loop with recursion
startGame(host, appID);
});
quitAppDialog.close();
});
return;
}, function (failedCurrentApp) {
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());
return;
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());
});
return;
}
var frameRate = $('#selectFramerate').data('value').toString();
var optimize = $("#optimizeGamesSwitch").parent().hasClass('is-checked') ? 1 : 0;
var streamWidth = $('#selectResolution').data('value').split(':')[0];
var streamHeight = $('#selectResolution').data('value').split(':')[1];
let frameRate = $('#selectFramerate').data('value').toString();
let optimize = $("#optimizeGamesSwitch").parent().hasClass('is-checked') ? 1 : 0;
let streamWidth = $('#selectResolution').data('value').split(':')[0];
let streamHeight = $('#selectResolution').data('value').split(':')[1];
// we told the user it was in Mbps. We're dirty liars and use Kbps behind their back.
var bitrate = parseInt($("#bitrateSlider").val()) * 1000;
console.log('%c[index.js, startGame]','color:green;', 'startRequest:' + host.address + ":" + streamWidth + ":" + streamHeight + ":" + frameRate + ":" + bitrate + ":" + optimize);
let bitrate = parseInt($("#bitrateSlider").val()) * 1000;
console.log('%c[index.js, startGame]', 'color:green;', 'startRequest:' + host.address + ":" + streamWidth + ":" + streamHeight + ":" + frameRate + ":" + bitrate + ":" + optimize);
var rikey = generateRemoteInputKey();
var rikeyid = generateRemoteInputKeyId();
let rikey = generateRemoteInputKey();
let rikeyid = generateRemoteInputKeyId();
$('#loadingMessage').text('Starting ' + appToStart.title + '...');
playGameMode();
if(host.currentGame == appID) { // if user wants to launch the already-running app, then we resume it.
if (host.currentGame === appID) { // if user wants to launch the already-running app, then we resume it.
return host.resumeApp(rikey, rikeyid).then(function (ret) {
sendMessage('startRequest', [host.address, streamWidth, streamHeight, frameRate,
bitrate.toString(), rikey, rikeyid.toString(), host.appVersion]);
bitrate.toString(), rikey, rikeyid.toString(), host.appVersion]);
}, function (failedResumeApp) {
console.eror('%c[index.js, startGame]', 'color:green;', 'Failed to resume the app! Returned error was' + failedResumeApp);
return;
console.error('%c[index.js, startGame]', 'color:green;', 'Failed to resume the app! Returned error was' + failedResumeApp);
});
}
var remote_audio_enabled = $("#remoteAudioEnabledSwitch").parent().hasClass('is-checked') ? 1 : 0;
let remote_audio_enabled = $("#remoteAudioEnabledSwitch").parent().hasClass('is-checked') ? 1 : 0;
host.launchApp(appID,
streamWidth + "x" + streamHeight + "x" + frameRate,
optimize, // DON'T Allow GFE (0) to optimize game settings, or ALLOW (1) to optimize game settings
rikey, rikeyid,
remote_audio_enabled, // Play audio locally too?
0x030002 // Surround channel mask << 16 | Surround channel count
).then(function (ret) {
streamWidth + "x" + streamHeight + "x" + frameRate,
optimize, // DON'T Allow GFE (0) to optimize game settings, or ALLOW (1) to optimize game settings
rikey, rikeyid,
remote_audio_enabled, // Play audio locally too?
0x030002 // Surround channel mask << 16 | Surround channel count
).then(function (ret) {
sendMessage('startRequest', [host.address, streamWidth, streamHeight, frameRate,
bitrate.toString(), rikey, rikeyid.toString(), host.appVersion]);
bitrate.toString(), rikey, rikeyid.toString(), host.appVersion]);
}, function (failedLaunchApp) {
console.error('%c[index.js, launchApp]','color: green;','Failed to launch app width id: ' + appID + '\nReturned error was: ' + failedLaunchApp);
return;
console.error('%c[index.js, launchApp]', 'color: green;', 'Failed to launch app width id: ' + appID + '\nReturned error was: ' + failedLaunchApp);
});
});
@ -627,17 +657,17 @@ function playGameMode() {
// Maximize the size of the nacl module by scaling and resizing appropriately
function fullscreenNaclModule() {
var streamWidth = $('#selectResolution').data('value').split(':')[0];
var streamHeight = $('#selectResolution').data('value').split(':')[1];
var screenWidth = window.innerWidth;
var screenHeight = window.innerHeight;
let streamWidth = $('#selectResolution').data('value').split(':')[0];
let streamHeight = $('#selectResolution').data('value').split(':')[1];
let screenWidth = window.innerWidth;
let screenHeight = window.innerHeight;
var xRatio = screenWidth / streamWidth;
var yRatio = screenHeight / streamHeight;
let xRatio = screenWidth / streamWidth;
let yRatio = screenHeight / streamHeight;
var zoom = Math.min(xRatio, yRatio);
let zoom = Math.min(xRatio, yRatio);
var module = $("#nacl_module")[0];
let module = $("#nacl_module")[0];
module.width = zoom * streamWidth;
module.height = zoom * streamHeight;
module.style.paddingTop = ((screenHeight - module.height) / 2) + "px";
@ -648,10 +678,10 @@ function stopGameWithConfirmation() {
snackbarLog('Nothing was running');
} else {
api.getAppById(api.currentGame).then(function (currentGame) {
var quitAppDialog = document.querySelector('#quitAppDialog');
let quitAppDialog = document.querySelector('#quitAppDialog');
document.getElementById('quitAppDialogText').innerHTML =
' Are you sure you would like to quit ' +
currentGame.title + '? Unsaved progress will be lost.';
' Are you sure you would like to quit ' +
currentGame.title + '? Unsaved progress will be lost.';
quitAppDialog.showModal();
$('#cancelQuitApp').off('click');
$('#cancelQuitApp').on('click', function () {
@ -682,7 +712,7 @@ function stopGame(host, callbackFunction) {
snackbarLog('Nothing was running');
return;
}
var appName = runningApp.title;
let appName = runningApp.title;
snackbarLog('Stopping ' + appName);
host.quitApp().then(function (ret2) {
host.refreshServerInfo().then(function (ret3) { // refresh to show no app is currently running.
@ -696,7 +726,7 @@ function stopGame(host, callbackFunction) {
console.error('%c[index.js, stopGame]', 'color:green;', 'Failed to quit app! Returned error was:' + failedQuitApp);
});
}, function (failedGetApp) {
console.error('%c[index.js, stopGame]', 'color:green;', 'Failed to get app ID! Returned error was:' + failedRefreshInfo);
console.error('%c[index.js, stopGame]', 'color:green;', 'Failed to get app ID! Returned error was:' + failedRefreshInfo);
});
}, function (failedRefreshInfo) {
console.error('%c[index.js, stopGame]', 'color:green;', 'Failed to refresh server info! Returned error was:' + failedRefreshInfo);
@ -704,14 +734,14 @@ function stopGame(host, callbackFunction) {
}
function storeData(key, data, callbackFunction) {
var obj = {};
let obj = {};
obj[key] = data;
if(chrome.storage)
if (chrome.storage)
chrome.storage.sync.set(obj, callbackFunction);
}
function saveResolution() {
var chosenResolution = $(this).data('value');
let chosenResolution = $(this).data('value');
$('#selectResolution').text($(this).text()).data('value', chosenResolution);
storeData('resolution', chosenResolution, null);
updateDefaultBitrate();
@ -720,27 +750,26 @@ function saveResolution() {
function saveOptimize() {
// MaterialDesignLight uses the mouseup trigger, so we give it some time to change the class name before
// checking the new state
setTimeout(function() {
var chosenOptimize = $("#optimizeGamesSwitch").parent().hasClass('is-checked');
setTimeout(function () {
let chosenOptimize = $("#optimizeGamesSwitch").parent().hasClass('is-checked');
console.log('%c[index.js, saveOptimize]', 'color: green;', 'Saving optimize state : ' + chosenOptimize);
storeData('optimize', chosenOptimize, null);
}, 100);
}
function saveFramerate() {
var chosenFramerate = $(this).data('value');
let chosenFramerate = $(this).data('value');
$('#selectFramerate').text($(this).text()).data('value', chosenFramerate);
storeData('frameRate', chosenFramerate, null);
updateDefaultBitrate();
}
// storing data in chrome.storage takes the data as an object, and shoves it into JSON to store
// unfortunately, objects with function instances (classes) are stripped of their function instances when converted to a raw object
// so we cannot forget to revive the object after we load it.
function saveHosts() {
for(var hostUID in hosts) {
for (let hostUID in hosts) {
// slim the object down to only store the necessary bytes, because we have limited storage
hosts[hostUID]._prepareForStorage();
}
@ -754,18 +783,18 @@ function saveBitrate() {
function saveRemoteAudio() {
// MaterialDesignLight uses the mouseup trigger, so we give it some time to change the class name before
// checking the new state
setTimeout(function() {
var remoteAudioState = $("#remoteAudioEnabledSwitch").parent().hasClass('is-checked');
setTimeout(function () {
let remoteAudioState = $("#remoteAudioEnabledSwitch").parent().hasClass('is-checked');
console.log('%c[index.js, saveRemoteAudio]', 'color: green;', 'Saving remote audio state : ' + remoteAudioState);
storeData('remoteAudio', remoteAudioState, null);
}, 100);
}
function updateDefaultBitrate() {
var res = $('#selectResolution').data('value');
var frameRate = $('#selectFramerate').data('value').toString();
let res = $('#selectResolution').data('value');
let frameRate = $('#selectFramerate').data('value').toString();
if (res ==="1920:1080") {
if (res === "1920:1080") {
if (frameRate === "30") { // 1080p, 30fps
$('#bitrateSlider')[0].MaterialSlider.change('10');
} else { // 1080p, 60fps
@ -791,17 +820,17 @@ function updateDefaultBitrate() {
saveBitrate();
}
function onWindowLoad(){
function onWindowLoad() {
console.log('%c[index.js]', 'color: green;', 'Moonlight\'s main window loaded');
// don't show the game selection div
$('#gameSelection').css('display', 'none');
loadWindowState();
if(chrome.storage) {
if (chrome.storage) {
// load stored resolution prefs
chrome.storage.sync.get('resolution', function(previousValue) {
if(previousValue.resolution != null) {
chrome.storage.sync.get('resolution', function (previousValue) {
if (previousValue.resolution !== null) {
$('.resolutionMenu li').each(function () {
if ($(this).data('value') === previousValue.resolution) {
$('#selectResolution').text($(this).text()).data('value', previousValue.resolution);
@ -811,19 +840,19 @@ function onWindowLoad(){
});
// Load stored remote audio prefs
chrome.storage.sync.get('remoteAudio', function(previousValue) {
if(previousValue.remoteAudio == null) {
chrome.storage.sync.get('remoteAudio', function (previousValue) {
if (previousValue.remoteAudio === null) {
document.querySelector('#externalAudioBtn').MaterialIconToggle.uncheck();
} else if (previousValue.remoteAudio == false) {
} else if (previousValue.remoteAudio === false) {
document.querySelector('#externalAudioBtn').MaterialIconToggle.uncheck();
} else {
} else {
document.querySelector('#externalAudioBtn').MaterialIconToggle.check();
}
});
// load stored framerate prefs
chrome.storage.sync.get('frameRate', function(previousValue) {
if(previousValue.frameRate != null) {
chrome.storage.sync.get('frameRate', function (previousValue) {
if (previousValue.frameRate !== null) {
$('.framerateMenu li').each(function () {
if ($(this).data('value') === previousValue.frameRate) {
$('#selectFramerate').text($(this).text()).data('value', previousValue.frameRate);
@ -833,31 +862,31 @@ function onWindowLoad(){
});
// load stored optimization prefs
chrome.storage.sync.get('optimize', function(previousValue) {
if (previousValue.optimize == null) {
chrome.storage.sync.get('optimize', function (previousValue) {
if (previousValue.optimize === null) {
document.querySelector('#optimizeGamesBtn').MaterialIconToggle.check();
} else if (previousValue.optimize == false) {
} else if (previousValue.optimize === false) {
document.querySelector('#optimizeGamesBtn').MaterialIconToggle.uncheck();
} else {
} else {
document.querySelector('#optimizeGamesBtn').MaterialIconToggle.check();
}
});
// load stored bitrate prefs
chrome.storage.sync.get('bitrate', function(previousValue) {
$('#bitrateSlider')[0].MaterialSlider.change(previousValue.bitrate != null ? previousValue.bitrate : '10');
chrome.storage.sync.get('bitrate', function (previousValue) {
$('#bitrateSlider')[0].MaterialSlider.change(previousValue.bitrate !== null ? previousValue.bitrate : '10');
updateBitrateField();
});
// load the HTTP cert if we have one.
chrome.storage.sync.get('cert', function(savedCert) {
if (savedCert.cert != null) { // we have a saved cert
chrome.storage.sync.get('cert', function (savedCert) {
if (savedCert.cert !== null) { // we have a saved cert
pairingCert = savedCert.cert;
}
});
chrome.storage.sync.get('uniqueid', function(savedUniqueid) {
if (savedUniqueid.uniqueid != null) { // we have a saved uniqueid
chrome.storage.sync.get('uniqueid', function (savedUniqueid) {
if (savedUniqueid.uniqueid !== null) { // we have a saved uniqueid
myUniqueid = savedUniqueid.uniqueid;
} else {
myUniqueid = uniqueid();
@ -866,10 +895,10 @@ function onWindowLoad(){
});
// load previously connected hosts, which have been killed into an object, and revive them back into a class
chrome.storage.sync.get('hosts', function(previousValue) {
hosts = previousValue.hosts != null ? previousValue.hosts : {};
for(var hostUID in hosts) { // programmatically add each new host.
var revivedHost = new NvHTTP(hosts[hostUID].address, myUniqueid, hosts[hostUID].userEnteredAddress);
chrome.storage.sync.get('hosts', function (previousValue) {
hosts = previousValue.hosts !== null ? previousValue.hosts : {};
for (let hostUID in hosts) { // programmatically add each new host.
let revivedHost = new NvHTTP(hosts[hostUID].address, myUniqueid, hosts[hostUID].userEnteredAddress);
revivedHost.serverUid = hosts[hostUID].serverUid;
revivedHost.externalIP = hosts[hostUID].externalIP;
revivedHost.hostname = hosts[hostUID].hostname;

View File

@ -1,38 +1,30 @@
function guuid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
let r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
function uniqueid() {
return 'xxxxxxxxxxxxxxxx'.replace(/[x]/g, function(c) {
var r = Math.random()*16|0;
return r.toString(16);
});
return 'xxxxxxxxxxxxxxxx'.replace(/[x]/g, function (c) {
let r = Math.random() * 16 | 0;
return r.toString(16);
});
}
function generateRemoteInputKey() {
return 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'.replace(/[x]/g, function(c) {
var r = Math.random()*16|0;
return 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'.replace(/[x]/g, function (c) {
let r = Math.random() * 16 | 0;
return r.toString(16);
});
}
function generateRemoteInputKeyId() {
return ((Math.random()-0.5) * 0x7FFFFFFF)|0;
}
String.prototype.toHex = function() {
var hex = '';
for(var i = 0; i < this.length; i++) {
hex += '' + this.charCodeAt(i).toString(16);
}
return hex;
return ((Math.random() - 0.5) * 0x7FFFFFFF) | 0;
}
function NvHTTP(address, clientUid, userEnteredAddress = '') {
console.log('%c[utils.js, NvHTTP Object]', 'color: gray;', this);
console.log('%c[utils.js, NvHTTP Object]', 'color: gray;', this);
this.address = address;
this.paired = false;
this.currentGame = 0;
@ -55,23 +47,23 @@ function NvHTTP(address, clientUid, userEnteredAddress = '') {
this._pollCompletionCallbacks = [];
_self = this;
};
}
function _arrayBufferToBase64( buffer ) {
var binary = '';
var bytes = new Uint8Array( buffer );
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode( bytes[ i ] );
function _arrayBufferToBase64(buffer) {
let binary = '';
let bytes = new Uint8Array(buffer);
let len = bytes.byteLength;
for (let i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return window.btoa( binary );
return window.btoa(binary);
}
function _base64ToArrayBuffer(base64) {
var binary_string = window.atob(base64);
var len = binary_string.length;
var bytes = new Uint8Array( len );
for (var i = 0; i < len; i++) {
let binary_string = window.atob(base64);
let len = binary_string.length;
let bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) {
bytes[i] = binary_string.charCodeAt(i);
}
return bytes.buffer;
@ -80,10 +72,10 @@ function _base64ToArrayBuffer(base64) {
NvHTTP.prototype = {
refreshServerInfo: function () {
// try HTTPS first
return sendMessage('openUrl', [ this._baseUrlHttps + '/serverinfo?' + this._buildUidStr(), false]).then(function(ret) {
return sendMessage('openUrl', [this._baseUrlHttps + '/serverinfo?' + this._buildUidStr(), false]).then(function (ret) {
if (!this._parseServerInfo(ret)) { // if that fails
// try HTTP as a failover. Useful to clients who aren't paired yet
return sendMessage('openUrl', [ this._baseUrlHttp + '/serverinfo?' + this._buildUidStr(), false]).then(function(retHttp) {
return sendMessage('openUrl', [this._baseUrlHttp + '/serverinfo?' + this._buildUidStr(), false]).then(function (retHttp) {
this._parseServerInfo(retHttp);
}.bind(this));
}
@ -91,13 +83,13 @@ NvHTTP.prototype = {
},
// refreshes the server info using a given address. This is useful for testing whether we can successfully ping a host at a given address
refreshServerInfoAtAddress: function(givenAddress) {
refreshServerInfoAtAddress: function (givenAddress) {
// 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
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
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);
}.bind(this));
}
@ -105,7 +97,7 @@ NvHTTP.prototype = {
},
// called every few seconds to poll the server for updated info
pollServer: function(onComplete) {
pollServer: function (onComplete) {
// Pend this callback on completion
this._pollCompletionCallbacks.push(onComplete);
@ -116,7 +108,7 @@ NvHTTP.prototype = {
return;
}
this.selectServerAddress(function(successfulAddress) {
this.selectServerAddress(function (successfulAddress) {
// Successfully determined server address. Update base URL.
this.address = successfulAddress;
this._baseUrlHttps = 'https://' + successfulAddress + ':47984';
@ -125,7 +117,7 @@ NvHTTP.prototype = {
// Poll for the app list every 10 successful serverinfo polls.
// Not including the first one to avoid PCs taking a while to show
// as online initially
if (this._pollCount++ % 10 == 1) {
if (this._pollCount++ % 10 === 1) {
this.getAppListWithCacheFlush();
}
@ -133,17 +125,17 @@ NvHTTP.prototype = {
this.online = true;
// Call all pending completion callbacks
var completion;
let completion;
while ((completion = this._pollCompletionCallbacks.pop())) {
completion(this);
}
}.bind(this), function() {
}.bind(this), function () {
if (++this._consecutivePollFailures >= 2) {
this.online = false;
}
// Call all pending completion callbacks
var completion;
let completion;
while ((completion = this._pollCompletionCallbacks.pop())) {
completion(this);
}
@ -151,20 +143,20 @@ NvHTTP.prototype = {
},
// initially pings the server to try and figure out if it's routable by any means.
selectServerAddress: function(onSuccess, onFailure) {
selectServerAddress: function (onSuccess, onFailure) {
// TODO: Deduplicate the addresses
this.refreshServerInfoAtAddress(this.address).then(function(successPrevAddr) {
this.refreshServerInfoAtAddress(this.address).then(function (successPrevAddr) {
onSuccess(this.address);
}.bind(this), function(successPrevAddr) {
this.refreshServerInfoAtAddress(this.hostname + '.local').then(function(successLocal) {
}.bind(this), function (successPrevAddr) {
this.refreshServerInfoAtAddress(this.hostname + '.local').then(function (successLocal) {
onSuccess(this.hostname + '.local');
}.bind(this), function(failureLocal) {
this.refreshServerInfoAtAddress(this.externalIP).then(function(successExternal) {
}.bind(this), function (failureLocal) {
this.refreshServerInfoAtAddress(this.externalIP).then(function (successExternal) {
onSuccess(this.externalIP);
}.bind(this), function(failureExternal) {
this.refreshServerInfoAtAddress(this.userEnteredAddress).then(function(successUserEntered) {
}.bind(this), function (failureExternal) {
this.refreshServerInfoAtAddress(this.userEnteredAddress).then(function (successUserEntered) {
onSuccess(this.userEnteredAddress);
}.bind(this), function(failureUserEntered) {
}.bind(this), function (failureUserEntered) {
console.warn('%c[utils.js, utils.js, selectServerAddress]', 'color: gray;', 'Failed to contact host ' + this.hostname, this);
onFailure();
}.bind(this));
@ -173,8 +165,8 @@ NvHTTP.prototype = {
}.bind(this));
},
toString: function() {
var string = '';
toString: function () {
let string = '';
string += 'server address: ' + this.address + '\r\n';
string += 'server UID: ' + this.serverUid + '\r\n';
string += 'is paired: ' + this.paired + '\r\n';
@ -185,32 +177,32 @@ NvHTTP.prototype = {
string += 'gpu type: ' + this.gputype + '\r\n';
string += 'number of apps: ' + this.numofapps + '\r\n';
string += 'supported display modes: ' + '\r\n';
for(var displayMode in this.supportedDisplayModes) {
for (let displayMode in this.supportedDisplayModes) {
string += '\t' + displayMode + ': ' + this.supportedDisplayModes[displayMode] + '\r\n';
}
return string;
},
_prepareForStorage: function() {
_prepareForStorage: function () {
this._memCachedBoxArtArray = {};
},
_parseServerInfo: function(xmlStr) {
_parseServerInfo: function (xmlStr) {
$xml = this._parseXML(xmlStr);
$root = $xml.find('root');
if($root.attr("status_code") != 200) {
if ($root.attr("status_code") !== 200) {
return false;
}
if(this.serverUid != $root.find('uniqueid').text().trim() && this.serverUid != "") {
if (this.serverUid !== $root.find('uniqueid').text().trim() && this.serverUid !== "") {
// if we received a UID that isn't the one we expected, fail.
return false;
}
console.log('%c[utils.js, _parseServerInfo]', 'color:gray;', 'Parsing server info:', $root);
console.log('%c[utils.js, _parseServerInfo]', 'color:gray;', 'Parsing server info:', $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.appVersion = $root.find("appversion").text().trim();
this.serverMajorVersion = parseInt(this.appVersion.substring(0, 1), 10);
@ -222,14 +214,14 @@ NvHTTP.prototype = {
this.gputype = $root.find('gputype').text().trim();
this.numofapps = $root.find('numofapps').text().trim();
// now for the hard part: parsing the supported streaming
$root.find('DisplayMode').each(function(index, value) { // for each resolution:FPS object
var yres = parseInt($(value).find('Height').text());
var xres = parseInt($(value).find('Width').text());
var fps = parseInt($(value).find('RefreshRate').text());
if(!this.supportedDisplayModes[yres + ':' + xres]) {
$root.find('DisplayMode').each(function (index, value) { // for each resolution:FPS object
let yres = parseInt($(value).find('Height').text());
let xres = parseInt($(value).find('Width').text());
let fps = parseInt($(value).find('RefreshRate').text());
if (!this.supportedDisplayModes[yres + ':' + xres]) {
this.supportedDisplayModes[yres + ':' + xres] = [];
}
if(!this.supportedDisplayModes[yres + ':' + xres].includes(fps)) {
if (!this.supportedDisplayModes[yres + ':' + xres].includes(fps)) {
this.supportedDisplayModes[yres + ':' + xres].push(fps);
}
}.bind(this));
@ -250,27 +242,10 @@ NvHTTP.prototype = {
getAppById: function (appId) {
return this.getAppList().then(function (list) {
var retApp = null;
let retApp = null;
list.some(function (app) {
if (app.id == appId) {
retApp = app;
return true;
}
return false;
});
return retApp;
});
},
getAppByName: function (appName) {
return this.getAppList().then(function (list) {
var retApp = null;
list.some(function (app) {
if (app.title == appName) {
if (app.id === appId) {
retApp = app;
return true;
}
@ -287,17 +262,17 @@ NvHTTP.prototype = {
$xml = this._parseXML(ret);
$root = $xml.find("root");
if ($root.attr("status_code") != 200) {
if ($root.attr("status_code") !== 200) {
// TODO: Bubble up an error here
console.error('%c[utils.js, utils.js, getAppListWithCacheFlush]', 'color: gray;', '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 [];
}
var rootElement = $xml.find("root")[0];
var appElements = rootElement.getElementsByTagName("App");
var appList = [];
let rootElement = $xml.find("root")[0];
let appElements = rootElement.getElementsByTagName("App");
let appList = [];
for (var i = 0, len = appElements.length; i < len; i++) {
for (let i = 0, len = appElements.length; i < len; i++) {
appList.push({
title: appElements[i].getElementsByTagName("AppTitle")[0].innerHTML.trim(),
id: parseInt(appElements[i].getElementsByTagName("ID")[0].innerHTML.trim(), 10)
@ -315,7 +290,6 @@ NvHTTP.prototype = {
return new Promise(function (resolve, reject) {
console.log('%c[utils.js, utils.js]', 'color: gray;', 'Returning memory-cached apps list');
resolve(this._memCachedApplist);
return;
}.bind(this));
}
@ -326,26 +300,25 @@ NvHTTP.prototype = {
// this is inefficient, but works well.
warmBoxArtCache: function () {
if (!this.paired) {
console.log('%c[utils.js, warmBoxArtCache]', 'color: grey;', 'Not warming box art cache for unpaired host');
return;
console.log('%c[utils.js, warmBoxArtCache]', 'color: grey;', 'Not warming box art cache for unpaired host');
return;
}
if (Object.keys(this._memCachedBoxArtArray).length != 0) {
console.log('%c[utils.js, warmBoxArtCache]', 'color: grey;', 'Box art cache already warmed');
return;
if (Object.keys(this._memCachedBoxArtArray).length !== 0) {
console.log('%c[utils.js, warmBoxArtCache]', 'color: grey;', 'Box art cache already warmed');
return;
}
if (chrome.storage) {
chrome.storage.local.get('boxArtCache', function(JSONCachedBoxArtArray) {
chrome.storage.local.get('boxArtCache', function (JSONCachedBoxArtArray) {
var storedBoxArtArray; // load cached data if it exists
if (JSONCachedBoxArtArray.boxArtCache != undefined) {
let storedBoxArtArray; // load cached data if it exists
if (JSONCachedBoxArtArray.boxArtCache !== undefined) {
storedBoxArtArray = JSONCachedBoxArtArray.boxArtCache;
for (var key in storedBoxArtArray) {
for (let key in storedBoxArtArray) {
this._memCachedBoxArtArray[key] = _base64ToArrayBuffer(storedBoxArtArray[key]);
}
console.log('%c[utils.js, warmBoxArtCache]', 'color: grey;', 'Box art cache warmed');
console.log('%c[utils.js, warmBoxArtCache]', 'color: grey;', 'Box art cache warmed');
} else {
console.warn('%c[utils.js, warmBoxArtCache]', 'color: grey;', 'No box art found in storage. Cannot warm cache!');
return;
console.warn('%c[utils.js, warmBoxArtCache]', 'color: grey;', 'No box art found in storage. Cannot warm cache!');
}
}.bind(this));
}
@ -360,15 +333,13 @@ NvHTTP.prototype = {
if (this._memCachedBoxArtArray[appId] === null) {
// This means a previous box art request failed, don't try again
return new Promise(function (resolve, reject) {
console.error('%c[utils.js, utils.js, getBoxArt]', 'color: gray;', 'Returning cached box-art failure result')
reject(null);
return;
console.error('%c[utils.js, utils.js, getBoxArt]', 'color: gray;', 'Returning cached box-art failure result');
reject(null);
}.bind(this));
} else if (this._memCachedBoxArtArray[appId] !== undefined) {
return new Promise(function (resolve, reject) {
console.log('%c[utils.js, utils.js, getBoxArt]', 'color: gray;', 'Returning memory-cached box-art');
resolve(this._memCachedBoxArtArray[appId]);
return;
}.bind(this));
}
@ -376,17 +347,17 @@ NvHTTP.prototype = {
// This may be bad practice to push/pull this much data through local storage?
return new Promise(function (resolve, reject) {
chrome.storage.local.get('boxArtCache', function(JSONCachedBoxArtArray) {
chrome.storage.local.get('boxArtCache', function (JSONCachedBoxArtArray) {
var storedBoxArtArray; // load cached data if it exists
if (JSONCachedBoxArtArray.boxArtCache != undefined && JSONCachedBoxArtArray.boxArtCache[appId] != undefined) {
let storedBoxArtArray; // load cached data if it exists
if (JSONCachedBoxArtArray.boxArtCache !== undefined && JSONCachedBoxArtArray.boxArtCache[appId] !== undefined) {
storedBoxArtArray = JSONCachedBoxArtArray.boxArtCache;
storedBoxArtArray[appId] = _base64ToArrayBuffer(storedBoxArtArray[appId]);
this._memCachedBoxArtArray[appId] = storedBoxArtArray[appId];
} else {
storedBoxArtArray = {};
storedBoxArtArray = {};
}
// if we already have it, load it.
@ -399,40 +370,39 @@ NvHTTP.prototype = {
// otherwise, put it in our cache, then return it
sendMessage('openUrl', [
this._baseUrlHttps +
'/appasset?'+this._buildUidStr() +
'/appasset?' + this._buildUidStr() +
'&appid=' + appId +
'&AssetType=2&AssetIdx=0',
true
]).then(function(streamedBoxArt) {
]).then(function (streamedBoxArt) {
// the memcached data is global to all the async calls we're doing. This way there's only one array that holds everything properly.
this._memCachedBoxArtArray[appId] = streamedBoxArt;
var obj = {};
var arrayToStore = {}
let obj = {};
let arrayToStore = {};
for (key in this._memCachedBoxArtArray) { // convert the arraybuffer into a string
arrayToStore[key] = _arrayBufferToBase64(this._memCachedBoxArtArray[key]);
}
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('%c[utils.js, utils.js, getBoxArt]', 'color: gray;', 'Returning streamed box art');
resolve(streamedBoxArt);
return;
}.bind(this), function(error) {
}.bind(this), function (error) {
// Cache the failure but not persistently
this._memCachedBoxArtArray[appId] = null;
console.error('%c[utils.js, utils.js, getBoxArt]', 'color: gray;', 'Box-art request failed!', error);
reject(error);
return;
}.bind(this));
}.bind(this));
}.bind(this));
} else { // shouldn't run because we always have chrome.storage, but I'm not going to antagonize other browsers
console.warn('%c[utils.js, utils.js, getBoxArt]', 'color: gray;', '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', [
this._baseUrlHttps +
'/appasset?'+this._buildUidStr() +
'/appasset?' + this._buildUidStr() +
'&appid=' + appId +
'&AssetType=2&AssetIdx=0',
true
@ -471,24 +441,24 @@ NvHTTP.prototype = {
quitApp: function () {
return sendMessage('openUrl', [this._baseUrlHttps + '/cancel?' + this._buildUidStr(), false])
// Refresh server info after quitting because it may silently fail if the
// session belongs to a different client.
// TODO: We should probably bubble this up to our caller.
// Refresh server info after quitting because it may silently fail if the
// session belongs to a different client.
// TODO: We should probably bubble this up to our caller.
.then(this.refreshServerInfo());
},
pair: function(randomNumber) {
pair: function (randomNumber) {
return this.refreshServerInfo().then(function () {
if (this.paired)
return true;
if (this.currentGame != 0)
if (this.currentGame !== 0)
return false;
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) {
$xml = this._parseXML(ret);
this.paired = $xml.find('paired').html() == "1";
this.paired = $xml.find('paired').html() === "1";
return this.paired;
}.bind(this));
}.bind(this));