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); $('#optimizeGamesSwitch').on('click', saveOptimize); $('#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; hosts[returneMdnsDiscoveredHost.serverUid].updateExternalAddressIP4(); } else { // Host must be in the grid before starting background polling addHostToGrid(returneMdnsDiscoveredHost, true); beginBackgroundPollingOfHost(returneMdnsDiscoveredHost); } saveHosts(); }); } } } }); } function beginBackgroundPollingOfHost(host) { var el = document.querySelector('#hostgrid-' + host.serverUid) if (host.online) { el.classList.remove('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) { el.classList.remove('host-cell-inactive') } else { el.classList.add('host-cell-inactive') } }); }, 5000); } else { el.classList.add('host-cell-inactive') // The host was offline, so poll immediately. host.pollServer(function() { if (host.online) { el.classList.remove('host-cell-inactive') } else { el.classList.add('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) { el.classList.remove('host-cell-inactive') } else { el.classList.add('host-cell-inactive') } }); }, 5000); }); } } 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]; } function snackbarLog(givenMessage) { console.log('%c[index.js, snackbarLog]', 'color: green;', givenMessage); var data = { message: givenMessage, timeout: 2000 }; document.querySelector('#snackbar').MaterialSnackbar.showSnackbar(data); } function snackbarLogLong(givenMessage) { console.log('%c[index.js, snackbarLog]', 'color: green;', givenMessage); var data = { message: givenMessage, timeout: 5000 }; document.querySelector('#snackbar').MaterialSnackbar.showSnackbar(data); } function updateBitrateField() { $('#bitrateField').html($('#bitrateSlider').val() + " Mbps"); saveBitrate(); } function moduleDidLoad() { // load the HTTP cert and unique ID if we have one. 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 myUniqueid = savedUniqueid.uniqueid; } else { 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'); sendMessage('makeCert', []).then(function(cert) { storeData('cert', cert, null); pairingCert = cert; console.info('%c[index.js, moduleDidLoad]', 'color: green;', 'Generated new cert:', cert); }, function(failedCert) { console.error('%c[index.js, 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[index.js, 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[index.js, moduleDidLoad]', 'color: green;', 'Failed httpInit! Returned error was: ', failedInit); }); } // 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); revivedHost.serverUid = hosts[hostUID].serverUid; revivedHost.externalIP = hosts[hostUID].externalIP; revivedHost.hostname = hosts[hostUID].hostname; revivedHost.ppkstr = hosts[hostUID].ppkstr; addHostToGrid(revivedHost); } console.log('%c[index.js]', 'color: green;', 'Loaded previously connected hosts'); }); }); }); } // 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[index.js]', '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 + '! Ensure that GameStream is enabled in GeForce Experience.'); console.error('%c[index.js]', 'color: green;', 'Host declared as offline:', nvhttpHost, nvhttpHost.toString()); //Logging both the object and the toString version for text logs onFailure(); 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[index.js]', 'color: green;', 'Sending pairing request to ' + nvhttpHost.hostname + ' with PIN: ' + randomNumber); nvhttpHost.pair(randomNumber).then(function() { snackbarLog('Pairing successful'); pairingDialog.close(); onSuccess(); }, function(failedPairing) { snackbarLog('Failed pairing to: ' + nvhttpHost.hostname); 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[index.js]', '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); _nvhttpHost.refreshServerInfoAtAddress(inputHost).then(function(success) { if (hosts[_nvhttpHost.serverUid] != null) { _nvhttpHost.ppkstr = hosts[_nvhttpHost.serverUid].ppkstr; } modal.close(); pairTo(_nvhttpHost, function() { // Check if we already have record of this host if (hosts[_nvhttpHost.serverUid] != null) { // Just update the addresses hosts[_nvhttpHost.serverUid].address = _nvhttpHost.address; hosts[_nvhttpHost.serverUid].userEnteredAddress = _nvhttpHost.userEnteredAddress; } else { // Host must be in the grid before starting background polling addHostToGrid(_nvhttpHost); beginBackgroundPollingOfHost(_nvhttpHost); } saveHosts(); }); }.bind(this), function(failure) { snackbarLog('Failed to connect to ' + _nvhttpHost.hostname + '! Ensure that GameStream is enabled in GeForce Experience.'); }.bind(this)); }); } // host is an NvHTTP object function addHostToGrid(host, ismDNSDiscovered) { var outerDiv = $("