Fix global counter issue

The total elements field need async to long to load, so that this value
is NaN by scanning the first url. We check now first of NaN or Null and
get the current value. The browser is waiting until the value is loaded.
This commit is contained in:
Kevin Röbert 2017-09-14 03:39:40 +02:00
parent 986ee20233
commit 47c4882e9b
2 changed files with 203 additions and 191 deletions

View File

@ -1,8 +1,8 @@
/* /*
* ################################################################## * ##################################################################
* # Fetch Rules & Exception from URL # * # Fetch Rules & Exception from URL #
* ################################################################## * ##################################################################
*/ */
var data = []; var data = [];
var providers = []; var providers = [];
var prvKeys = []; var prvKeys = [];
@ -11,24 +11,24 @@ var badges = [];
var badgedStatus; var badgedStatus;
var tabid = 0; var tabid = 0;
var globalCounter; var globalCounter;
var globalURLCounter; var globalurlcounter;
var siteBlockedAlert = browser.extension.getURL ('./siteBlockedAlert.html'); var siteBlockedAlert = browser.extension.getURL ('./siteBlockedAlert.html');
/** /**
* Initialize the JSON provider object keys. * Initialize the JSON provider object keys.
* *
* @param {JSON Object} obj * @param {JSON Object} obj
*/ */
function getKeys(obj){ function getKeys(obj){
for(var key in obj){ for(var key in obj){
prvKeys.push(key); prvKeys.push(key);
} }
}; };
/** /**
* Initialize the providers form the JSON object. * Initialize the providers form the JSON object.
* *
*/ */
function createProviders() function createProviders()
{ {
for(var p = 0; p < prvKeys.length; p++) for(var p = 0; p < prvKeys.length; p++)
@ -54,11 +54,11 @@ function createProviders()
}; };
/** /**
* Convert the external data to JSON Objects and * Convert the external data to JSON Objects and
* call the create provider function. * call the create provider function.
* *
* @param {String} retrievedText - pure data form github * @param {String} retrievedText - pure data form github
*/ */
function toJSON(retrievedText) { function toJSON(retrievedText) {
data = JSON.parse(retrievedText); data = JSON.parse(retrievedText);
getKeys(data.providers); getKeys(data.providers);
@ -66,10 +66,10 @@ function toJSON(retrievedText) {
} }
/** /**
* Load local saved data, if the browser is offline or * Load local saved data, if the browser is offline or
* some other network trouble. * some other network trouble.
* *
*/ */
function loadOldDataFromStore() function loadOldDataFromStore()
{ {
browser.storage.local.get('ClearURLsData', function(data){ browser.storage.local.get('ClearURLsData', function(data){
@ -85,9 +85,9 @@ function loadOldDataFromStore()
} }
/** /**
* Fetch the Rules & Exception github. * Fetch the Rules & Exception github.
* *
*/ */
function fetchFromURL() function fetchFromURL()
{ {
fetch("https://raw.githubusercontent.com/KevinRoebert/ClearUrls/master/data/data.json?flush_cache=true") fetch("https://raw.githubusercontent.com/KevinRoebert/ClearUrls/master/data/data.json?flush_cache=true")
@ -105,7 +105,7 @@ function fetchFromURL()
toJSON(responseText); toJSON(responseText);
} }
else { else {
loadOldDataFromStore(); loadOldDataFromStore();
} }
}); });
}; };
@ -114,16 +114,16 @@ function fetchFromURL()
// ################################################################## // ##################################################################
/* /*
* ################################################################## * ##################################################################
* # Supertyp Provider # * # Supertyp Provider #
* ################################################################## * ##################################################################
*/ */
/** /**
* Declare constructor * Declare constructor
* *
* @param {String} _name Provider name * @param {String} _name Provider name
* @param {boolean} completeProvider Set URL Pattern as rule * @param {boolean} completeProvider Set URL Pattern as rule
*/ */
function Provider(_name,_completeProvider = false){ function Provider(_name,_completeProvider = false){
var name = _name; var name = _name;
var urlPattern; var urlPattern;
@ -136,73 +136,73 @@ function Provider(_name,_completeProvider = false){
} }
/** /**
* Add URL pattern. * Add URL pattern.
* *
* @require urlPatterns as RegExp * @require urlPatterns as RegExp
*/ */
this.setURLPattern = function(urlPatterns) { this.setURLPattern = function(urlPatterns) {
urlPattern = new RegExp(urlPatterns, "mgi"); urlPattern = new RegExp(urlPatterns, "mgi");
}; };
/** /**
* Return if the Provider Request is canceled * Return if the Provider Request is canceled
* @return {Boolean} isCanceled * @return {Boolean} isCanceled
*/ */
this.isCaneling = function() { this.isCaneling = function() {
return canceling; return canceling;
}; };
/** /**
* Check the url is matching the ProviderURL. * Check the url is matching the ProviderURL.
* *
* @return {String} ProviderURL as RegExp * @return {String} ProviderURL as RegExp
*/ */
this.matchURL = function(url) { this.matchURL = function(url) {
return !(this.matchException(url)) && (url.match(urlPattern) != null) && (url.match(urlPattern).length > 0); return !(this.matchException(url)) && (url.match(urlPattern) != null) && (url.match(urlPattern).length > 0);
}; };
/** /**
* Add a rule to the rule array. * Add a rule to the rule array.
* *
* @param String rule RegExp as string * @param String rule RegExp as string
*/ */
this.addRule = function(rule) { this.addRule = function(rule) {
rules.push(rule); rules.push(rule);
}; };
/** /**
* Set the rules for the provider * Set the rules for the provider
* @param String _rules RegEx as string * @param String _rules RegEx as string
*/ */
this.setRules = function(_rules) { this.setRules = function(_rules) {
rules = _rules; rules = _rules;
}; };
/** /**
* Return all rules as an array. * Return all rules as an array.
* *
* @return Array RegExp strings * @return Array RegExp strings
*/ */
this.getRules = function() { this.getRules = function() {
return rules; return rules;
}; };
/** /**
* Add a exception to the exceptions array. * Add a exception to the exceptions array.
* *
* @param String exception RegExp as string * @param String exception RegExp as string
*/ */
this.addException = function(exception) { this.addException = function(exception) {
exceptions.push(exception); exceptions.push(exception);
}; };
/** /**
* Private helper method to check if the url * Private helper method to check if the url
* an exception. * an exception.
* *
* @param {String} url RegExp as string * @param {String} url RegExp as string
* @return {boolean} if matching? true: false * @return {boolean} if matching? true: false
*/ */
this.matchException = function(url) { this.matchException = function(url) {
var result = false; var result = false;
@ -221,13 +221,13 @@ function Provider(_name,_completeProvider = false){
// ################################################################## // ##################################################################
/** /**
* Helper function which remove the tracking fields * Helper function which remove the tracking fields
* for each provider given as parameter. * for each provider given as parameter.
* *
* @param {Provider} provider Provider-Object * @param {Provider} provider Provider-Object
* @param {webRequest} request webRequest-Object * @param {webRequest} request webRequest-Object
* @return {Array} Array with changes and url fields * @return {Array} Array with changes and url fields
*/ */
function removeFieldsFormURL(provider, request) function removeFieldsFormURL(provider, request)
{ {
var url = request.url; var url = request.url;
@ -289,10 +289,10 @@ function removeFieldsFormURL(provider, request)
}; };
/** /**
* Return the number of parameters query strings. * Return the number of parameters query strings.
* @param {String} url URL as String * @param {String} url URL as String
* @return {int} Number of Parameters * @return {int} Number of Parameters
*/ */
function countFields(url) function countFields(url)
{ {
var matches = (url.match(/[^\/|\?|&]+=[^\/|\?|&]+/gi) || []); var matches = (url.match(/[^\/|\?|&]+=[^\/|\?|&]+/gi) || []);
@ -302,100 +302,114 @@ function countFields(url)
} }
/** /**
* Function which called from the webRequest to * Function which called from the webRequest to
* remove the tracking fields from the url. * remove the tracking fields from the url.
* *
* @param {webRequest} request webRequest-Object * @param {webRequest} request webRequest-Object
* @return {Array} redirectUrl or none * @return {Array} redirectUrl or none
*/ */
function clearUrl(request) function clearUrl(request)
{ {
var URLbeforeReplaceCount = countFields(request.url); if(globalurlcounter === null || typeof(globalurlcounter) == "undefined")
//Add Fields form Request to global url counter {
globalURLCounter += URLbeforeReplaceCount; /**
browser.storage.local.set({"globalURLCounter": globalURLCounter}); * Get the globalURLCounter value from the browser storage
* @param {(data){} Return value form browser.storage.local.get
browser.storage.local.get('globalStatus', clear); */
browser.storage.local.get('globalurlcounter', function(data){
function clear(data){ if(data.globalurlcounter){
globalStatus = data.globalStatus; globalurlcounter = data.globalurlcounter;
}
if(globalStatus == null){ else {
globalStatus = true; globalurlcounter = 0;
}
}
if(globalStatus){
var result = {
"changes": false,
"url": ""
};
/*
* Call for every provider the removeFieldsFormURL method.
*/
for (var i = 0; i < providers.length; i++) {
result = removeFieldsFormURL(providers[i], request);
/*
* Cancel the Request and redirect to the site blocked alert page,
* to inform the user about the full url blocking.
*/
if(result["cancel"]){
return {
redirectUrl: siteBlockedAlert
};
} }
return clearUrl(request);
});
}
else if(globalCounter === null || typeof(globalCounter) == "undefined") {
/**
* Get the globalCounter value from the browser storage
* @param {(data){} Return value form browser.storage.local.get
*/
browser.storage.local.get('globalCounter', function(data){
if(data.globalCounter){
globalCounter = data.globalCounter;
}
else {
globalCounter = 0;
}
return clearUrl(request);
});
}
else {
var URLbeforeReplaceCount = countFields(request.url);
//Add Fields form Request to global url counter
globalurlcounter += URLbeforeReplaceCount;
browser.storage.local.set({"globalurlcounter": globalurlcounter});
browser.storage.local.get('globalStatus', clear);
function clear(data){
globalStatus = data.globalStatus;
if(globalStatus == null){
globalStatus = true;
}
}
if(globalStatus){
var result = {
"changes": false,
"url": ""
};
/* /*
* Ensure that the function go not into * Call for every provider the removeFieldsFormURL method.
* an loop. */
*/ for (var i = 0; i < providers.length; i++) {
if(result["changes"]){ result = removeFieldsFormURL(providers[i], request);
return {
redirectUrl: result["url"] /*
}; * Cancel the Request and redirect to the site blocked alert page,
* to inform the user about the full url blocking.
*/
if(result["cancel"]){
return {
redirectUrl: siteBlockedAlert
};
}
/*
* Ensure that the function go not into
* an loop.
*/
if(result["changes"]){
return {
redirectUrl: result["url"]
};
}
} }
} }
} }
}; };
/** /**
* Call by each tab is closed. * Call by each tab is closed.
*/ */
function handleRemoved(tabId, removeInfo) { function handleRemoved(tabId, removeInfo) {
delete badges[tabId]; delete badges[tabId];
} }
/** /**
* Get the globalCounter value from the browser storage * Get the badged status from the browser storage and put the value
* @param {(data){} Return value form browser.storage.local.get * into a local variable.
*/ *
function setGlobalCounter() { */
browser.storage.local.get('globalCounter', function(data){
if(data.globalCounter){
globalCounter = data.globalCounter;
}
else {
globalCounter = 0;
}
});
browser.storage.local.get('globalURLCounter', function(data){
if(data.globalURLCounter){
globalURLCounter = data.globalURLCounter;
}
else {
globalURLCounter = 0;
}
});
}
/**
* Get the badged status from the browser storage and put the value
* into a local variable.
*
*/
function setBadgedStatus() { function setBadgedStatus() {
browser.storage.local.get('badgedStatus', function(data) { browser.storage.local.get('badgedStatus', function(data) {
if(data.badgedStatus) { if(data.badgedStatus) {
@ -414,42 +428,40 @@ function setBadgedStatus() {
} }
/** /**
* Call the fetch, counter and status functions * Call the fetch, counter and status functions
*/ */
fetchFromURL(); fetchFromURL();
setBadgedStatus(); setBadgedStatus();
setGlobalCounter();
/** /**
* Call by each change in the browser storage. * Call by each change in the browser storage.
*/ */
browser.storage.onChanged.addListener(setGlobalCounter);
browser.storage.onChanged.addListener(setBadgedStatus); browser.storage.onChanged.addListener(setBadgedStatus);
/** /**
* Call by each tab is closed. * Call by each tab is closed.
*/ */
browser.tabs.onRemoved.addListener(handleRemoved); browser.tabs.onRemoved.addListener(handleRemoved);
/** /**
* Call by each tab change to set the actual tab id * Call by each tab change to set the actual tab id
*/ */
function handleActivated(activeInfo) { function handleActivated(activeInfo) {
tabid = activeInfo.tabId; tabid = activeInfo.tabId;
} }
/** /**
* Call by each tab change. * Call by each tab change.
*/ */
browser.tabs.onActivated.addListener(handleActivated); browser.tabs.onActivated.addListener(handleActivated);
/** /**
* Call by each Request and checking the url. * Call by each Request and checking the url.
* *
* @type {Array} * @type {Array}
*/ */
browser.webRequest.onBeforeRequest.addListener( browser.webRequest.onBeforeRequest.addListener(
clearUrl, clearUrl,
{urls: ["<all_urls>"]}, {urls: ["<all_urls>"]},
["blocking"] ["blocking"]
); );

View File

@ -21,7 +21,7 @@ function changeStatistics(){
var elTotal = $('#statistics_total_elements'); var elTotal = $('#statistics_total_elements');
var globalPercentage = 0; var globalPercentage = 0;
var globalCounter; var globalCounter;
var globalURLCounter; var globalurlcounter;
browser.storage.local.get('globalCounter', function(data){ browser.storage.local.get('globalCounter', function(data){
if(data.globalCounter){ if(data.globalCounter){
@ -34,22 +34,22 @@ function changeStatistics(){
element.text(globalCounter.toLocaleString()); element.text(globalCounter.toLocaleString());
}); });
browser.storage.local.get('globalURLCounter', function(data){ browser.storage.local.get('globalurlcounter', function(data){
if(data.globalURLCounter){ if(data.globalurlcounter){
globalURLCounter = data.globalURLCounter; globalurlcounter = data.globalurlcounter;
} }
else { else {
globalURLCounter = 0; globalurlcounter = 0;
} }
globalPercentage = ((globalCounter/globalURLCounter)*100).toFixed(3); globalPercentage = ((globalCounter/globalurlcounter)*100).toFixed(3);
if(isNaN(Number(globalPercentage))) globalPercentage = 0; if(isNaN(Number(globalPercentage))) globalPercentage = 0;
elGlobalPercentage.text(globalPercentage+"%"); elGlobalPercentage.text(globalPercentage+"%");
elProgressbar_blocked.css('width', globalPercentage+'%'); elProgressbar_blocked.css('width', globalPercentage+'%');
elProgressbar_non_blocked.css('width', (100-globalPercentage)+'%'); elProgressbar_non_blocked.css('width', (100-globalPercentage)+'%');
elTotal.text(globalURLCounter); elTotal.text(globalurlcounter.toLocaleString());
}); });
}; };
@ -122,7 +122,7 @@ function setTabcounter() {
*/ */
function resetGlobalCounter(){ function resetGlobalCounter(){
browser.storage.local.set({"globalCounter": 0}); browser.storage.local.set({"globalCounter": 0});
browser.storage.local.set({"globalURLCounter": 0}); browser.storage.local.set({"globalurlcounter": 0});
}; };
$(document).ready(function(){ $(document).ready(function(){