From 618cca1117044d15e5cd061e76a80ae0d27aaaad Mon Sep 17 00:00:00 2001 From: Laion Camargo Date: Fri, 1 Feb 2019 18:49:02 +0000 Subject: [PATCH 1/4] Revert "Fix badge" This reverts commit 0a5696871e59c441d64ba037349e5e8861ab6ed5. --- js/sendControll.js | 64 ------------------------------------- proxy_form_controller.js | 69 +++------------------------------------- 2 files changed, 5 insertions(+), 128 deletions(-) diff --git a/js/sendControll.js b/js/sendControll.js index aba0af3..11cbc28 100644 --- a/js/sendControll.js +++ b/js/sendControll.js @@ -4,62 +4,6 @@ $(document).ready(function() { var defaultPort = "8180"; var defaultStats = "[not available]"; - - var url = "http://geo.geosurf.io/"; - var xmlhttp = new XMLHttpRequest(); - - xmlhttp.onreadystatechange = function() { - if (xmlhttp.status != 200 && window.localStorage['proxyConfig'][20] != "s") { - - // Badge the popup icon. - var RED = [255, 0, 0, 255]; - chrome.browserAction.setBadgeBackgroundColor({color: RED}); - chrome.browserAction.setBadgeText({text: 'X'}); - chrome.browserAction.setTitle({ - title: chrome.i18n.getMessage('errorPopupTitle') - }); - - // delete all existing and opened alerts - var els = document.getElementsByClassName('overlay'); - - while (els[0]) { - els[0].classList.remove('active') - } - - clearErrorDivs(); - - var success = document.createElement('div'); - success.setAttribute('id', 'proxyFail'); - - if(close == true){ - success.classList.add('overlay'); - } - else{ - success.removeAttribute('hidden', 'hidden'); - success.classList.add('proxyFailMsg'); - } - success.setAttribute('role', 'alert'); - - success.textContent = chrome.i18n.getMessage('errorProxyError'); - - document.getElementById("connectedMsg").innerText = "CONNECTION ERROR"; - document.getElementById("tryAgainMsg").innerText = "TRY AGAIN"; - document.getElementById("imgError").removeAttribute('hidden', 'hidden'); - document.getElementById("dataValue").setAttribute('hidden', 'hidden'); - - document.getElementById("settingsConfig").setAttribute('hidden', 'hidden'); - - // switch visible sections, hiding welcome screen and showing the other where error is shown - document.getElementById("fixed_servers").setAttribute('hidden', 'hidden'); - document.getElementById("system").removeAttribute('hidden', 'hidden'); - - document.getElementById("dataValue").setAttribute('hidden', 'hidden'); - - document.body.appendChild(success); - - setTimeout(function() { success.classList.add('visible'); }, 10); - } - } if (window.localStorage['proxyConfig'] == undefined || window.localStorage['proxyConfig'][20] == "s") { console.log("Local Storage does not exist"); @@ -188,14 +132,6 @@ $(document).ready(function() { } }); - - xmlhttp.open("GET", url, true); - xmlhttp.timeout = 2500; // time in milliseconds - xmlhttp.setRequestHeader('Access-Control-Allow-Origin','*'); - xmlhttp.setRequestHeader('Access-Control-Allow-Methods', '*'); - xmlhttp.setRequestHeader('Access-Control-Allow-Headers', '*'); - xmlhttp.send(); - // make following action fire when radio button changes $('input[type=radio]').click(function(){ if(document.getElementById('proxyHostHttp').value.length < 1 && document.getElementById('proxyPortHttp').value.length < 1){ diff --git a/proxy_form_controller.js b/proxy_form_controller.js index e3d26a7..1dcfcf0 100644 --- a/proxy_form_controller.js +++ b/proxy_form_controller.js @@ -1,6 +1,6 @@ // interval between each online check. Increase if successfull, decrease if unsuccessfull -var defaultOnlineCheckTimeout = 1000; -var onlineCheckTimeout = 1000; +var defaultOnlineCheckTimeout = 5000; +var onlineCheckTimeout = 5000; var onlineTimeoutID = 0; // id of the latest timeout so we can reset it if needed var defaultStats = "[not available]"; @@ -25,58 +25,6 @@ function resetOnlineTimerCheck() { resetTimeoutOnline(); } -function getBadge() { - if (window.localStorage['proxyConfig'][20] != "s") { - // Badge the popup icon. - var RED = [255, 0, 0, 255]; - chrome.browserAction.setBadgeBackgroundColor({color: RED}); - chrome.browserAction.setBadgeText({text: 'X'}); - chrome.browserAction.setTitle({ - title: chrome.i18n.getMessage('errorPopupTitle') - }); - - // delete all existing and opened alerts - var els = document.getElementsByClassName('overlay'); - - while (els[0]) { - els[0].classList.remove('active') - } - - clearErrorDivs(); - - var success = document.createElement('div'); - success.setAttribute('id', 'proxyFail'); - - if(close == true){ - success.classList.add('overlay'); - } - else{ - success.removeAttribute('hidden', 'hidden'); - success.classList.add('proxyFailMsg'); - } - success.setAttribute('role', 'alert'); - - success.textContent = chrome.i18n.getMessage('errorProxyError'); - - document.getElementById("connectedMsg").innerText = "CONNECTION ERROR"; - document.getElementById("tryAgainMsg").innerText = "TRY AGAIN"; - document.getElementById("imgError").removeAttribute('hidden', 'hidden'); - document.getElementById("dataValue").setAttribute('hidden', 'hidden'); - - document.getElementById("settingsConfig").setAttribute('hidden', 'hidden'); - - // switch visible sections, hiding welcome screen and showing the other where error is shown - document.getElementById("fixed_servers").setAttribute('hidden', 'hidden'); - document.getElementById("system").removeAttribute('hidden', 'hidden'); - - document.getElementById("dataValue").setAttribute('hidden', 'hidden'); - - document.body.appendChild(success); - - setTimeout(function() { success.classList.add('visible'); }, 10); - } -} - // check if extension is online function getOnline() { // keep track of the timeout ID so we can reset it @@ -113,13 +61,9 @@ function getOnline() { setServerIP(response.ip); // increase interval for checks if last request was successfull and recursively call to the function - setOnlineTimerCheck(5 * defaultOnlineCheckTimeout); + setOnlineTimerCheck(6 * defaultOnlineCheckTimeout); } else if (xmlhttp.status == 0) { - - // Badge the popup icon. - getBadge(); - // show an alert and disconnect if we are connected and an error is found // if this is not an empty array, extension popup is open @@ -128,10 +72,10 @@ function getOnline() { if (views.length != 0) { if (document.getElementById("system").hidden == false) { // trigger click on disconnect button - //document.getElementById("proxyTypeSystem").click(); + document.getElementById("proxyTypeSystem").click(); // even though we clicked on disconnect, we want to see the try again screen - //generateAlert(chrome.i18n.getMessage('errorProxyError'), false); + generateAlert(chrome.i18n.getMessage('errorProxyError'), false); //generateAlert("TEST1", false); } } @@ -289,9 +233,6 @@ function updateProxyStats() { setTimeout(function() { updateProxyStats(); }, 1000); - } else { - // Badge the popup icon. - getBadge(); } /* console.log(xmlhttp); From 36959afa9b3f140ba5ed8884e1ceb765b63ec661 Mon Sep 17 00:00:00 2001 From: Laion Camargo Date: Thu, 7 Feb 2019 11:57:38 +0000 Subject: [PATCH 2/4] change from 1 seconds to 5 seconds each request --- js/sendControll.js | 64 ++++++++++++++++++++++++++++++++++++++ proxy_form_controller.js | 67 +++++++++++++++++++++++++++++++++++++--- 2 files changed, 127 insertions(+), 4 deletions(-) diff --git a/js/sendControll.js b/js/sendControll.js index 11cbc28..aba0af3 100644 --- a/js/sendControll.js +++ b/js/sendControll.js @@ -4,6 +4,62 @@ $(document).ready(function() { var defaultPort = "8180"; var defaultStats = "[not available]"; + + var url = "http://geo.geosurf.io/"; + var xmlhttp = new XMLHttpRequest(); + + xmlhttp.onreadystatechange = function() { + if (xmlhttp.status != 200 && window.localStorage['proxyConfig'][20] != "s") { + + // Badge the popup icon. + var RED = [255, 0, 0, 255]; + chrome.browserAction.setBadgeBackgroundColor({color: RED}); + chrome.browserAction.setBadgeText({text: 'X'}); + chrome.browserAction.setTitle({ + title: chrome.i18n.getMessage('errorPopupTitle') + }); + + // delete all existing and opened alerts + var els = document.getElementsByClassName('overlay'); + + while (els[0]) { + els[0].classList.remove('active') + } + + clearErrorDivs(); + + var success = document.createElement('div'); + success.setAttribute('id', 'proxyFail'); + + if(close == true){ + success.classList.add('overlay'); + } + else{ + success.removeAttribute('hidden', 'hidden'); + success.classList.add('proxyFailMsg'); + } + success.setAttribute('role', 'alert'); + + success.textContent = chrome.i18n.getMessage('errorProxyError'); + + document.getElementById("connectedMsg").innerText = "CONNECTION ERROR"; + document.getElementById("tryAgainMsg").innerText = "TRY AGAIN"; + document.getElementById("imgError").removeAttribute('hidden', 'hidden'); + document.getElementById("dataValue").setAttribute('hidden', 'hidden'); + + document.getElementById("settingsConfig").setAttribute('hidden', 'hidden'); + + // switch visible sections, hiding welcome screen and showing the other where error is shown + document.getElementById("fixed_servers").setAttribute('hidden', 'hidden'); + document.getElementById("system").removeAttribute('hidden', 'hidden'); + + document.getElementById("dataValue").setAttribute('hidden', 'hidden'); + + document.body.appendChild(success); + + setTimeout(function() { success.classList.add('visible'); }, 10); + } + } if (window.localStorage['proxyConfig'] == undefined || window.localStorage['proxyConfig'][20] == "s") { console.log("Local Storage does not exist"); @@ -132,6 +188,14 @@ $(document).ready(function() { } }); + + xmlhttp.open("GET", url, true); + xmlhttp.timeout = 2500; // time in milliseconds + xmlhttp.setRequestHeader('Access-Control-Allow-Origin','*'); + xmlhttp.setRequestHeader('Access-Control-Allow-Methods', '*'); + xmlhttp.setRequestHeader('Access-Control-Allow-Headers', '*'); + xmlhttp.send(); + // make following action fire when radio button changes $('input[type=radio]').click(function(){ if(document.getElementById('proxyHostHttp').value.length < 1 && document.getElementById('proxyPortHttp').value.length < 1){ diff --git a/proxy_form_controller.js b/proxy_form_controller.js index 1dcfcf0..b07e504 100644 --- a/proxy_form_controller.js +++ b/proxy_form_controller.js @@ -1,5 +1,5 @@ // interval between each online check. Increase if successfull, decrease if unsuccessfull -var defaultOnlineCheckTimeout = 5000; +var defaultOnlineCheckTimeout = 1000; var onlineCheckTimeout = 5000; var onlineTimeoutID = 0; // id of the latest timeout so we can reset it if needed @@ -25,6 +25,58 @@ function resetOnlineTimerCheck() { resetTimeoutOnline(); } +function getBadge() { + if (window.localStorage['proxyConfig'][20] != "s") { + // Badge the popup icon. + var RED = [255, 0, 0, 255]; + chrome.browserAction.setBadgeBackgroundColor({color: RED}); + chrome.browserAction.setBadgeText({text: 'X'}); + chrome.browserAction.setTitle({ + title: chrome.i18n.getMessage('errorPopupTitle') + }); + + // delete all existing and opened alerts + var els = document.getElementsByClassName('overlay'); + + while (els[0]) { + els[0].classList.remove('active') + } + + clearErrorDivs(); + + var success = document.createElement('div'); + success.setAttribute('id', 'proxyFail'); + + if(close == true){ + success.classList.add('overlay'); + } + else{ + success.removeAttribute('hidden', 'hidden'); + success.classList.add('proxyFailMsg'); + } + success.setAttribute('role', 'alert'); + + success.textContent = chrome.i18n.getMessage('errorProxyError'); + + document.getElementById("connectedMsg").innerText = "CONNECTION ERROR"; + document.getElementById("tryAgainMsg").innerText = "TRY AGAIN"; + document.getElementById("imgError").removeAttribute('hidden', 'hidden'); + document.getElementById("dataValue").setAttribute('hidden', 'hidden'); + + document.getElementById("settingsConfig").setAttribute('hidden', 'hidden'); + + // switch visible sections, hiding welcome screen and showing the other where error is shown + document.getElementById("fixed_servers").setAttribute('hidden', 'hidden'); + document.getElementById("system").removeAttribute('hidden', 'hidden'); + + document.getElementById("dataValue").setAttribute('hidden', 'hidden'); + + document.body.appendChild(success); + + setTimeout(function() { success.classList.add('visible'); }, 10); + } +} + // check if extension is online function getOnline() { // keep track of the timeout ID so we can reset it @@ -61,9 +113,13 @@ function getOnline() { setServerIP(response.ip); // increase interval for checks if last request was successfull and recursively call to the function - setOnlineTimerCheck(6 * defaultOnlineCheckTimeout); + setOnlineTimerCheck(5 * defaultOnlineCheckTimeout); } else if (xmlhttp.status == 0) { + + // Badge the popup icon. + getBadge(); + // show an alert and disconnect if we are connected and an error is found // if this is not an empty array, extension popup is open @@ -72,10 +128,10 @@ function getOnline() { if (views.length != 0) { if (document.getElementById("system").hidden == false) { // trigger click on disconnect button - document.getElementById("proxyTypeSystem").click(); + //document.getElementById("proxyTypeSystem").click(); // even though we clicked on disconnect, we want to see the try again screen - generateAlert(chrome.i18n.getMessage('errorProxyError'), false); + //generateAlert(chrome.i18n.getMessage('errorProxyError'), false); //generateAlert("TEST1", false); } } @@ -233,6 +289,9 @@ function updateProxyStats() { setTimeout(function() { updateProxyStats(); }, 1000); + } else { + // Badge the popup icon. + getBadge(); } /* console.log(xmlhttp); From 68f87d567e7f62cf43ed416a7e1340385085f431 Mon Sep 17 00:00:00 2001 From: Laion Camargo Date: Wed, 13 Feb 2019 10:43:45 +0000 Subject: [PATCH 3/4] fix some request to haproxy --- proxy_form_controller.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/proxy_form_controller.js b/proxy_form_controller.js index b07e504..2266177 100644 --- a/proxy_form_controller.js +++ b/proxy_form_controller.js @@ -1,6 +1,6 @@ // interval between each online check. Increase if successfull, decrease if unsuccessfull -var defaultOnlineCheckTimeout = 1000; -var onlineCheckTimeout = 5000; +var defaultOnlineCheckTimeout = 10000; +var onlineCheckTimeout = 10000; var onlineTimeoutID = 0; // id of the latest timeout so we can reset it if needed var defaultStats = "[not available]"; @@ -113,7 +113,7 @@ function getOnline() { setServerIP(response.ip); // increase interval for checks if last request was successfull and recursively call to the function - setOnlineTimerCheck(5 * defaultOnlineCheckTimeout); + setOnlineTimerCheck(6 * defaultOnlineCheckTimeout); } else if (xmlhttp.status == 0) { From b94de6e00b2cec29c868f642eed6097336f0b0b1 Mon Sep 17 00:00:00 2001 From: Laion Camargo Date: Mon, 25 Feb 2019 13:58:06 +0000 Subject: [PATCH 4/4] Remove many request to haproxy, fix badge, remove repeated code --- js/sendControll.js | 64 -- proxy_error_handler.js | 40 - proxy_form_controller.js | 1564 ++++++++++++++++++-------------------- 3 files changed, 735 insertions(+), 933 deletions(-) diff --git a/js/sendControll.js b/js/sendControll.js index aba0af3..11cbc28 100644 --- a/js/sendControll.js +++ b/js/sendControll.js @@ -4,62 +4,6 @@ $(document).ready(function() { var defaultPort = "8180"; var defaultStats = "[not available]"; - - var url = "http://geo.geosurf.io/"; - var xmlhttp = new XMLHttpRequest(); - - xmlhttp.onreadystatechange = function() { - if (xmlhttp.status != 200 && window.localStorage['proxyConfig'][20] != "s") { - - // Badge the popup icon. - var RED = [255, 0, 0, 255]; - chrome.browserAction.setBadgeBackgroundColor({color: RED}); - chrome.browserAction.setBadgeText({text: 'X'}); - chrome.browserAction.setTitle({ - title: chrome.i18n.getMessage('errorPopupTitle') - }); - - // delete all existing and opened alerts - var els = document.getElementsByClassName('overlay'); - - while (els[0]) { - els[0].classList.remove('active') - } - - clearErrorDivs(); - - var success = document.createElement('div'); - success.setAttribute('id', 'proxyFail'); - - if(close == true){ - success.classList.add('overlay'); - } - else{ - success.removeAttribute('hidden', 'hidden'); - success.classList.add('proxyFailMsg'); - } - success.setAttribute('role', 'alert'); - - success.textContent = chrome.i18n.getMessage('errorProxyError'); - - document.getElementById("connectedMsg").innerText = "CONNECTION ERROR"; - document.getElementById("tryAgainMsg").innerText = "TRY AGAIN"; - document.getElementById("imgError").removeAttribute('hidden', 'hidden'); - document.getElementById("dataValue").setAttribute('hidden', 'hidden'); - - document.getElementById("settingsConfig").setAttribute('hidden', 'hidden'); - - // switch visible sections, hiding welcome screen and showing the other where error is shown - document.getElementById("fixed_servers").setAttribute('hidden', 'hidden'); - document.getElementById("system").removeAttribute('hidden', 'hidden'); - - document.getElementById("dataValue").setAttribute('hidden', 'hidden'); - - document.body.appendChild(success); - - setTimeout(function() { success.classList.add('visible'); }, 10); - } - } if (window.localStorage['proxyConfig'] == undefined || window.localStorage['proxyConfig'][20] == "s") { console.log("Local Storage does not exist"); @@ -188,14 +132,6 @@ $(document).ready(function() { } }); - - xmlhttp.open("GET", url, true); - xmlhttp.timeout = 2500; // time in milliseconds - xmlhttp.setRequestHeader('Access-Control-Allow-Origin','*'); - xmlhttp.setRequestHeader('Access-Control-Allow-Methods', '*'); - xmlhttp.setRequestHeader('Access-Control-Allow-Headers', '*'); - xmlhttp.send(); - // make following action fire when radio button changes $('input[type=radio]').click(function(){ if(document.getElementById('proxyHostHttp').value.length < 1 && document.getElementById('proxyPortHttp').value.length < 1){ diff --git a/proxy_error_handler.js b/proxy_error_handler.js index 5bf2d27..67ee7dd 100644 --- a/proxy_error_handler.js +++ b/proxy_error_handler.js @@ -69,40 +69,8 @@ ProxyErrorHandler.prototype = { * @private */ handleError_: function(details) { - var xhttp = new XMLHttpRequest(); - xhttp.addEventListener("error", transferFailed ); - xhttp.addEventListener("load", transferComplete); - xhttp.open("GET", "https://geoip.nekudo.com/api/", true); - xhttp.send(); - - function transferFailed(){ - var RED = [255, 0, 0, 255]; - var YELLOW = [255, 205, 0, 255]; - - // Badge the popup icon. - var color = details.fatal ? RED : YELLOW; - chrome.browserAction.setBadgeBackgroundColor({color: color}); - chrome.browserAction.setBadgeText({text: 'X'}); - chrome.browserAction.setTitle({ - title: chrome.i18n.getMessage('errorPopupTitle', details.error) - }); - } - // Store the error for display in the popup. this.lastError_ = JSON.stringify(details); - - function transferComplete(){ - if(document.getElementById('proxyFail') !== null){ - document.getElementById('proxyFail').setAttribute('hidden', 'hidden'); - var GREEN = [124, 252, 0, 255]; - chrome.browserAction.setBadgeText({text: 'o'}); - chrome.browserAction.setBadgeBackgroundColor({color: GREEN}); - chrome.browserAction.setTitle({ - title: chrome.i18n.getMessage('connectedPopupTitle') - }); - } - - } }, @@ -124,14 +92,6 @@ ProxyErrorHandler.prototype = { chrome.browserAction.setTitle({ title: chrome.i18n.getMessage('extDescription') }); - if(window.localStorage['proxyConfig'][20] == "f"){ - var GREEN = [124, 252, 0, 255]; - chrome.browserAction.setBadgeText({text: 'o'}); - chrome.browserAction.setBadgeBackgroundColor({color: GREEN}); - chrome.browserAction.setTitle({ - title: chrome.i18n.getMessage('connectedPopupTitle') - }); - } this.lastError_ = null; } } diff --git a/proxy_form_controller.js b/proxy_form_controller.js index 2266177..507a643 100644 --- a/proxy_form_controller.js +++ b/proxy_form_controller.js @@ -25,79 +25,31 @@ function resetOnlineTimerCheck() { resetTimeoutOnline(); } -function getBadge() { - if (window.localStorage['proxyConfig'][20] != "s") { - // Badge the popup icon. - var RED = [255, 0, 0, 255]; - chrome.browserAction.setBadgeBackgroundColor({color: RED}); - chrome.browserAction.setBadgeText({text: 'X'}); - chrome.browserAction.setTitle({ - title: chrome.i18n.getMessage('errorPopupTitle') - }); - - // delete all existing and opened alerts - var els = document.getElementsByClassName('overlay'); - - while (els[0]) { - els[0].classList.remove('active') - } - - clearErrorDivs(); - - var success = document.createElement('div'); - success.setAttribute('id', 'proxyFail'); - - if(close == true){ - success.classList.add('overlay'); - } - else{ - success.removeAttribute('hidden', 'hidden'); - success.classList.add('proxyFailMsg'); - } - success.setAttribute('role', 'alert'); - - success.textContent = chrome.i18n.getMessage('errorProxyError'); - - document.getElementById("connectedMsg").innerText = "CONNECTION ERROR"; - document.getElementById("tryAgainMsg").innerText = "TRY AGAIN"; - document.getElementById("imgError").removeAttribute('hidden', 'hidden'); - document.getElementById("dataValue").setAttribute('hidden', 'hidden'); - - document.getElementById("settingsConfig").setAttribute('hidden', 'hidden'); - - // switch visible sections, hiding welcome screen and showing the other where error is shown - document.getElementById("fixed_servers").setAttribute('hidden', 'hidden'); - document.getElementById("system").removeAttribute('hidden', 'hidden'); - - document.getElementById("dataValue").setAttribute('hidden', 'hidden'); - - document.body.appendChild(success); - - setTimeout(function() { success.classList.add('visible'); }, 10); - } -} - // check if extension is online function getOnline() { // keep track of the timeout ID so we can reset it onlineTimeoutID = setTimeout(function() { - console.log("Checking if we are online"); - - var url = "http://geo.geosurf.io/"; + var url = "https://geo.geosurf.io/"; var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState != 4) { return; } - - if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { + + updateProxyProvider(); + + console.log("ready stats 4"); + if (xmlhttp.status == 200) { + console.log("status 200 google"); chrome.browserAction.setBadgeText({text: ''}); chrome.browserAction.setTitle({ title: chrome.i18n.getMessage('extDescription') }); + if (window.localStorage['proxyConfig'] != undefined && window.localStorage['proxyConfig'][20] == "f") { + console.log("status 200 geo surf ip + " + window.localStorage['proxyConfig'][20]); var GREEN = [124, 252, 0, 255]; chrome.browserAction.setBadgeText({text: 'o'}); chrome.browserAction.setBadgeBackgroundColor({color: GREEN}); @@ -107,45 +59,36 @@ function getOnline() { clearErrorDivs(); } - + var response = JSON.parse(xmlhttp.response); - setServerIP(response.ip); - + if (response.ip) { + setServerIP(response.ip); + } else { + setServerIP("Unable to locate"); + } + // increase interval for checks if last request was successfull and recursively call to the function setOnlineTimerCheck(6 * defaultOnlineCheckTimeout); - } - else if (xmlhttp.status == 0) { + } else if (xmlhttp.status != 200) { // Badge the popup icon. - getBadge(); + generateAlert(chrome.i18n.getMessage('errorProxyError'), false); // show an alert and disconnect if we are connected and an error is found // if this is not an empty array, extension popup is open var views = chrome.extension.getViews({ type: "popup" }); - - if (views.length != 0) { - if (document.getElementById("system").hidden == false) { - // trigger click on disconnect button - //document.getElementById("proxyTypeSystem").click(); - - // even though we clicked on disconnect, we want to see the try again screen - //generateAlert(chrome.i18n.getMessage('errorProxyError'), false); - //generateAlert("TEST1", false); - } - } // reset interval for checks if last request was unsuccessfull and recursively call to the function resetOnlineTimerCheck(); } // hide loading screen, if visible - if(document.getElementById("loadingScreen") !== null){ - //document.getElementById("loadingScreen").setAttribute("hidden", true); - document.getElementById('loadingScreen').style.removeProperty("display"); - } - + if(document.getElementById("loadingScreen") !== null){ + //document.getElementById("loadingScreen").setAttribute("hidden", true); + document.getElementById('loadingScreen').style.removeProperty("display"); + } } xmlhttp.open("GET", url, true); @@ -157,8 +100,6 @@ function getOnline() { }, onlineCheckTimeout); - - console.log("New timeout ID is " + onlineTimeoutID + " and timeout was " + onlineCheckTimeout); } @@ -210,93 +151,91 @@ function csvToArray( strData, strDelimiter ){ function timer(time) { - secs = parseFloat(time) - console.log(secs + " my secs ------------") - var h = secs/60/60 - var m = (secs/60)%60 - var s = secs%60 - var array = [h,m,s].map(Math.floor) - var value = '' - for(x = 0; x < array.length; x++){ - if(array[x] < 10){ - array[x] = "0" + array[x] - }else{ - array[x] = array[x] - } - function getCom(y){ - if(y < 2){return ":"}else{return ""} - } - var c = getCom(x) - value = value + array[x] + c - } - - return value + secs = parseFloat(time) + var h = secs/60/60 + var m = (secs/60)%60 + var s = secs%60 + var array = [h,m,s].map(Math.floor) + var value = '' + for (x = 0; x < array.length; x++) { + if (array[x] < 10) { + array[x] = "0" + array[x] + } else { + array[x] = array[x] + } + function getCom(y) { + if(y < 2) { + return ":" + } else { + return "" + } + } + var c = getCom(x) + value = value + array[x] + c + } + return value } // update connection stats if we are indeed connected function updateProxyStats() { var type = 'Http'; - + //console.log(document.getElementById('proxyHost' + type)); if(document.getElementById('proxyHost' + type) !== null || document.getElementById('proxyPort' + type) !== null){ - var haproxyIp = document.getElementById('proxyHost' + type).value; - var haproxyPort = parseInt(document.getElementById('proxyPort' + type).value, 10); - - } - + var haproxyIp = document.getElementById('proxyHost' + type).value; + var haproxyPort = parseInt(document.getElementById('proxyPort' + type).value, 10); + } + // return and check later if host or port is invalid if (haproxyIp == "" || isNaN(haproxyPort)) { setTimeout(function() { updateProxyStats(); }, 5000); - + return; } - - var url = "http://" + haproxyIp + ":8181/stats;csv"; - - console.log("Checking HAProxy @ " + url); - + + var url = "http://" + haproxyIp + ":8181/stats;csv"; var xmlhttp = new XMLHttpRequest(); - + // get every seconds from haproxy info about donwload/upload/time online xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { - console.log(xmlhttp.responseText + "my response") //parse donwload and upload haproxy stats from /stats;csv var haproxyStats = csvToArray(xmlhttp.responseText); haproxyStats = JSON.stringify(haproxyStats[1]); - console.log(haproxyStats + "my haproxyStats") haproxyStats = haproxyStats.split(','); haproxyStats[8] = haproxyStats[8].replace('"', ''); haproxyStats[9] = haproxyStats[9].replace('"', ''); - + var data = "Down: " + formatBytes(parseInt(haproxyStats[9])) + " Up: " + formatBytes(parseInt(haproxyStats[8])); - console.log("Download: " + formatBytes(parseInt(haproxyStats[8])) + " / Upload: "+ formatBytes(parseInt(haproxyStats[9]))); - // parse time online from /stats;csv haproxyStats = csvToArray(xmlhttp.responseText); haproxyStats = JSON.stringify(haproxyStats[3]); - console.log(haproxyStats + "my haproxyStats") haproxyStats = haproxyStats.split(','); haproxyStats[23] = haproxyStats[23].replace('"', ''); var timeOnline = haproxyStats[23]; - + setConnectionData(timeOnline, data); + getOnline(); setTimeout(function() { updateProxyStats(); - }, 1000); - } else { - // Badge the popup icon. - getBadge(); + }, 5000); + + } else if (xmlhttp.status != 200 && xmlhttp.readyState == 4) { + if (window.localStorage['proxyConfig'] != undefined && window.localStorage['proxyConfig'][20] != "s") { + // Badge the popup icon. + var RED = [255, 0, 0, 255]; + chrome.browserAction.setBadgeBackgroundColor({color: RED}); + chrome.browserAction.setBadgeText({text: 'X'}); + chrome.browserAction.setTitle({ + title: chrome.i18n.getMessage('errorPopupTitle') + }); + } } - /* - console.log(xmlhttp); - console.log(xmlhttp.responseText); - */ } xmlhttp.open("GET", url, true); @@ -313,37 +252,18 @@ function updateProxyProvider() { var xmlhttpProvider = new XMLHttpRequest(); xmlhttpProvider.onreadystatechange=function() { if (xmlhttpProvider.readyState == 4 && xmlhttpProvider.status == 200) { - console.log(xmlhttpProvider.responseText); var providerStats = JSON.parse(xmlhttpProvider.responseText); - console.log(providerStats.provider + " my provider 0") - console.log(providerStats.service + " my provider 0") - //document.getElementById("providerName").innerText = providerStats.provider; - //document.getElementById("serviceName").innerText = providerStats.service; setConnectionProvider(providerStats.provider, providerStats.service); - - -/* - var providerStats = csvToArray(xmlhttpProvider.responseText); - providerStats = JSON.stringify(providerStats); - providerStats = providerStats.split(','); - providerStats[0] = providerStats[0].split('"').join(''); - providerStats[0] = providerStats[0].split("[").join(''); - providerStats[1] = providerStats[1].split('"').join(''); - providerStats[1] = providerStats[1].split(']').join(''); - console.log(providerStats + " -------------------------------- FULL"); - console.log(providerStats[0] + " -------------------------------- PROVIDER"); - console.log(providerStats[1] + " -------------------------------- PLAN"); - - //document.getElementById("providerName").value = providerStats[0].provider; - //document.getElementById("serviceName").value = providerStats[0].plan; - - setConnectionProvider(providerStats[0], providerStats[1]); - -*/ - - setTimeout(function() { - updateProxyProvider(); - }, 1000); + } else if (xmlhttpProvider.status != 200 && xmlhttpProvider.readyState == 4) { + if (window.localStorage['proxyConfig'] != undefined && window.localStorage['proxyConfig'][20] != "s") { + // Badge the popup icon. + var RED = [255, 0, 0, 255]; + chrome.browserAction.setBadgeBackgroundColor({color: RED}); + chrome.browserAction.setBadgeText({text: 'X'}); + chrome.browserAction.setTitle({ + title: chrome.i18n.getMessage('errorPopupTitle') + }); + } } } @@ -368,9 +288,12 @@ function updateConnectedScreenStats() { if (document.getElementById('timeOnline') !== null) { var time = localStorage.getItem('stats_time'); + if (isNaN(parseInt(time))) { + time = 1; + } document.getElementById('timeOnline').innerHTML = timer(time); // increase local timer - localStorage.setItem('stats_time', time + 1); + localStorage.setItem('stats_time', parseInt(time) + 1); } if (document.getElementById('serverIP') !== null) { @@ -393,7 +316,6 @@ function setServerIP(ip) { ip = defaultStats; } - console.log("Setting server IP to " + ip); localStorage.setItem('stats_ip', ip); } @@ -409,7 +331,6 @@ function setConnectionData(timeOnline, dataTransferred) { dataTransferred = defaultStats; } - console.log("Setting Connection Values"); localStorage.setItem('stats_time', timeOnline); localStorage.setItem('stats_transfer', dataTransferred); } @@ -426,7 +347,6 @@ function setConnectionProvider(providerName, serviceName) { serviceName = defaultStats; } - console.log("Setting Connection Values"); localStorage.setItem('stats_provider', providerName); localStorage.setItem('stats_service', serviceName); } @@ -442,7 +362,6 @@ function formatBytes(bytes,decimals) { } - // activate method to check if we are online resetOnlineTimerCheck(); @@ -457,28 +376,28 @@ updateConnectedScreenStats(); var ProxyFormController = function(id) { - this.form_ = document.getElementById(id); + this.form_ = document.getElementById(id); - // Throw an error if the element either doesn't exist, or isn't a form. - if (!this.form_) - throw chrome.i18n.getMessage('errorIdNotFound', id); - else if (this.form_.nodeName !== 'FORM') - throw chrome.i18n.getMessage('errorIdNotForm', id); + // Throw an error if the element either doesn't exist, or isn't a form. + if (!this.form_) + throw chrome.i18n.getMessage('errorIdNotFound', id); + else if (this.form_.nodeName !== 'FORM') + throw chrome.i18n.getMessage('errorIdNotForm', id); - /** - * Cached references to the `fieldset` groups that define the configuration - * options presented to the user. - * - * @type {NodeList} - * @private - */ - this.configGroups_ = document.querySelectorAll('#' + id + ' > fieldset'); + /** + * Cached references to the `fieldset` groups that define the configuration + * options presented to the user. + * + * @type {NodeList} + * @private + */ + this.configGroups_ = document.querySelectorAll('#' + id + ' > fieldset'); - this.bindEventHandlers_(); - this.readCurrentState_(); + this.bindEventHandlers_(); + this.readCurrentState_(); - // Handle errors - this.handleProxyErrors_(); + // Handle errors + this.handleProxyErrors_(); }; @@ -489,9 +408,9 @@ var ProxyFormController = function(id) { * @enum {string} */ ProxyFormController.ProxyTypes = { - AUTO: 'auto_detect', - FIXED: 'fixed_servers', - SYSTEM: 'system' + AUTO: 'auto_detect', + FIXED: 'fixed_servers', + SYSTEM: 'system' }; /** @@ -499,8 +418,8 @@ ProxyFormController.ProxyTypes = { * @enum {int} */ ProxyFormController.WindowTypes = { - REGULAR: 1, - INCOGNITO: 2 + REGULAR: 1, + INCOGNITO: 2 }; /** @@ -508,10 +427,10 @@ ProxyFormController.WindowTypes = { * @enum {string} */ ProxyFormController.LevelOfControl = { - NOT_CONTROLLABLE: 'not_controllable', - OTHER_EXTENSION: 'controlled_by_other_extension', - AVAILABLE: 'controllable_by_this_extension', - CONTROLLING: 'controlled_by_this_extension' + NOT_CONTROLLABLE: 'not_controllable', + OTHER_EXTENSION: 'controlled_by_other_extension', + AVAILABLE: 'controllable_by_this_extension', + CONTROLLING: 'controlled_by_this_extension' }; /** @@ -532,10 +451,10 @@ ProxyFormController.WrappedProxyConfig; * @static */ ProxyFormController.getPersistedSettings = function() { - var result = null; - if (window.localStorage['proxyConfig'] !== undefined) - result = JSON.parse(window.localStorage['proxyConfig']); - return result ? result : null; + var result = null; + if (window.localStorage['proxyConfig'] !== undefined) + result = JSON.parse(window.localStorage['proxyConfig']); + return result ? result : null; }; @@ -546,605 +465,581 @@ ProxyFormController.getPersistedSettings = function() { * @static */ ProxyFormController.setPersistedSettings = function(config) { - console.log("Storing Settings"); - console.log(config); - window.localStorage['proxyConfig'] = JSON.stringify(config); + console.log("Storing Settings"); + console.log(config); + window.localStorage['proxyConfig'] = JSON.stringify(config); }; /////////////////////////////////////////////////////////////////////////////// ProxyFormController.prototype = { - /** - * The form's current state. - * @type {regular: ?ProxyConfig, incognito: ?ProxyConfig} - * @private - */ - config_: {regular: null, incognito: null}, - - /** - * Do we have access to incognito mode? - * @type {boolean} - * @private - */ - isAllowedIncognitoAccess_: false, - - - /** - * @return {Array} A list of hostnames that should bypass the proxy. - */ - get bypassList() { - console.log("bypasslist"); - return [""]; - - //return document.getElementById('bypassList').value.split(/\s*(?:,|^)\s*/m); - }, - - - /** - * @param {?Array} data A list of hostnames that should bypass - * the proxy. If empty, the bypass list is emptied. - */ - set bypassList(data) { - if (!data) - data = []; - document.getElementById('bypassList').value = data.join(', '); - }, - - - /** - * @see http://code.google.com/chrome/extensions/trunk/proxy.html - * @return {?ProxyServer} An object containing the proxy server host, port, - * and scheme. If null, there is no single proxy. - */ - get singleProxy() { - //document.getElementById('singleProxyForEverything').checked = true; - //var checkbox = document.getElementById('singleProxyForEverything'); - return this.httpProxy - //return checkbox.checked ? this.httpProxy : null; - }, - - - /** - * @see http://code.google.com/chrome/extensions/trunk/proxy.html - * @param {?ProxyServer} data An object containing the proxy server host, - * port, and scheme. If null, the single proxy checkbox will be unchecked. - */ - - /** - * @return {?ProxyServer} An object containing the proxy server host, port - * and scheme. - */ - get httpProxy() { - return this.getProxyImpl_('Http'); - }, - - - /** - * @param {?ProxyServer} data An object containing the proxy server host, - * port, and scheme. If empty, empties the proxy setting. - */ - set httpProxy(data) { - this.setProxyImpl_('Http', data); - }, - - - /** - * @return {?ProxyServer} An object containing the proxy server host, port - * and scheme. - */ - get httpsProxy() { - return this.getProxyImpl_('Https'); - }, - - - /** - * @param {?ProxyServer} data An object containing the proxy server host, - * port, and scheme. If empty, empties the proxy setting. - */ - set httpsProxy(data) { - this.setProxyImpl_('Https', data); - }, - - - /** - * @return {?ProxyServer} An object containing the proxy server host, port - * and scheme. - */ - get ftpProxy() { - return this.getProxyImpl_('Ftp'); - }, - - - /** - * @param {?ProxyServer} data An object containing the proxy server host, - * port, and scheme. If empty, empties the proxy setting. - */ - set ftpProxy(data) { - this.setProxyImpl_('Ftp', data); - }, - - - /** - * @return {?ProxyServer} An object containing the proxy server host, port - * and scheme. - */ - get fallbackProxy() { - return this.getProxyImpl_('Fallback'); - }, - - - /** - * @param {?ProxyServer} data An object containing the proxy server host, - * port, and scheme. If empty, empties the proxy setting. - */ - set fallbackProxy(data) { - this.setProxyImpl_('Fallback', data); - }, - - - /** - * @param {string} type The type of proxy that's being set ("Http", - * "Https", etc.). - * @return {?ProxyServer} An object containing the proxy server host, - * port, and scheme. - * @private - */ - getProxyImpl_: function(type) { - var result = { - scheme: document.getElementById('proxyScheme' + type).value, - host: document.getElementById('proxyHost' + type).value, - port: parseInt(document.getElementById('proxyPort' + type).value, 10) - }; - return (result.scheme && result.host && result.port) ? result : undefined; - }, - - - /** - * A generic mechanism for setting proxy data. - * - * @see http://code.google.com/chrome/extensions/trunk/proxy.html - * @param {string} type The type of proxy that's being set ("Http", - * "Https", etc.). - * @param {?ProxyServer} data An object containing the proxy server host, - * port, and scheme. If empty, empties the proxy setting. - * @private - */ - setProxyImpl_: function(type, data) { - if (!data) - data = {scheme: 'http', host: '', port: ''}; - - document.getElementById('proxyScheme' + type).value = data.scheme; - document.getElementById('proxyHost' + type).value = data.host; - document.getElementById('proxyPort' + type).value = data.port; - }, + /** + * The form's current state. + * @type {regular: ?ProxyConfig, incognito: ?ProxyConfig} + * @private + */ + config_: {regular: null, incognito: null}, + + /** + * Do we have access to incognito mode? + * @type {boolean} + * @private + */ + isAllowedIncognitoAccess_: false, + + + /** + * @return {Array} A list of hostnames that should bypass the proxy. + */ + get bypassList() { + console.log("bypasslist"); + return [""]; + + //return document.getElementById('bypassList').value.split(/\s*(?:,|^)\s*/m); + }, + + + /** + * @param {?Array} data A list of hostnames that should bypass + * the proxy. If empty, the bypass list is emptied. + */ + set bypassList(data) { + if (!data) + data = []; + document.getElementById('bypassList').value = data.join(', '); + }, + + + /** + * @see http://code.google.com/chrome/extensions/trunk/proxy.html + * @return {?ProxyServer} An object containing the proxy server host, port, + * and scheme. If null, there is no single proxy. + */ + get singleProxy() { + //document.getElementById('singleProxyForEverything').checked = true; + //var checkbox = document.getElementById('singleProxyForEverything'); + return this.httpProxy + //return checkbox.checked ? this.httpProxy : null; + }, + + + /** + * @see http://code.google.com/chrome/extensions/trunk/proxy.html + * @param {?ProxyServer} data An object containing the proxy server host, + * port, and scheme. If null, the single proxy checkbox will be unchecked. + */ + + /** + * @return {?ProxyServer} An object containing the proxy server host, port + * and scheme. + */ + get httpProxy() { + return this.getProxyImpl_('Http'); + }, + + + /** + * @param {?ProxyServer} data An object containing the proxy server host, + * port, and scheme. If empty, empties the proxy setting. + */ + set httpProxy(data) { + this.setProxyImpl_('Http', data); + }, + + + /** + * @return {?ProxyServer} An object containing the proxy server host, port + * and scheme. + */ + get httpsProxy() { + return this.getProxyImpl_('Https'); + }, + + + /** + * @param {?ProxyServer} data An object containing the proxy server host, + * port, and scheme. If empty, empties the proxy setting. + */ + set httpsProxy(data) { + this.setProxyImpl_('Https', data); + }, + + + /** + * @return {?ProxyServer} An object containing the proxy server host, port + * and scheme. + */ + get ftpProxy() { + return this.getProxyImpl_('Ftp'); + }, + + + /** + * @param {?ProxyServer} data An object containing the proxy server host, + * port, and scheme. If empty, empties the proxy setting. + */ + set ftpProxy(data) { + this.setProxyImpl_('Ftp', data); + }, + + + /** + * @return {?ProxyServer} An object containing the proxy server host, port + * and scheme. + */ + get fallbackProxy() { + return this.getProxyImpl_('Fallback'); + }, + + + /** + * @param {?ProxyServer} data An object containing the proxy server host, + * port, and scheme. If empty, empties the proxy setting. + */ + set fallbackProxy(data) { + this.setProxyImpl_('Fallback', data); + }, + + + /** + * @param {string} type The type of proxy that's being set ("Http", + * "Https", etc.). + * @return {?ProxyServer} An object containing the proxy server host, + * port, and scheme. + * @private + */ + getProxyImpl_: function(type) { + var result = { + scheme: document.getElementById('proxyScheme' + type).value, + host: document.getElementById('proxyHost' + type).value, + port: parseInt(document.getElementById('proxyPort' + type).value, 10) + }; + return (result.scheme && result.host && result.port) ? result : undefined; + }, + + + /** + * A generic mechanism for setting proxy data. + * + * @see http://code.google.com/chrome/extensions/trunk/proxy.html + * @param {string} type The type of proxy that's being set ("Http", + * "Https", etc.). + * @param {?ProxyServer} data An object containing the proxy server host, + * port, and scheme. If empty, empties the proxy setting. + * @private + */ + setProxyImpl_: function(type, data) { + if (!data) data = {scheme: 'http', host: '', port: ''}; + + document.getElementById('proxyScheme' + type).value = data.scheme; + document.getElementById('proxyHost' + type).value = data.host; + document.getElementById('proxyPort' + type).value = data.port; + }, + + /////////////////////////////////////////////////////////////////////////////// + + /** + * Calls the proxy API to read the current settings, and populates the form + * accordingly. + * + * @private + */ + readCurrentState_: function() { + chrome.extension.isAllowedIncognitoAccess(this.handleIncognitoAccessResponse_.bind(this)); + }, + + /** + * Handles the respnse from `chrome.extension.isAllowedIncognitoAccess` + * We can't render the form until we know what our access level is, so + * we wait until we have confirmed incognito access levels before + * asking for the proxy state. + * + * @param {boolean} state The state of incognito access. + * @private + */ + handleIncognitoAccessResponse_: function(state) { + this.isAllowedIncognitoAccess_ = state; + chrome.proxy.settings.get({incognito: false}, + this.handleRegularState_.bind(this)); + if (this.isAllowedIncognitoAccess_) { + chrome.proxy.settings.get({incognito: true}, this.handleIncognitoState_.bind(this)); + } + }, + + /** + * Handles the response from 'proxy.settings.get' for regular + * settings. + * + * @param {ProxyFormController.WrappedProxyConfig} c The proxy data and + * extension's level of control thereof. + * @private + */ + handleRegularState_: function(c) { + if (c.levelOfControl === ProxyFormController.LevelOfControl.AVAILABLE || + c.levelOfControl === ProxyFormController.LevelOfControl.CONTROLLING) { + this.recalcFormValues_(c.value); + this.config_.regular = c.value; + } else { + this.handleLackOfControl_(c.levelOfControl); + } + }, + + /** + * Handles the response from 'proxy.settings.get' for incognito + * settings. + * + * @param {ProxyFormController.WrappedProxyConfig} c The proxy data and + * extension's level of control thereof. + * @private + */ + handleIncognitoState_: function(c) { + if (c.levelOfControl === ProxyFormController.LevelOfControl.AVAILABLE || c.levelOfControl === ProxyFormController.LevelOfControl.CONTROLLING) { + if (this.isIncognitoMode_()) this.recalcFormValues_(c.value); + + this.config_.incognito = c.value; + } else { + this.handleLackOfControl_(c.levelOfControl); + } + }, + + /** + * Binds event handlers for the various bits and pieces of the form that + * are interesting to the controller. + * + * @private + */ + bindEventHandlers_: function() { + this.form_.addEventListener('click', this.dispatchFormClick_.bind(this)); + }, + + + /** + * When a `click` event is triggered on the form, this function handles it by + * analyzing the context, and dispatching the click to the correct handler. + * + * @param {Event} e The event to be handled. + * @private + * @return {boolean} True if the event should bubble, false otherwise. + */ + dispatchFormClick_: function(e) { + var t = e.target; + + console.log('dispatchFormClick_ ' + t); + + // Case 1: "Apply" + if (t.nodeName === 'BUTTON' && t.getAttribute('type') === 'submit') { + while (t && (t.nodeName !== 'FIELDSET' || t.parentNode.nodeName !== 'FORM')) { + t = t.parentNode; + } + if (t) { + return this.applyChanges_(e); + } -/////////////////////////////////////////////////////////////////////////////// + } else { + // Walk up the tree until we hit `form > fieldset` or fall off the top + while (t && (t.nodeName !== 'FIELDSET' || + t.parentNode.nodeName !== 'FORM')) { + t = t.parentNode; + } + if (t) { + this.changeActive_(t); + } + } - /** - * Calls the proxy API to read the current settings, and populates the form - * accordingly. - * - * @private - */ - readCurrentState_: function() { - chrome.extension.isAllowedIncognitoAccess( - this.handleIncognitoAccessResponse_.bind(this)); - }, - - /** - * Handles the respnse from `chrome.extension.isAllowedIncognitoAccess` - * We can't render the form until we know what our access level is, so - * we wait until we have confirmed incognito access levels before - * asking for the proxy state. - * - * @param {boolean} state The state of incognito access. - * @private - */ - handleIncognitoAccessResponse_: function(state) { - this.isAllowedIncognitoAccess_ = state; - chrome.proxy.settings.get({incognito: false}, - this.handleRegularState_.bind(this)); - if (this.isAllowedIncognitoAccess_) { - chrome.proxy.settings.get({incognito: true}, - this.handleIncognitoState_.bind(this)); - } - }, - - /** - * Handles the response from 'proxy.settings.get' for regular - * settings. - * - * @param {ProxyFormController.WrappedProxyConfig} c The proxy data and - * extension's level of control thereof. - * @private - */ - handleRegularState_: function(c) { - if (c.levelOfControl === ProxyFormController.LevelOfControl.AVAILABLE || - c.levelOfControl === ProxyFormController.LevelOfControl.CONTROLLING) { - this.recalcFormValues_(c.value); - this.config_.regular = c.value; - } else { - this.handleLackOfControl_(c.levelOfControl); - } - }, - - /** - * Handles the response from 'proxy.settings.get' for incognito - * settings. - * - * @param {ProxyFormController.WrappedProxyConfig} c The proxy data and - * extension's level of control thereof. - * @private - */ - handleIncognitoState_: function(c) { - if (c.levelOfControl === ProxyFormController.LevelOfControl.AVAILABLE || - c.levelOfControl === ProxyFormController.LevelOfControl.CONTROLLING) { - if (this.isIncognitoMode_()) - this.recalcFormValues_(c.value); - - this.config_.incognito = c.value; - } else { - this.handleLackOfControl_(c.levelOfControl); - } - }, - - /** - * Binds event handlers for the various bits and pieces of the form that - * are interesting to the controller. - * - * @private - */ - bindEventHandlers_: function() { - this.form_.addEventListener('click', this.dispatchFormClick_.bind(this)); - }, - - - /** - * When a `click` event is triggered on the form, this function handles it by - * analyzing the context, and dispatching the click to the correct handler. - * - * @param {Event} e The event to be handled. - * @private - * @return {boolean} True if the event should bubble, false otherwise. - */ - dispatchFormClick_: function(e) { - var t = e.target; - - console.log('dispatchFormClick_ ' + t); - - // Case 1: "Apply" - if (t.nodeName === 'BUTTON' && t.getAttribute('type') === 'submit') { - while (t && (t.nodeName !== 'FIELDSET' || t.parentNode.nodeName !== 'FORM')) { - t = t.parentNode; - } - if (t) { - return this.applyChanges_(e); - } + return true; + }, + + + /** + * Sets the form's active config group. + * + * @param {DOMElement} fieldset The configuration group to activate. + * @private + */ + changeActive_: function(fieldset) { + for (var i = 0; i < this.configGroups_.length; i++) { + var el = this.configGroups_[i]; + var radio = el.querySelector("input[type='radio']"); + if (el === fieldset) { + el.classList.add('active'); + radio.checked = true; + } else { + el.classList.remove('active'); + } + } - } else { - // Walk up the tree until we hit `form > fieldset` or fall off the top - while (t && (t.nodeName !== 'FIELDSET' || - t.parentNode.nodeName !== 'FORM')) { - t = t.parentNode; - } - if (t) { - this.changeActive_(t); - } - } - - return true; - }, - - - /** - * Sets the form's active config group. - * - * @param {DOMElement} fieldset The configuration group to activate. - * @private - */ - changeActive_: function(fieldset) { - for (var i = 0; i < this.configGroups_.length; i++) { - var el = this.configGroups_[i]; - var radio = el.querySelector("input[type='radio']"); - if (el === fieldset) { - el.classList.add('active'); - radio.checked = true; + this.recalcDisabledInputs_(); + }, + + + /** + * Recalculates the `disabled` state of the form's input elements, based + * on the currently active group, and that group's contents. + * + * @private + */ + recalcDisabledInputs_: function() { + var i, j; + for (i = 0; i < this.configGroups_.length; i++) { + var el = this.configGroups_[i]; + var inputs = el.querySelectorAll( + "input:not([type='radio']), select, textarea"); + if (el.classList.contains('active')) { + for (j = 0; j < inputs.length; j++) { + inputs[j].removeAttribute('disabled'); + console.log(inputs[j].id) + } - } else { - el.classList.remove('active'); - } - } - - this.recalcDisabledInputs_(); - }, - - - /** - * Recalculates the `disabled` state of the form's input elements, based - * on the currently active group, and that group's contents. - * - * @private - */ - recalcDisabledInputs_: function() { - var i, j; - for (i = 0; i < this.configGroups_.length; i++) { - var el = this.configGroups_[i]; - var inputs = el.querySelectorAll( - "input:not([type='radio']), select, textarea"); - if (el.classList.contains('active')) { - for (j = 0; j < inputs.length; j++) { - inputs[j].removeAttribute('disabled'); - console.log(inputs[j].id) - - } - } else { - for (j = 0; j < inputs.length; j++) { - inputs[j].setAttribute('disabled', 'disabled'); - } - } - } - - }, - - - /** - * Handler called in response to click on form's submission button. Generates - * the proxy configuration and passes it to `useCustomProxySettings`, or - * handles errors in user input. - * - * Proxy errors (and the browser action's badge) are cleared upon setting new - * values. - * - * @param {Event} e DOM event generated by the user's click. - * @private - */ - applyChanges_: function(e) { - - console.log("applyChanges_ start"); - console.log(e); - - e.preventDefault(); - e.stopPropagation(); - - if (this.isIncognitoMode_()) - this.config_.incognito = this.generateProxyConfig_(); - else - this.config_.regular = this.generateProxyConfig_(); - - chrome.proxy.settings.set( - {value: this.config_.regular, scope: 'regular'}, - this.callbackForRegularSettings_.bind(this)); - chrome.extension.sendRequest({type: 'clearError'}); - }, - - /** - * Called in response to setting a regular window's proxy settings: checks - * for `lastError`, and then sets incognito settings (if they exist). - * - * @private - */ - callbackForRegularSettings_: function() { - if (chrome.runtime.lastError) { - this.generateAlert_(chrome.i18n.getMessage('errorSettingRegularProxy'), true); - //this.generateAlert_("TEST2", true); - - // trigger click on disconnect button - document.getElementById("proxyTypeSystem").click(); - - return; - } - if (this.config_.incognito) { - chrome.proxy.settings.set( - {value: this.config_.incognito, scope: 'incognito_persistent'}, - this.callbackForIncognitoSettings_.bind(this)); - } else { - ProxyFormController.setPersistedSettings(this.config_); - } - }, - - /** - * Called in response to setting an incognito window's proxy settings: checks - * for `lastError` and sets a success message. - * - * @private - */ - callbackForIncognitoSettings_: function() { - if (chrome.runtime.lastError) { - this.generateAlert_(chrome.i18n.getMessage('errorSettingIncognitoProxy')); - //this.generateAlert_("TEST3"); - return; - } - ProxyFormController.setPersistedSettings(this.config_); - }, - - /** - * Generates an alert overlay inside the proxy's popup, then closes the popup - * after a short delay. - * - * @param {string} msg The message to be displayed in the overlay. - * @param {?boolean} close Should the window be closed? Defaults to true. - * @private - */ - generateAlert_: function(msg, close) { - generateAlert(msg, close); - }, - - - /** - * Parses the proxy configuration form, and generates a ProxyConfig object - * that can be passed to `useCustomProxyConfig`. - * - * @see http://code.google.com/chrome/extensions/trunk/proxy.html - * @return {ProxyConfig} The proxy configuration represented by the form. - * @private - */ - generateProxyConfig_: function() { - var active = document.getElementsByClassName('active')[0]; - switch (active.id) { - case ProxyFormController.ProxyTypes.SYSTEM: - return {mode: 'system'}; - case ProxyFormController.ProxyTypes.FIXED: - var config = {mode: 'fixed_servers'}; - config.rules = { - singleProxy: this.singleProxy, - bypassList: this.bypassList - }; - return config; - } - }, - - - /** - * Sets the proper display classes based on the "Use the same proxy server - * for all protocols" checkbox. Expects to be called as an event handler - * when that field is clicked. - * - * @param {Event} e The `click` event to respond to. - * @private - */ - toggleSingleProxyConfig_: function(e) { - var checkbox = e.target; - - checkbox.parentNode.parentNode.classList.add('single'); - }, - - - /** - * Returns the form's current incognito status. - * - * @return {boolean} True if the form is in incognito mode, false otherwise. - * @private - */ - isIncognitoMode_: function(e) { - return this.form_.parentNode.classList.contains('incognito'); - }, - - - /** - * Toggles the form's incognito mode. Saves the current state to an object - * property for later use, clears the form, and toggles the appropriate state. - * - * @param {Event} e The `click` event to respond to. - * @private - */ - toggleIncognitoMode_: function(e) { - var div = this.form_.parentNode; - var button = document.getElementsByTagName('button')[0]; - - // Cancel the button click. - e.preventDefault(); - e.stopPropagation(); - - // If we can't access Incognito settings, throw a message and return. - if (!this.isAllowedIncognitoAccess_) { - var msg = "I'm sorry, I'm afraid I can't do that. Give me access " + - "to Incognito settings by checking the checkbox labeled " + - "'Allow in Incognito mode', which is visible at " + - "chrome://extensions."; - this.generateAlert_(msg, false); - return; - } - - if (this.isIncognitoMode_()) { - // In incognito mode, switching to cognito. - this.config_.incognito = this.generateProxyConfig_(); - div.classList.remove('incognito'); - this.recalcFormValues_(this.config_.regular); - button.innerText = 'Configure incognito window settings.'; - } else { - // In cognito mode, switching to incognito. - this.config_.regular = this.generateProxyConfig_(); - div.classList.add('incognito'); - this.recalcFormValues_(this.config_.incognito); - button.innerText = 'Configure regular window settings.'; - } - }, - - - /** - * Sets the form's values based on a ProxyConfig. - * - * @param {!ProxyConfig} c The ProxyConfig object. - * @private - */ - recalcFormValues_: function(c) { - - console.log("Mode " + c.mode); - // Activate one of the groups, based on `mode`. - this.changeActive_(document.getElementById(c.mode)); - - // Evaluate the `rules` - if (c.rules) { - var rules = c.rules; - //if (rules.singleProxy) { - this.singleProxy = rules.singleProxy; - this.bypassList = rules.bypassList; - } else { - this.singleProxy = null; - this.httpProxy = null; - this.httpsProxy = null; - this.ftpProxy = null; - this.fallbackProxy = null; - this.bypassList = ''; - } - }, - - - /** - * Handles the case in which this extension doesn't have the ability to - * control the Proxy settings, either because of an overriding policy - * or an extension with higher priority. - * - * @param {ProxyFormController.LevelOfControl} l The level of control this - * extension has over the proxy settings. - * @private - */ - handleLackOfControl_: function(l) { - var msg; - if (l === ProxyFormController.LevelOfControl.NO_ACCESS) - msg = chrome.i18n.getMessage('errorNoExtensionAccess'); - else if (l === ProxyFormController.LevelOfControl.OTHER_EXTENSION) - msg = chrome.i18n.getMessage('errorOtherExtensionControls'); - this.generateAlert_(msg); - //this.generateAlert_("TEST4" + msg); - }, - - - /** - * Handle the case in which errors have been generated outside the context - * of this popup. - * - * @private - */ - handleProxyErrors_: function() { - chrome.extension.sendRequest( - {type: 'getError'}, - this.handleProxyErrorHandlerResponse_.bind(this)); - }, - - /** - * Handles response from ProxyErrorHandler - * - * @param {{result: !string}} response The message sent in response to this - * popup's request. - */ - handleProxyErrorHandlerResponse_: function(response) { - - if (response.result !== null) { - var error = JSON.parse(response.result); - - // ignore, sometimes we get temporary tunnel connections failed but proxy is working - if (error.error == "net::ERR_TUNNEL_CONNECTION_FAILED") { - return; - } - - this.generateAlert_( - chrome.i18n.getMessage( - error.details ? 'errorProxyDetailedError' : 'errorProxyError', - [error.error, error.details]), - false); - } - } + } else { + for (j = 0; j < inputs.length; j++) { + inputs[j].setAttribute('disabled', 'disabled'); + } + } + } + }, + + + /** + * Handler called in response to click on form's submission button. Generates + * the proxy configuration and passes it to `useCustomProxySettings`, or + * handles errors in user input. + * + * Proxy errors (and the browser action's badge) are cleared upon setting new + * values. + * + * @param {Event} e DOM event generated by the user's click. + * @private + */ + applyChanges_: function(e) { + console.log("applyChanges_ start"); + console.log(e); + + e.preventDefault(); + e.stopPropagation(); + + if (this.isIncognitoMode_()) + this.config_.incognito = this.generateProxyConfig_(); + else + this.config_.regular = this.generateProxyConfig_(); + + chrome.proxy.settings.set({value: this.config_.regular, scope: 'regular'}, this.callbackForRegularSettings_.bind(this)); + chrome.extension.sendRequest({type: 'clearError'}); + }, + + /** + * Called in response to setting a regular window's proxy settings: checks + * for `lastError`, and then sets incognito settings (if they exist). + * + * @private + */ + callbackForRegularSettings_: function() { + if (chrome.runtime.lastError) { + this.generateAlert_(chrome.i18n.getMessage('errorSettingRegularProxy'), true); + //this.generateAlert_("TEST2", true); + + // trigger click on disconnect button + document.getElementById("proxyTypeSystem").click(); + + return; + } + if (this.config_.incognito) { + chrome.proxy.settings.set({value: this.config_.incognito, scope: 'incognito_persistent'}, this.callbackForIncognitoSettings_.bind(this)); + } else { + ProxyFormController.setPersistedSettings(this.config_); + } + }, + + /** + * Called in response to setting an incognito window's proxy settings: checks + * for `lastError` and sets a success message. + * + * @private + */ + callbackForIncognitoSettings_: function() { + if (chrome.runtime.lastError) { + this.generateAlert_(chrome.i18n.getMessage('errorSettingIncognitoProxy')); + //this.generateAlert_("TEST3"); + return; + } + ProxyFormController.setPersistedSettings(this.config_); + }, + + /** + * Generates an alert overlay inside the proxy's popup, then closes the popup + * after a short delay. + * + * @param {string} msg The message to be displayed in the overlay. + * @param {?boolean} close Should the window be closed? Defaults to true. + * @private + */ + generateAlert_: function(msg, close) { + generateAlert(msg, close); + }, + + + /** + * Parses the proxy configuration form, and generates a ProxyConfig object + * that can be passed to `useCustomProxyConfig`. + * + * @see http://code.google.com/chrome/extensions/trunk/proxy.html + * @return {ProxyConfig} The proxy configuration represented by the form. + * @private + */ + generateProxyConfig_: function() { + var active = document.getElementsByClassName('active')[0]; + switch (active.id) { + case ProxyFormController.ProxyTypes.SYSTEM: + return {mode: 'system'}; + case ProxyFormController.ProxyTypes.FIXED: + var config = {mode: 'fixed_servers'}; + config.rules = {singleProxy: this.singleProxy, bypassList: this.bypassList}; + return config; + } + }, + + + /** + * Sets the proper display classes based on the "Use the same proxy server + * for all protocols" checkbox. Expects to be called as an event handler + * when that field is clicked. + * + * @param {Event} e The `click` event to respond to. + * @private + */ + toggleSingleProxyConfig_: function(e) { + var checkbox = e.target; + + checkbox.parentNode.parentNode.classList.add('single'); + }, + + + /** + * Returns the form's current incognito status. + * + * @return {boolean} True if the form is in incognito mode, false otherwise. + * @private + */ + isIncognitoMode_: function(e) { + return this.form_.parentNode.classList.contains('incognito'); + }, + + + /** + * Toggles the form's incognito mode. Saves the current state to an object + * property for later use, clears the form, and toggles the appropriate state. + * + * @param {Event} e The `click` event to respond to. + * @private + */ + toggleIncognitoMode_: function(e) { + var div = this.form_.parentNode; + var button = document.getElementsByTagName('button')[0]; + + // Cancel the button click. + e.preventDefault(); + e.stopPropagation(); + + // If we can't access Incognito settings, throw a message and return. + if (!this.isAllowedIncognitoAccess_) { + var msg = "I'm sorry, I'm afraid I can't do that. Give me access " + + "to Incognito settings by checking the checkbox labeled " + + "'Allow in Incognito mode', which is visible at " + + "chrome://extensions."; + this.generateAlert_(msg, false); + return; + } + + if (this.isIncognitoMode_()) { + // In incognito mode, switching to cognito. + this.config_.incognito = this.generateProxyConfig_(); + div.classList.remove('incognito'); + this.recalcFormValues_(this.config_.regular); + button.innerText = 'Configure incognito window settings.'; + } else { + // In cognito mode, switching to incognito. + this.config_.regular = this.generateProxyConfig_(); + div.classList.add('incognito'); + this.recalcFormValues_(this.config_.incognito); + button.innerText = 'Configure regular window settings.'; + } + }, + + + /** + * Sets the form's values based on a ProxyConfig. + * + * @param {!ProxyConfig} c The ProxyConfig object. + * @private + */ + recalcFormValues_: function(c) { + // Activate one of the groups, based on `mode`. + this.changeActive_(document.getElementById(c.mode)); + + // Evaluate the `rules` + if (c.rules) { + var rules = c.rules; + //if (rules.singleProxy) { + this.singleProxy = rules.singleProxy; + this.bypassList = rules.bypassList; + } else { + this.singleProxy = null; + this.httpProxy = null; + this.httpsProxy = null; + this.ftpProxy = null; + this.fallbackProxy = null; + this.bypassList = ''; + } + }, + + + /** + * Handles the case in which this extension doesn't have the ability to + * control the Proxy settings, either because of an overriding policy + * or an extension with higher priority. + * + * @param {ProxyFormController.LevelOfControl} l The level of control this + * extension has over the proxy settings. + * @private + */ + handleLackOfControl_: function(l) { + var msg; + if (l === ProxyFormController.LevelOfControl.NO_ACCESS) + msg = chrome.i18n.getMessage('errorNoExtensionAccess'); + else if (l === ProxyFormController.LevelOfControl.OTHER_EXTENSION) + msg = chrome.i18n.getMessage('errorOtherExtensionControls'); + this.generateAlert_(msg); + }, + + + /** + * Handle the case in which errors have been generated outside the context + * of this popup. + * + * @private + */ + handleProxyErrors_: function() { + chrome.extension.sendRequest({type: 'getError'}, this.handleProxyErrorHandlerResponse_.bind(this)); + }, + + /** + * Handles response from ProxyErrorHandler + * + * @param {{result: !string}} response The message sent in response to this + * popup's request. + */ + handleProxyErrorHandlerResponse_: function(response) { + + if (response.result !== null) { + var error = JSON.parse(response.result); + + // ignore, sometimes we get temporary tunnel connections failed but proxy is working + if (error.error == "net::ERR_TUNNEL_CONNECTION_FAILED") { + return; + } + + this.generateAlert_(chrome.i18n.getMessage(error.details ? 'errorProxyDetailedError' : 'errorProxyError',[error.error, error.details]),false); + } + } }; @@ -1157,50 +1052,61 @@ function clearErrorDivs() { } function generateAlert(msg, close) { - // delete all existing and opened alerts - var els = document.getElementsByClassName('overlay'); - while (els[0]) { - els[0].classList.remove('active') - } + console.log("generateAlert"); - clearErrorDivs(); - - var success = document.createElement('div'); - success.setAttribute('id', 'proxyFail'); - - if(close == true){ - success.classList.add('overlay'); - } - else{ - success.removeAttribute('hidden', 'hidden'); - success.classList.add('proxyFailMsg'); - } - success.setAttribute('role', 'alert'); - - success.textContent = msg; - - document.getElementById("connectedMsg").innerText = "CONNECTION ERROR"; - document.getElementById("tryAgainMsg").innerText = "TRY AGAIN"; - document.getElementById("imgError").removeAttribute('hidden', 'hidden'); - document.getElementById("dataValue").setAttribute('hidden', 'hidden'); - - document.getElementById("settingsConfig").setAttribute('hidden', 'hidden'); - - // switch visible sections, hiding welcome screen and showing the other where error is shown - document.getElementById("fixed_servers").setAttribute('hidden', 'hidden'); - document.getElementById("system").removeAttribute('hidden', 'hidden'); - - document.getElementById("dataValue").setAttribute('hidden', 'hidden'); - - document.body.appendChild(success); - - setTimeout(function() { success.classList.add('visible'); }, 10); - - setTimeout(function() { - if(close == true){ - success.setAttribute('hidden', 'hidden'); - } - success.classList.remove('overlay'); - }, 4000); + // delete all existing and opened alerts + var els = document.getElementsByClassName('overlay'); + + while (els[0]) { + els[0].classList.remove('active') + } + + clearErrorDivs(); + + var success = document.createElement('div'); + success.setAttribute('id', 'proxyFail'); + + if (close == true) { + success.classList.add('overlay'); + } else { + success.removeAttribute('hidden', 'hidden'); + success.classList.add('proxyFailMsg'); + } + + success.setAttribute('role', 'alert'); + success.textContent = msg; + + // switch visible sections, hiding welcome screen and showing the other where error is shown + if (document.getElementById("imgError") !== null) { + + // Badge the popup icon. + var RED = [255, 0, 0, 255]; + chrome.browserAction.setBadgeBackgroundColor({color: RED}); + chrome.browserAction.setBadgeText({text: 'X'}); + chrome.browserAction.setTitle({ + title: chrome.i18n.getMessage('errorPopupTitle') + }); + + document.getElementById("imgError").removeAttribute('hidden', 'hidden'); + document.getElementById("dataValue").setAttribute('hidden', 'hidden'); + document.getElementById("settingsConfig").setAttribute('hidden', 'hidden'); + document.getElementById("fixed_servers").setAttribute('hidden', 'hidden'); + document.getElementById("system").removeAttribute('hidden', 'hidden'); + document.getElementById("dataValue").setAttribute('hidden', 'hidden'); + document.getElementById("connectedMsg").innerHTML = "CONNECTION ERROR"; + document.getElementById("tryAgainMsg").innerHTML = "TRY AGAIN"; + } + + + document.body.appendChild(success); + + setTimeout(function() { success.classList.add('visible'); }, 10); + + setTimeout(function() { + if (close == true) { + success.setAttribute('hidden', 'hidden'); + } + success.classList.remove('overlay'); + }, 4000); } \ No newline at end of file