Fixed indentation usign atom-beautify

This commit is contained in:
Jorys_Paulin 2018-04-24 08:40:39 +02:00
parent 49bdfcc33d
commit 28a76fa965
5 changed files with 1205 additions and 1150 deletions

View File

@ -10,7 +10,9 @@ function createWindow(state) {
// state = 'normal' in some cases not work (e.g. starting app from 'chrome://extensions' always open window in fullscreen mode) // state = 'normal' in some cases not work (e.g. starting app from 'chrome://extensions' always open window in fullscreen mode)
// it requires manually restoring window state to 'normal' // it requires manually restoring window state to 'normal'
if (state == 'normal') { if (state == 'normal') {
setTimeout(function() { window.restore(); }, 1000); setTimeout(function() {
window.restore();
}, 1000);
} }
}); });
} }
@ -22,9 +24,9 @@ chrome.app.runtime.onLaunched.addListener(function() {
if (chrome.storage) { if (chrome.storage) {
// load stored window state // load stored window state
chrome.storage.sync.get('windowState', function(item) { chrome.storage.sync.get('windowState', function(item) {
windowState = (item && item.windowState) windowState = (item && item.windowState) ?
? item.windowState item.windowState :
: windowState; windowState;
createWindow(windowState); createWindow(windowState);
}); });
} else { } else {

View File

@ -35,13 +35,15 @@ function fullscreenChromeWindow() {
} }
function loadWindowState() { 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 // load stored window state
windowState = (item && item.windowState) windowState = (item && item.windowState) ?
? item.windowState item.windowState :
: windowState; windowState;
// subscribe to chrome's windowState events // subscribe to chrome's windowState events
chrome.app.window.current().onFullscreened.addListener(onFullscreened); chrome.app.window.current().onFullscreened.addListener(onFullscreened);
@ -71,13 +73,13 @@ function changeUiModeForNaClLoad() {
} }
function startPollingHosts() { function startPollingHosts() {
for(var hostUID in hosts) { for (var hostUID in hosts) {
beginBackgroundPollingOfHost(hosts[hostUID]); beginBackgroundPollingOfHost(hosts[hostUID]);
} }
} }
function stopPollingHosts() { function stopPollingHosts() {
for(var hostUID in hosts) { for (var hostUID in hosts) {
stopBackgroundPollingOfHost(hosts[hostUID]); stopBackgroundPollingOfHost(hosts[hostUID]);
} }
} }
@ -89,7 +91,7 @@ function restoreUiAfterNaClLoad() {
$('#loadingSpinner').css('display', 'none'); $('#loadingSpinner').css('display', 'none');
showHostsAndSettingsMode(); showHostsAndSettingsMode();
findNvService(function (finder, opt_error) { findNvService(function(finder, opt_error) {
if (finder.byService_['_nvstream._tcp']) { if (finder.byService_['_nvstream._tcp']) {
var ips = Object.keys(finder.byService_['_nvstream._tcp']); var ips = Object.keys(finder.byService_['_nvstream._tcp']);
for (var i in ips) { for (var i in ips) {
@ -122,7 +124,7 @@ function beginBackgroundPollingOfHost(host) {
// The host was already online. Just start polling in the background now. // 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 // every 5 seconds, poll at the address we know it was live at
host.pollServer(function () { host.pollServer(function() {
if (host.online) { if (host.online) {
$("#hostgrid-" + host.serverUid).removeClass('host-cell-inactive'); $("#hostgrid-" + host.serverUid).removeClass('host-cell-inactive');
} else { } else {
@ -133,7 +135,7 @@ function beginBackgroundPollingOfHost(host) {
} else { } else {
$("#hostgrid-" + host.serverUid).addClass('host-cell-inactive'); $("#hostgrid-" + host.serverUid).addClass('host-cell-inactive');
// The host was offline, so poll immediately. // The host was offline, so poll immediately.
host.pollServer(function () { host.pollServer(function() {
if (host.online) { if (host.online) {
$("#hostgrid-" + host.serverUid).removeClass('host-cell-inactive'); $("#hostgrid-" + host.serverUid).removeClass('host-cell-inactive');
} else { } else {
@ -143,7 +145,7 @@ function beginBackgroundPollingOfHost(host) {
// Now start background polling // 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 // every 5 seconds, poll at the address we know it was live at
host.pollServer(function () { host.pollServer(function() {
if (host.online) { if (host.online) {
$("#hostgrid-" + host.serverUid).removeClass('host-cell-inactive'); $("#hostgrid-" + host.serverUid).removeClass('host-cell-inactive');
} else { } else {
@ -201,24 +203,23 @@ function moduleDidLoad() {
if (!pairingCert) { // we couldn't load a cert. Make 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'); 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.info('%c[index.js, moduleDidLoad]', 'color: green;', 'Generated new cert:', cert); console.info('%c[index.js, moduleDidLoad]', 'color: green;', 'Generated new cert:', cert);
}, function (failedCert) { }, function(failedCert) {
console.error('%c[index.js, moduleDidLoad]', 'color: green;', 'Failed to generate new cert! Returned error was: \n', failedCert); console.error('%c[index.js, moduleDidLoad]', 'color: green;', 'Failed to generate new cert! Returned error was: \n', 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.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);
}); });
}); });
} } else {
else { 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.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);
}); });
} }
@ -226,7 +227,7 @@ function moduleDidLoad() {
// load previously connected hosts, which have been killed into an object, and revive them back into a class // 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) { chrome.storage.sync.get('hosts', function(previousValue) {
hosts = previousValue.hosts != null ? previousValue.hosts : {}; hosts = previousValue.hosts != null ? previousValue.hosts : {};
for(var hostUID in hosts) { // programmatically add each new host. for (var hostUID in hosts) { // programmatically add each new host.
var revivedHost = new NvHTTP(hosts[hostUID].address, myUniqueid, hosts[hostUID].userEnteredAddress); var revivedHost = new NvHTTP(hosts[hostUID].address, myUniqueid, hosts[hostUID].userEnteredAddress);
revivedHost.serverUid = hosts[hostUID].serverUid; revivedHost.serverUid = hosts[hostUID].serverUid;
revivedHost.externalIP = hosts[hostUID].externalIP; revivedHost.externalIP = hosts[hostUID].externalIP;
@ -241,14 +242,14 @@ function moduleDidLoad() {
// pair to the given NvHTTP host object. Returns whether pairing was successful. // pair to the given NvHTTP host object. Returns whether pairing was successful.
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.warn('%c[index.js]', 'color: green;', '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;
} }
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.error('%c[index.js]', 'color: green;', 'Host declared as offline:', nvhttpHost, nvhttpHost.toString()); //Logging both the object and the toString version for text logs 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
@ -261,18 +262,18 @@ function pairTo(nvhttpHost, onSuccess, onFailure) {
return; return;
} }
var randomNumber = String("0000" + (Math.random()*10000|0)).slice(-4); var randomNumber = String("0000" + (Math.random() * 10000 | 0)).slice(-4);
var pairingDialog = document.querySelector('#pairingDialog'); var 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'); $('#pairingDialogText').html('Please enter the number ' + randomNumber + ' on the GFE dialog on the computer. This dialog will be dismissed once complete');
pairingDialog.showModal(); pairingDialog.showModal();
$('#cancelPairingDialog').off('click'); $('#cancelPairingDialog').off('click');
$('#cancelPairingDialog').on('click', function () { $('#cancelPairingDialog').on('click', function() {
pairingDialog.close(); pairingDialog.close();
}); });
console.log('%c[index.js]', 'color: green;', '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) {
$('#pairingDialogText').html('Error: ' + nvhttpHost.hostname + ' is busy. Stop streaming to pair.'); $('#pairingDialogText').html('Error: ' + nvhttpHost.hostname + ' is busy. Stop streaming to pair.');
@ -287,7 +288,7 @@ function pairTo(nvhttpHost, onSuccess, onFailure) {
snackbarLog('Pairing successful'); snackbarLog('Pairing successful');
pairingDialog.close(); pairingDialog.close();
onSuccess(); onSuccess();
}, function (failedPairing) { }, function(failedPairing) {
snackbarLog('Failed pairing to: ' + nvhttpHost.hostname); snackbarLog('Failed pairing to: ' + nvhttpHost.hostname);
console.error('%c[index.js]', 'color: green;', 'Pairing failed, and returned:', failedPairing); console.error('%c[index.js]', 'color: green;', 'Pairing failed, and returned:', failedPairing);
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.error('%c[index.js]', 'color: green;', 'Failed API object:', nvhttpHost, nvhttpHost.toString()); //Logging both the object and the toString version for text logs
@ -312,7 +313,7 @@ function hostChosen(host) {
showApps(host); showApps(host);
saveHosts(); saveHosts();
}, },
function(){ function() {
startPollingHosts(); startPollingHosts();
}); });
} else { } else {
@ -335,7 +336,7 @@ function addHost() {
// try to pair if they continue // try to pair if they continue
$('#continueAddHost').off('click'); $('#continueAddHost').off('click');
$('#continueAddHost').on('click', function () { $('#continueAddHost').on('click', function() {
var inputHost = $('#dialogInputHost').val(); var inputHost = $('#dialogInputHost').val();
var _nvhttpHost = new NvHTTP(inputHost, myUniqueid, inputHost); var _nvhttpHost = new NvHTTP(inputHost, myUniqueid, inputHost);
@ -345,8 +346,7 @@ function addHost() {
// Just update the addresses // Just update the addresses
hosts[_nvhttpHost.serverUid].address = _nvhttpHost.address; hosts[_nvhttpHost.serverUid].address = _nvhttpHost.address;
hosts[_nvhttpHost.serverUid].userEnteredAddress = _nvhttpHost.userEnteredAddress; hosts[_nvhttpHost.serverUid].userEnteredAddress = _nvhttpHost.userEnteredAddress;
} } else {
else {
beginBackgroundPollingOfHost(_nvhttpHost); beginBackgroundPollingOfHost(_nvhttpHost);
addHostToGrid(_nvhttpHost); addHostToGrid(_nvhttpHost);
} }
@ -362,20 +362,38 @@ function addHost() {
// host is an NvHTTP object // host is an NvHTTP object
function addHostToGrid(host, ismDNSDiscovered) { 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 outerDiv = $("<div>", {
var cell = $("<div>", {class: 'mdl-card__title mdl-card--expand', id: 'hostgrid-' + host.serverUid }); class: 'host-container mdl-card mdl-shadow--4dp',
$(cell).prepend($("<h2>", {class: "mdl-card__title-text", html: host.hostname})); id: 'host-container-' + host.serverUid,
var removalButton = $("<div>", {class: "remove-host", id: "removeHostButton-" + host.serverUid, role: 'button', tabindex: 0, 'aria-label': 'Remove host ' + host.hostname}); role: 'link',
tabindex: 0,
'aria-label': host.hostname
});
var 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
});
removalButton.off('click'); removalButton.off('click');
removalButton.click(function () { removalButton.click(function() {
removeClicked(host); removeClicked(host);
}); });
cell.off('click'); cell.off('click');
cell.click(function () { cell.click(function() {
hostChosen(host); hostChosen(host);
}); });
outerDiv.keypress(function(e){ outerDiv.keypress(function(e) {
if(e.keyCode == 13) { if (e.keyCode == 13) {
hostChosen(host); hostChosen(host);
} }
}); });
@ -395,7 +413,7 @@ function removeClicked(host) {
deleteHostDialog.showModal(); deleteHostDialog.showModal();
$('#cancelDeleteHost').off('click'); $('#cancelDeleteHost').off('click');
$('#cancelDeleteHost').on('click', function () { $('#cancelDeleteHost').on('click', function() {
deleteHostDialog.close(); deleteHostDialog.close();
}); });
@ -403,7 +421,7 @@ function removeClicked(host) {
// note: this does not make the host forget the pairing to us. // note: this does not make the host forget the pairing to us.
// this means we can re-add the host, and will still be paired. // this means we can re-add the host, and will still be paired.
$('#continueDeleteHost').off('click'); $('#continueDeleteHost').off('click');
$('#continueDeleteHost').on('click', function () { $('#continueDeleteHost').on('click', function() {
var deleteHostDialog = document.querySelector('#deleteHostDialog'); var deleteHostDialog = document.querySelector('#deleteHostDialog');
$('#host-container-' + host.serverUid).remove(); $('#host-container-' + host.serverUid).remove();
delete hosts[host.serverUid]; // remove the host from the array; delete hosts[host.serverUid]; // remove the host from the array;
@ -418,16 +436,16 @@ function removeClicked(host) {
// the function was made like this so that we can remove duplicated code, but // 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 // not do N*N stylizations of the box art, or make the code not flow very well
function stylizeBoxArt(freshApi, appIdToStylize) { function stylizeBoxArt(freshApi, appIdToStylize) {
if (freshApi.currentGame === appIdToStylize){ // stylize the currently running game if (freshApi.currentGame === appIdToStylize) { // stylize the currently running game
// destylize it, if it has the not-current-game style // destylize it, if it has the not-current-game style
if ($('#game-'+ appIdToStylize).hasClass("not-current-game")) $('#game-'+ appIdToStylize).removeClass("not-current-game"); if ($('#game-' + appIdToStylize).hasClass("not-current-game")) $('#game-' + appIdToStylize).removeClass("not-current-game");
// add the current-game style // add the current-game style
$('#game-'+ appIdToStylize).addClass("current-game"); $('#game-' + appIdToStylize).addClass("current-game");
} else { } else {
// destylize it, if it has the current-game style // destylize it, if it has the current-game style
if ($('#game-'+ appIdToStylize).hasClass("current-game")) $('#game-'+ appIdToStylize).removeClass("current-game"); if ($('#game-' + appIdToStylize).hasClass("current-game")) $('#game-' + appIdToStylize).removeClass("current-game");
// add the not-current-game style // add the not-current-game style
$('#game-'+ appIdToStylize).addClass('not-current-game'); $('#game-' + appIdToStylize).addClass('not-current-game');
} }
} }
@ -438,22 +456,31 @@ function sortTitles(list, sortOrder) {
// A - Z // A - Z
if (sortOrder === 'ASC') { if (sortOrder === 'ASC') {
if (titleA < titleB) { return -1; } if (titleA < titleB) {
if (titleA > titleB) { return 1; } return -1;
}
if (titleA > titleB) {
return 1;
}
return 0; return 0;
} }
// Z - A // Z - A
if (sortOrder === 'DESC') { if (sortOrder === 'DESC') {
if (titleA < titleB) { return 1; } if (titleA < titleB) {
if (titleA > titleB) { return -1; } return 1;
return 0; } }
if (titleA > titleB) {
return -1;
}
return 0;
}
}); });
} }
// 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('%c[index.js, showApps]', 'color: green;', '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;
} }
@ -465,7 +492,7 @@ function showApps(host) {
$('#naclSpinnerMessage').text('Loading apps...'); $('#naclSpinnerMessage').text('Loading apps...');
$('#naclSpinner').css('display', 'inline-block'); $('#naclSpinner').css('display', 'inline-block');
host.getAppList().then(function (appList) { host.getAppList().then(function(appList) {
// if game grid is populated, empty it // if game grid is populated, empty it
$("div.game-container").remove(); $("div.game-container").remove();
@ -474,21 +501,33 @@ function showApps(host) {
const sortedAppList = sortTitles(appList, 'ASC'); const sortedAppList = sortTitles(appList, 'ASC');
sortedAppList.forEach(function (app) { sortedAppList.forEach(function(app) {
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.
// to mitigate this we ensure we don't add a duplicate. // 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 // 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, role: 'link', tabindex: 0, title: app.title, 'aria-label': app.title }); var outerDiv = $("<div>", {
class: 'game-container mdl-card mdl-shadow--4dp',
id: 'game-' + app.id,
role: 'link',
tabindex: 0,
title: app.title,
'aria-label': app.title
});
$(outerDiv).append($("<div>", {class: "game-title", html: $("<span>", {html: app.title} )})); $(outerDiv).append($("<div>", {
class: "game-title",
html: $("<span>", {
html: app.title
})
}));
$("#game-grid").append(outerDiv); $("#game-grid").append(outerDiv);
$('#game-'+app.id).on('click', function () { $('#game-' + app.id).on('click', function() {
startGame(host, app.id); startGame(host, app.id);
}); });
$('#game-'+app.id).keypress(function(e){ $('#game-' + app.id).keypress(function(e) {
if(e.keyCode == 13) { if (e.keyCode == 13) {
startGame(host, app.id); startGame(host, app.id);
} }
}); });
@ -496,16 +535,22 @@ function showApps(host) {
// apply CSS stylization to indicate whether the app is active // apply CSS stylization to indicate whether the app is active
stylizeBoxArt(host, app.id); stylizeBoxArt(host, app.id);
} }
host.getBoxArt(app.id).then(function (resolvedPromise) { host.getBoxArt(app.id).then(function(resolvedPromise) {
// put the box art into the image holder // put the box art into the image holder
$(outerDiv).append($("<img \>", {src: resolvedPromise, name: app.title })); $(outerDiv).append($("<img \>", {
src: resolvedPromise,
name: app.title
}));
}, function (failedPromise) { }, 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());
$(outerDiv).append($("<img \>", {src: "static/res/no_app_image.png", name: app.title })); $(outerDiv).append($("<img \>", {
src: "static/res/no_app_image.png",
name: app.title
}));
}); });
}); });
}, function (failedAppList) { }, function(failedAppList) {
$('#naclSpinner').hide(); $('#naclSpinner').hide();
console.log('%c[index.js, showApps]', 'color: green;', 'Failed to get applist from host: ' + host.hostname, '\n Host object:', host, host.toString()); console.log('%c[index.js, showApps]', 'color: green;', 'Failed to get applist from host: ' + host.hostname, '\n Host object:', host, host.toString());
@ -553,31 +598,31 @@ function showAppsMode() {
// start the given appID. if another app is running, offer to quit it. // start the given appID. if another app is running, offer to quit it.
// 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.error('%c[index.js, startGame]', 'color: green;', 'Attempted to start a game, but `host` did not initialize properly. Host object: ', host); 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.
host.refreshServerInfo().then(function (ret) { host.refreshServerInfo().then(function(ret) {
host.getAppById(appID).then(function (appToStart) { 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) { host.getAppById(host.currentGame).then(function(currentApp) {
var quitAppDialog = document.querySelector('#quitAppDialog'); var quitAppDialog = document.querySelector('#quitAppDialog');
document.getElementById('quitAppDialogText').innerHTML = document.getElementById('quitAppDialogText').innerHTML =
currentApp.title + ' is already running. Would you like to quit ' + currentApp.title + ' is already running. Would you like to quit ' +
currentApp.title + '?'; currentApp.title + '?';
quitAppDialog.showModal(); quitAppDialog.showModal();
$('#cancelQuitApp').off('click'); $('#cancelQuitApp').off('click');
$('#cancelQuitApp').on('click', function () { $('#cancelQuitApp').on('click', function() {
quitAppDialog.close(); 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').off('click');
$('#continueQuitApp').on('click', function () { $('#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 () { 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);
}); });
@ -585,8 +630,8 @@ function startGame(host, appID) {
}); });
return; return;
}, function (failedCurrentApp) { }, 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()); 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; return;
}); });
return; return;
@ -598,7 +643,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('%c[index.js, startGame]','color:green;', 'startRequest:' + host.address + ":" + streamWidth + ":" + streamHeight + ":" + frameRate + ":" + bitrate + ":" + optimize); console.log('%c[index.js, startGame]', 'color:green;', 'startRequest:' + host.address + ":" + streamWidth + ":" + streamHeight + ":" + frameRate + ":" + bitrate + ":" + optimize);
var rikey = generateRemoteInputKey(); var rikey = generateRemoteInputKey();
var rikeyid = generateRemoteInputKeyId(); var rikeyid = generateRemoteInputKeyId();
@ -607,13 +652,14 @@ function startGame(host, appID) {
$('#loadingMessage').text('Starting ' + appToStart.title + '...'); $('#loadingMessage').text('Starting ' + appToStart.title + '...');
playGameMode(); 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( return host.resumeApp(
rikey, rikeyid, 0x030002 // Surround channel mask << 16 | Surround channel count rikey, rikeyid, 0x030002 // Surround channel mask << 16 | Surround channel count
).then(function (ret) { ).then(function(ret) {
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.eror('%c[index.js, startGame]', 'color:green;', 'Failed to resume the app! Returned error was' + failedResumeApp); console.eror('%c[index.js, startGame]', 'color:green;', 'Failed to resume the app! Returned error was' + failedResumeApp);
return; return;
}); });
@ -628,11 +674,12 @@ function startGame(host, appID) {
remote_audio_enabled, // Play audio locally too? remote_audio_enabled, // Play audio locally too?
0x030002, // Surround channel mask << 16 | Surround channel count 0x030002, // Surround channel mask << 16 | Surround channel count
gamepadMask gamepadMask
).then(function (ret) { ).then(function(ret) {
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) { ]);
console.error('%c[index.js, launchApp]','color: green;','Failed to launch app width id: ' + appID + '\nReturned error was: ' + failedLaunchApp); }, function(failedLaunchApp) {
console.error('%c[index.js, launchApp]', 'color: green;', 'Failed to launch app width id: ' + appID + '\nReturned error was: ' + failedLaunchApp);
return; return;
}); });
@ -676,19 +723,19 @@ function stopGameWithConfirmation() {
if (api.currentGame === 0) { if (api.currentGame === 0) {
snackbarLog('Nothing was running'); snackbarLog('Nothing was running');
} else { } else {
api.getAppById(api.currentGame).then(function (currentGame) { api.getAppById(api.currentGame).then(function(currentGame) {
var quitAppDialog = document.querySelector('#quitAppDialog'); var quitAppDialog = document.querySelector('#quitAppDialog');
document.getElementById('quitAppDialogText').innerHTML = document.getElementById('quitAppDialogText').innerHTML =
' Are you sure you would like to quit ' + ' Are you sure you would like to quit ' +
currentGame.title + '? Unsaved progress will be lost.'; currentGame.title + '? Unsaved progress will be lost.';
quitAppDialog.showModal(); quitAppDialog.showModal();
$('#cancelQuitApp').off('click'); $('#cancelQuitApp').off('click');
$('#cancelQuitApp').on('click', function () { $('#cancelQuitApp').on('click', function() {
console.log('%c[index.js, stopGameWithConfirmation]', 'color:green;', '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('%c[index.js, stopGameWithConfirmation]', 'color:green;', '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();
@ -705,29 +752,29 @@ function stopGame(host, callbackFunction) {
return; return;
} }
host.refreshServerInfo().then(function (ret) { host.refreshServerInfo().then(function(ret) {
host.getAppById(host.currentGame).then(function (runningApp) { host.getAppById(host.currentGame).then(function(runningApp) {
if (!runningApp) { if (!runningApp) {
snackbarLog('Nothing was running'); snackbarLog('Nothing was running');
return; return;
} }
var appName = runningApp.title; var appName = runningApp.title;
snackbarLog('Stopping ' + appName); snackbarLog('Stopping ' + appName);
host.quitApp().then(function (ret2) { host.quitApp().then(function(ret2) {
host.refreshServerInfo().then(function (ret3) { // refresh to show no app is currently running. host.refreshServerInfo().then(function(ret3) { // refresh to show no app is currently running.
showAppsMode(); showAppsMode();
stylizeBoxArt(host, runningApp.id); stylizeBoxArt(host, runningApp.id);
if (typeof(callbackFunction) === "function") callbackFunction(); if (typeof(callbackFunction) === "function") callbackFunction();
}, function (failedRefreshInfo2) { }, function(failedRefreshInfo2) {
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.error('%c[index.js, stopGame]', 'color:green;', 'Failed to refresh server info! Returned error was:' + failedRefreshInfo + ' and failed server was:', host, host.toString());
}); });
}, function (failedQuitApp) { }, function(failedQuitApp) {
console.error('%c[index.js, stopGame]', 'color:green;', 'Failed to quit app! Returned error was:' + failedQuitApp); console.error('%c[index.js, stopGame]', 'color:green;', 'Failed to quit app! Returned error was:' + failedQuitApp);
}); });
}, function (failedGetApp) { }, 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) { }, function(failedRefreshInfo) {
console.error('%c[index.js, stopGame]', 'color:green;', 'Failed to refresh server info! Returned error was:' + failedRefreshInfo); console.error('%c[index.js, stopGame]', 'color:green;', 'Failed to refresh server info! Returned error was:' + failedRefreshInfo);
}); });
} }
@ -735,7 +782,7 @@ function stopGame(host, callbackFunction) {
function storeData(key, data, callbackFunction) { function storeData(key, data, callbackFunction) {
var obj = {}; var obj = {};
obj[key] = data; obj[key] = data;
if(chrome.storage) if (chrome.storage)
chrome.storage.sync.set(obj, callbackFunction); chrome.storage.sync.set(obj, callbackFunction);
} }
@ -790,7 +837,7 @@ function updateDefaultBitrate() {
var res = $('#selectResolution').data('value'); var res = $('#selectResolution').data('value');
var frameRate = $('#selectFramerate').data('value').toString(); var frameRate = $('#selectFramerate').data('value').toString();
if (res ==="1920:1080") { if (res === "1920:1080") {
if (frameRate === "30") { // 1080p, 30fps if (frameRate === "30") { // 1080p, 30fps
$('#bitrateSlider')[0].MaterialSlider.change('10'); $('#bitrateSlider')[0].MaterialSlider.change('10');
} else { // 1080p, 60fps } else { // 1080p, 60fps
@ -816,18 +863,18 @@ function updateDefaultBitrate() {
saveBitrate(); saveBitrate();
} }
function onWindowLoad(){ function onWindowLoad() {
console.log('%c[index.js]', 'color: green;', 'Moonlight\'s main 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');
loadWindowState(); loadWindowState();
if(chrome.storage) { if (chrome.storage) {
// load stored resolution prefs // load stored resolution prefs
chrome.storage.sync.get('resolution', function(previousValue) { chrome.storage.sync.get('resolution', function(previousValue) {
if(previousValue.resolution != null) { if (previousValue.resolution != null) {
$('.resolutionMenu li').each(function () { $('.resolutionMenu li').each(function() {
if ($(this).data('value') === previousValue.resolution) { if ($(this).data('value') === previousValue.resolution) {
$('#selectResolution').text($(this).text()).data('value', previousValue.resolution); $('#selectResolution').text($(this).text()).data('value', previousValue.resolution);
} }
@ -837,7 +884,7 @@ function onWindowLoad(){
// Load stored remote audio prefs // Load stored remote audio prefs
chrome.storage.sync.get('remoteAudio', function(previousValue) { chrome.storage.sync.get('remoteAudio', function(previousValue) {
if(previousValue.remoteAudio == null) { if (previousValue.remoteAudio == null) {
document.querySelector('#externalAudioBtn').MaterialIconToggle.uncheck(); document.querySelector('#externalAudioBtn').MaterialIconToggle.uncheck();
} else if (previousValue.remoteAudio == false) { } else if (previousValue.remoteAudio == false) {
document.querySelector('#externalAudioBtn').MaterialIconToggle.uncheck(); document.querySelector('#externalAudioBtn').MaterialIconToggle.uncheck();
@ -848,8 +895,8 @@ function onWindowLoad(){
// load stored framerate prefs // load stored framerate prefs
chrome.storage.sync.get('frameRate', function(previousValue) { chrome.storage.sync.get('frameRate', function(previousValue) {
if(previousValue.frameRate != null) { if (previousValue.frameRate != null) {
$('.framerateMenu li').each(function () { $('.framerateMenu li').each(function() {
if ($(this).data('value') === previousValue.frameRate) { if ($(this).data('value') === previousValue.frameRate) {
$('#selectFramerate').text($(this).text()).data('value', previousValue.frameRate); $('#selectFramerate').text($(this).text()).data('value', previousValue.frameRate);
} }

View File

@ -11,7 +11,10 @@ var callbacks_ids = 1;
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,
@ -33,16 +36,16 @@ function handleMessage(msg) {
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('%c[messages.js, handleMessage]', 'color:gray;', 'Message data: ', 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');
// Release our keep awake request // Release our keep awake request
chrome.power.releaseKeepAwake(); chrome.power.releaseKeepAwake();
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
api.getAppList().then(function (appList) { api.getAppList().then(function(appList) {
appList.forEach(function (app) { appList.forEach(function(app) {
stylizeBoxArt(api, app.id); // and reapply stylization to indicate what's currently running stylizeBoxArt(api, app.id); // and reapply stylization to indicate what's currently running
}); });
}); });
@ -54,20 +57,20 @@ function handleMessage(msg) {
(windowState == 'normal') && chrome.app.window.current().restore(); (windowState == 'normal') && chrome.app.window.current().restore();
}); });
} else if(msg.data === 'Connection Established') { } else if (msg.data === 'Connection Established') {
$('#loadingSpinner').css('display', 'none'); $('#loadingSpinner').css('display', 'none');
$('body').css('backgroundColor', 'black'); $('body').css('backgroundColor', 'black');
// Keep the display awake while streaming // Keep the display awake while streaming
chrome.power.requestKeepAwake("display"); chrome.power.requestKeepAwake("display");
} else if(msg.data.indexOf('ProgressMsg: ') === 0) { } else if (msg.data.indexOf('ProgressMsg: ') === 0) {
$('#loadingMessage').text(msg.data.replace('ProgressMsg: ', '')); $('#loadingMessage').text(msg.data.replace('ProgressMsg: ', ''));
} else if(msg.data.indexOf('TransientMsg: ') === 0) { } else if (msg.data.indexOf('TransientMsg: ') === 0) {
snackbarLog(msg.data.replace('TransientMsg: ', '')); snackbarLog(msg.data.replace('TransientMsg: ', ''));
} else if(msg.data.indexOf('DialogMsg: ') === 0) { } else if (msg.data.indexOf('DialogMsg: ') === 0) {
// FIXME: Really use a dialog // FIXME: Really use a dialog
snackbarLogLong(msg.data.replace('DialogMsg: ', '')); snackbarLogLong(msg.data.replace('DialogMsg: ', ''));
} else if(msg.data === 'displayVideo') { } else if (msg.data === 'displayVideo') {
$("#listener").addClass("fullscreen"); $("#listener").addClass("fullscreen");
} }
} }

View File

@ -1,26 +1,27 @@
function guuid() { function guuid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8); var r = Math.random() * 16 | 0,
v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16); return v.toString(16);
}); });
} }
function uniqueid() { function uniqueid() {
return 'xxxxxxxxxxxxxxxx'.replace(/[x]/g, function(c) { return 'xxxxxxxxxxxxxxxx'.replace(/[x]/g, function(c) {
var r = Math.random()*16|0; var r = Math.random() * 16 | 0;
return r.toString(16); return r.toString(16);
}); });
} }
function generateRemoteInputKey() { function generateRemoteInputKey() {
return 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'.replace(/[x]/g, function(c) { return 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'.replace(/[x]/g, function(c) {
var r = Math.random()*16|0; var r = Math.random() * 16 | 0;
return r.toString(16); return r.toString(16);
}); });
} }
function generateRemoteInputKeyId() { function generateRemoteInputKeyId() {
return ((Math.random()-0.5) * 0x7FFFFFFF)|0; return ((Math.random() - 0.5) * 0x7FFFFFFF) | 0;
} }
function getConnectedGamepadMask() { function getConnectedGamepadMask() {
@ -51,13 +52,13 @@ function getConnectedGamepadMask() {
} }
} }
console.log('%c[utils.js, getConnectedGamepadMask]', 'color:gray;', 'Detected '+count+' gamepads'); console.log('%c[utils.js, getConnectedGamepadMask]', 'color:gray;', 'Detected ' + count + ' gamepads');
return mask; return mask;
} }
String.prototype.toHex = function() { String.prototype.toHex = function() {
var hex = ''; var hex = '';
for(var i = 0; i < this.length; i++) { for (var i = 0; i < this.length; i++) {
hex += '' + this.charCodeAt(i).toString(16); hex += '' + this.charCodeAt(i).toString(16);
} }
return hex; return hex;
@ -88,20 +89,20 @@ function NvHTTP(address, clientUid, userEnteredAddress = '') {
_self = this; _self = this;
}; };
function _arrayBufferToBase64( buffer ) { function _arrayBufferToBase64(buffer) {
var binary = ''; var binary = '';
var bytes = new Uint8Array( buffer ); var bytes = new Uint8Array(buffer);
var len = bytes.byteLength; var len = bytes.byteLength;
for (var i = 0; i < len; i++) { for (var i = 0; i < len; i++) {
binary += String.fromCharCode( bytes[ i ] ); binary += String.fromCharCode(bytes[i]);
} }
return window.btoa( binary ); return window.btoa(binary);
} }
function _base64ToArrayBuffer(base64) { function _base64ToArrayBuffer(base64) {
var binary_string = window.atob(base64); var binary_string = window.atob(base64);
var len = binary_string.length; var len = binary_string.length;
var bytes = new Uint8Array( len ); var bytes = new Uint8Array(len);
for (var i = 0; i < len; i++) { for (var i = 0; i < len; i++) {
bytes[i] = binary_string.charCodeAt(i); bytes[i] = binary_string.charCodeAt(i);
} }
@ -109,12 +110,12 @@ function _base64ToArrayBuffer(base64) {
} }
NvHTTP.prototype = { NvHTTP.prototype = {
refreshServerInfo: function () { refreshServerInfo: function() {
// try HTTPS first // 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 if (!this._parseServerInfo(ret)) { // if that fails
// 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', [ this._baseUrlHttp + '/serverinfo?' + this._buildUidStr(), false]).then(function(retHttp) { return sendMessage('openUrl', [this._baseUrlHttp + '/serverinfo?' + this._buildUidStr(), false]).then(function(retHttp) {
this._parseServerInfo(retHttp); this._parseServerInfo(retHttp);
}.bind(this)); }.bind(this));
} }
@ -124,11 +125,11 @@ 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 // 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 // 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('%c[utils.js, utils.js, refreshServerInfoAtAddress]', 'color: gray;', '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);
}.bind(this)); }.bind(this));
} }
@ -216,7 +217,7 @@ NvHTTP.prototype = {
string += 'gpu type: ' + this.gputype + '\r\n'; string += 'gpu type: ' + this.gputype + '\r\n';
string += 'number of apps: ' + this.numofapps + '\r\n'; string += 'number of apps: ' + this.numofapps + '\r\n';
string += 'supported display modes: ' + '\r\n'; string += 'supported display modes: ' + '\r\n';
for(var displayMode in this.supportedDisplayModes) { for (var displayMode in this.supportedDisplayModes) {
string += '\t' + displayMode + ': ' + this.supportedDisplayModes[displayMode] + '\r\n'; string += '\t' + displayMode + ': ' + this.supportedDisplayModes[displayMode] + '\r\n';
} }
return string; return string;
@ -226,11 +227,11 @@ NvHTTP.prototype = {
$xml = this._parseXML(xmlStr); $xml = this._parseXML(xmlStr);
$root = $xml.find('root'); $root = $xml.find('root');
if($root.attr("status_code") != 200) { if ($root.attr("status_code") != 200) {
return false; 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. // if we received a UID that isn't the one we expected, fail.
return false; return false;
} }
@ -253,10 +254,10 @@ NvHTTP.prototype = {
var yres = parseInt($(value).find('Height').text()); var yres = parseInt($(value).find('Height').text());
var xres = parseInt($(value).find('Width').text()); var xres = parseInt($(value).find('Width').text());
var fps = parseInt($(value).find('RefreshRate').text()); var fps = parseInt($(value).find('RefreshRate').text());
if(!this.supportedDisplayModes[yres + ':' + xres]) { if (!this.supportedDisplayModes[yres + ':' + xres]) {
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); this.supportedDisplayModes[yres + ':' + xres].push(fps);
} }
}.bind(this)); }.bind(this));
@ -275,11 +276,11 @@ NvHTTP.prototype = {
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;
@ -292,11 +293,11 @@ NvHTTP.prototype = {
}); });
}, },
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;
@ -309,8 +310,8 @@ NvHTTP.prototype = {
}); });
}, },
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);
$root = $xml.find("root"); $root = $xml.find("root");
@ -337,9 +338,9 @@ NvHTTP.prototype = {
}.bind(this)); }.bind(this));
}, },
getAppList: function () { getAppList: function() {
if (this._memCachedApplist) { if (this._memCachedApplist) {
return new Promise(function (resolve, reject) { return new Promise(function(resolve, reject) {
console.log('%c[utils.js, utils.js]', 'color: gray;', 'Returning memory-cached apps list'); console.log('%c[utils.js, utils.js]', 'color: gray;', 'Returning memory-cached apps list');
resolve(this._memCachedApplist); resolve(this._memCachedApplist);
return; return;
@ -351,22 +352,22 @@ NvHTTP.prototype = {
// 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) {
if (chrome.storage) { if (chrome.storage) {
// This may be bad practice to push/pull this much data through local storage? // This may be bad practice to push/pull this much data through local storage?
return new Promise(function (resolve, reject) { return new Promise(function(resolve, reject) {
chrome.storage.local.get('boxart-'+appId, function(storageData) { chrome.storage.local.get('boxart-' + appId, function(storageData) {
// if we already have it, load it. // if we already have it, load it.
if (storageData !== undefined && Object.keys(storageData).length !== 0 && storageData['boxart-'+appId].constructor !== Object) { if (storageData !== undefined && Object.keys(storageData).length !== 0 && storageData['boxart-' + appId].constructor !== Object) {
console.log('%c[utils.js, getBoxArt]', 'color: gray;', 'Returning storage-cached box art for app: ', appId); console.log('%c[utils.js, getBoxArt]', 'color: gray;', 'Returning storage-cached box art for app: ', appId);
resolve(storageData['boxart-'+appId]); resolve(storageData['boxart-' + appId]);
return; return;
} }
// otherwise, put it in our cache, then return it // otherwise, put it in our cache, then return it
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
@ -374,12 +375,14 @@ NvHTTP.prototype = {
var reader = new FileReader(); var reader = new FileReader();
reader.onloadend = function() { reader.onloadend = function() {
var obj = {}; var obj = {};
obj['boxart-'+appId] = this.result; obj['boxart-' + appId] = this.result;
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 network-fetched box art'); console.log('%c[utils.js, utils.js, getBoxArt]', 'color: gray;', 'Returning network-fetched box art');
resolve(this.result); resolve(this.result);
} }
reader.readAsDataURL(new Blob([boxArtBuffer], {type: "image/png"})); reader.readAsDataURL(new Blob([boxArtBuffer], {
type: "image/png"
}));
}.bind(this), function(error) { }.bind(this), function(error) {
console.error('%c[utils.js, utils.js, getBoxArt]', 'color: gray;', 'Box-art request failed!', error); console.error('%c[utils.js, utils.js, getBoxArt]', 'color: gray;', 'Box-art request failed!', error);
reject(error); reject(error);
@ -392,7 +395,7 @@ NvHTTP.prototype = {
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', [ 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
@ -400,7 +403,7 @@ NvHTTP.prototype = {
} }
}, },
launchApp: function (appId, mode, sops, rikey, rikeyid, localAudio, surroundAudioInfo, gamepadMask) { launchApp: function(appId, mode, sops, rikey, rikeyid, localAudio, surroundAudioInfo, gamepadMask) {
return sendMessage('openUrl', [ return sendMessage('openUrl', [
this._baseUrlHttps + this._baseUrlHttps +
'/launch?' + this._buildUidStr() + '/launch?' + this._buildUidStr() +
@ -414,12 +417,12 @@ NvHTTP.prototype = {
'&remoteControllersBitmap=' + gamepadMask + '&remoteControllersBitmap=' + gamepadMask +
'&gcmap=' + gamepadMask, '&gcmap=' + gamepadMask,
false false
]).then(function (ret) { ]).then(function(ret) {
return true; return true;
}); });
}, },
resumeApp: function (rikey, rikeyid, surroundAudioInfo) { resumeApp: function(rikey, rikeyid, surroundAudioInfo) {
return sendMessage('openUrl', [ return sendMessage('openUrl', [
this._baseUrlHttps + this._baseUrlHttps +
'/resume?' + this._buildUidStr() + '/resume?' + this._buildUidStr() +
@ -427,12 +430,12 @@ NvHTTP.prototype = {
'&rikeyid=' + rikeyid + '&rikeyid=' + rikeyid +
'&surroundAudioInfo=' + surroundAudioInfo, '&surroundAudioInfo=' + surroundAudioInfo,
false false
]).then(function (ret) { ]).then(function(ret) {
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
// session belongs to a different client. // session belongs to a different client.
@ -441,15 +444,15 @@ NvHTTP.prototype = {
}, },
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);
this.paired = $xml.find('paired').html() == "1"; this.paired = $xml.find('paired').html() == "1";
return this.paired; return this.paired;
@ -458,11 +461,11 @@ NvHTTP.prototype = {
}.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()));
}, },
}; };