var hosts = {}; // hosts is an associative array of NvHTTP objects, keyed by server UID var activePolls = {}; // hosts currently being polled. An associated array of polling IDs, keyed by server UID var pairingCert; var myUniqueid; var api; // `api` should only be set if we're in a host-specific screen. on the initial screen it should always be null. var isInGame = false; // flag indicating whether the game stream started var windowState = 'normal'; // chrome's windowState, possible values: 'normal' or 'fullscreen' // Called by the common.js module. function attachListeners() { changeUiModeForNaClLoad(); $('.resolutionMenu li').on('click', saveResolution); $('.framerateMenu li').on('click', saveFramerate); $('#bitrateSlider').on('input', updateBitrateField); // input occurs every notch you slide //$('#bitrateSlider').on('change', saveBitrate); //FIXME: it seems not working $("#remoteAudioEnabledSwitch").on('click', saveRemoteAudio); $('#addHostCell').on('click', addHost); $('#backIcon').on('click', showHostsAndSettingsMode); $('#quitCurrentApp').on('click', stopGameWithConfirmation); $(window).resize(fullscreenNaclModule); chrome.app.window.current().onMaximized.addListener(fullscreenChromeWindow); } function fullscreenChromeWindow() { // when the user clicks the maximize button on the window, // FIRST restore it to the previous size, then fullscreen it to the whole screen // this prevents the previous window size from being 'maximized', // and allows us to functionally retain two window sizes // so that when the user hits `esc`, they go back to the "restored" size, // instead of "maximized", which would immediately go to fullscreen chrome.app.window.current().restore(); chrome.app.window.current().fullscreen(); } function loadWindowState() { if (!chrome.storage) { return; } chrome.storage.sync.get('windowState', function(item) { // load stored window state windowState = (item && item.windowState) ? item.windowState : windowState; // subscribe to chrome's windowState events chrome.app.window.current().onFullscreened.addListener(onFullscreened); chrome.app.window.current().onBoundsChanged.addListener(onBoundsChanged); }); } function onFullscreened() { if (!isInGame && windowState == 'normal') { storeData('windowState', 'fullscreen', null); windowState = 'fullscreen'; } } function onBoundsChanged() { if (!isInGame && windowState == 'fullscreen') { storeData('windowState', 'normal', null); windowState = 'normal'; } } function changeUiModeForNaClLoad() { $('#main-navigation').children().hide(); $("#main-content").children().not("#listener, #naclSpinner").hide(); $('#naclSpinnerMessage').text('Loading Moonlight plugin...'); $('#naclSpinner').css('display', 'inline-block'); } function startPollingHosts() { for(var hostUID in hosts) { beginBackgroundPollingOfHost(hosts[hostUID]); } } function stopPollingHosts() { for(var hostUID in hosts) { stopBackgroundPollingOfHost(hosts[hostUID]); } } function restoreUiAfterNaClLoad() { $('#main-navigation').children().not("#quitCurrentApp").show(); $("#main-content").children().not("#listener, #naclSpinner, #game-grid").show(); $('#naclSpinner').hide(); $('#loadingSpinner').css('display', 'none'); showHostsAndSettingsMode(); 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]; if (finder.byService_['_nvstream._tcp'][ip]) { var 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 we're seeing a host we've already seen before, update it for the current local IP. hosts[returneMdnsDiscoveredHost.serverUid].address = returneMdnsDiscoveredHost.address; } else { beginBackgroundPollingOfHost(returneMdnsDiscoveredHost); addHostToGrid(returneMdnsDiscoveredHost, true); } }); } } } }); } function beginBackgroundPollingOfHost(host) { host.warmBoxArtCache(); 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() { // every 5 seconds, poll at the address we know it was live at host.pollServer(function () { if (host.online) { $("#hostgrid-" + host.serverUid).removeClass('host-cell-inactive'); } else { $("#hostgrid-" + host.serverUid).addClass('host-cell-inactive'); } }); }, 5000); } else { $("#hostgrid-" + host.serverUid).addClass('host-cell-inactive'); // The host was offline, so poll immediately. host.pollServer(function () { if (host.online) { $("#hostgrid-" + host.serverUid).removeClass('host-cell-inactive'); } else { $("#hostgrid-" + host.serverUid).addClass('host-cell-inactive'); } // Now start background polling 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) { $("#hostgrid-" + host.serverUid).removeClass('host-cell-inactive'); } else { $("#hostgrid-" + host.serverUid).addClass('host-cell-inactive'); } }); }, 5000); }); } } function stopBackgroundPollingOfHost(host) { console.log('%c[Moonlight GUI, backgroundPolling]', 'color: green;', 'Stopping background polling of host ' + host.serverUid + '\n', host); window.clearInterval(activePolls[host.serverUid]); delete activePolls[host.serverUid]; } function snackbarLog(givenMessage) { console.log(givenMessage); var data = { message: givenMessage, timeout: 2000 }; document.querySelector('#snackbar').MaterialSnackbar.showSnackbar(data); } function snackbarLogLong(givenMessage) { console.log(givenMessage); var data = { message: givenMessage, timeout: 5000 }; document.querySelector('#snackbar').MaterialSnackbar.showSnackbar(data); } function updateBitrateField() { $('#bitrateField').html($('#bitrateSlider').val() + " Mbps"); saveBitrate(); } function moduleDidLoad() { if(!myUniqueid) { console.warn('%c[Moonlight GUI, 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[Moonlight GUI, moduleDidLoad]', 'color: green;', 'Failed to load local cert. Generating new one'); sendMessage('makeCert', []).then(function (cert) { storeData('cert', cert, null); pairingCert = cert; console.info('%c[Moonlight GUI, moduleDidLoad]', 'color: green;', 'Generated new cert:', cert); }, function (failedCert) { console.error('%c[Moonlight GUI, moduleDidLoad]', 'color: green;', 'Failed to generate new cert! Returned error was: \n', failedCert); }).then(function (ret) { sendMessage('httpInit', [pairingCert.cert, pairingCert.privateKey, myUniqueid]).then(function (ret) { restoreUiAfterNaClLoad(); }, function (failedInit) { console.error('%c[Moonlight GUI, moduleDidLoad]', 'color: green;', 'Failed httpInit! Returned error was: ', failedInit); }); }); } else { sendMessage('httpInit', [pairingCert.cert, pairingCert.privateKey, myUniqueid]).then(function (ret) { restoreUiAfterNaClLoad(); }, function (failedInit) { console.error('%c[Moonlight GUI, 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) { snackbarLog('ERROR: cert has not been generated yet. Is NaCl initialized?'); console.warn('%c[Moonlight GUI]', 'color: green;', 'User wants to pair, and we still have no cert. Problem = very yes.'); onFailure(); return; } nvhttpHost.pollServer(function (ret) { if (!nvhttpHost.online) { snackbarLog('Failed to connect to ' + nvhttpHost.hostname + '! Are you sure the host is on?'); console.error('%c[Moonlight GUI]', 'color: green;', 'Host declared as offline:', nvhttpHost, nvhttpHost.toString()); //Logging both the object and the toString version for text logs onFailure(); return; } if (nvhttpHost.paired) { onSuccess(); return; } var randomNumber = String("0000" + (Math.random()*10000|0)).slice(-4); 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'); pairingDialog.showModal(); $('#cancelPairingDialog').off('click'); $('#cancelPairingDialog').on('click', function () { pairingDialog.close(); }); console.log('%c[Moonlight GUI]', 'color: green;', 'Sending pairing request to ' + nvhttpHost.hostname + ' with random number' + randomNumber); nvhttpHost.pair(randomNumber).then(function (paired) { if (!paired) { 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 + '.'); } console.log('%c[Moonlight GUI]', 'color: green;', 'Failed API object:', nvhttpHost, nvhttpHost.toString()); //Logging both the object and the toString version for text logs onFailure(); return; } snackbarLog('Pairing successful'); pairingDialog.close(); onSuccess(); }, function (failedPairing) { snackbarLog('Failed pairing to: ' + nvhttpHost.hostname); console.error('%c[Moonlight GUI]', 'color: green;', 'Pairing failed, and returned:', failedPairing); console.error('%c[Moonlight GUI]', 'color: green;', 'Failed API object:', nvhttpHost, nvhttpHost.toString()); //Logging both the object and the toString version for text logs onFailure(); }); }); } function hostChosen(host) { if (!host.online) { return; } // Avoid delay from other polling during pairing stopPollingHosts(); api = host; if (!host.paired) { // Still not paired; go to the pairing flow pairTo(host, function() { showApps(host); saveHosts(); }, function(){ startPollingHosts(); }); } else { // When we queried again, it was paired, so show apps. showApps(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'); modal.showModal(); // drop the dialog if they cancel $('#cancelAddHost').off('click'); $('#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); pairTo(_nvhttpHost, function() { beginBackgroundPollingOfHost(_nvhttpHost); addHostToGrid(_nvhttpHost); saveHosts(); }, function() { snackbarLog('pairing to ' + inputHost + ' failed!'); }); modal.close(); }); } // host is an NvHTTP object function addHostToGrid(host, ismDNSDiscovered) { var outerDiv = $("