Restyle, scope vars/names out of window

This commit is contained in:
Ilya Ig. Petrov 2016-11-20 04:58:49 -08:00
parent 05c6deadf8
commit 1ef480acd1
4 changed files with 497 additions and 483 deletions

View File

@ -13,8 +13,9 @@
use chrome.runtime.getBackgroundPage(..), use chrome.runtime.getBackgroundPage(..),
extension.getBackgroundPage is deprecated extension.getBackgroundPage is deprecated
*/ */
{ // Private namespace starts.
window.antiCensorRu = { window.antiCensorRu = {
version: chrome.runtime.getManifest().version, version: chrome.runtime.getManifest().version,
@ -165,8 +166,9 @@ window.antiCensorRu = {
let nextUpdateMoment = this.lastPacUpdateStamp + this._pacUpdatePeriodInMinutes*60*1000; let nextUpdateMoment = this.lastPacUpdateStamp + this._pacUpdatePeriodInMinutes*60*1000;
const now = Date.now(); const now = Date.now();
if (nextUpdateMoment < now) if (nextUpdateMoment < now) {
nextUpdateMoment = now; nextUpdateMoment = now;
}
console.log( 'Next PAC update is scheduled on', new Date(nextUpdateMoment).toLocaleString('ru-RU') ); console.log( 'Next PAC update is scheduled on', new Date(nextUpdateMoment).toLocaleString('ru-RU') );
@ -179,6 +181,7 @@ window.antiCensorRu = {
); );
return nextUpdateMoment === now; // ifAlarmTriggered. May be changed in the future. return nextUpdateMoment === now; // ifAlarmTriggered. May be changed in the future.
}, },
installPac(key, cb) { installPac(key, cb) {
@ -217,10 +220,10 @@ window.antiCensorRu = {
); );
} }
}; };
// ON EACH LAUNCH, STARTUP, RELOAD, UPDATE, ENABLE // ON EACH LAUNCH, STARTUP, RELOAD, UPDATE, ENABLE
chrome.storage.local.get(null, (oldStorage) => { chrome.storage.local.get(null, (oldStorage) => {
console.log('Init on storage:', oldStorage); console.log('Init on storage:', oldStorage);
antiCensorRu.ifFirstInstall = Object.keys(oldStorage).length === 0; antiCensorRu.ifFirstInstall = Object.keys(oldStorage).length === 0;
@ -239,6 +242,7 @@ chrome.storage.local.get(null, (oldStorage) => {
console.log('Periodic PAC update triggered:', new Date().toLocaleString('ru-RU')); console.log('Periodic PAC update triggered:', new Date().toLocaleString('ru-RU'));
antiCensorRu.syncWithPacProvider(/* Swallows errors. */); antiCensorRu.syncWithPacProvider(/* Swallows errors. */);
} }
} }
); );
console.log('Alarm listener installed. We won\'t miss any PAC update.'); console.log('Alarm listener installed. We won\'t miss any PAC update.');
@ -258,6 +262,11 @@ chrome.storage.local.get(null, (oldStorage) => {
if (!antiCensorRu.pacProvider) { if (!antiCensorRu.pacProvider) {
return console.log('No PAC provider set. Do nothing.'); return console.log('No PAC provider set. Do nothing.');
/*
In case of UPDATE:
1. new providers will still be shown.
2. new version won't be pushed to storage
*/
} }
/* /*
@ -278,10 +287,7 @@ chrome.storage.local.get(null, (oldStorage) => {
// UPDATE & MIGRATION // UPDATE & MIGRATION
console.log('Extension updated.'); console.log('Extension updated.');
if (!ifAlarmTriggered) { if (!ifAlarmTriggered) {
updatePacProxyIps( antiCensorRu.pushToStorage(/* Swallows errors. */);
antiCensorRu.pacProvider,
(ipsError) => ipsError ? console.error('Error updating IPs:', ipsError) : antiCensorRu.pushToStorage(/* Swallows errors. */)
);
} }
/* /*
@ -294,9 +300,9 @@ chrome.storage.local.get(null, (oldStorage) => {
* Changed storage.ifNotInstalled to storage.ifFirstInstall * Changed storage.ifNotInstalled to storage.ifFirstInstall
* Added storage.lastPacUpdateStamp * Added storage.lastPacUpdateStamp
**/ **/
}); });
function asyncLogGroup(...args) { function asyncLogGroup(...args) {
const cb = args.pop() || (() => {}); const cb = args.pop() || (() => {});
console.group.apply(console, args); console.group.apply(console, args);
@ -307,9 +313,9 @@ function asyncLogGroup(...args) {
return cb.apply(this, cbArgs); return cb.apply(this, cbArgs);
} }
} }
function checkChromeError(betterStack) { function checkChromeError(betterStack) {
// Chrome API calls your cb in a context different from the point of API method invokation. // Chrome API calls your cb in a context different from the point of API method invokation.
const err = chrome.runtime.lastError || chrome.extension.lastError || null; const err = chrome.runtime.lastError || chrome.extension.lastError || null;
@ -322,9 +328,9 @@ function checkChromeError(betterStack) {
} }
return err; return err;
} }
function chromified(cb, ...replaceArgs) { function chromified(cb, ...replaceArgs) {
const stack = (new Error()).stack; const stack = (new Error()).stack;
// Take error first callback and covert it to chrome api callback. // Take error first callback and covert it to chrome api callback.
@ -338,9 +344,9 @@ function chromified(cb, ...replaceArgs) {
}; };
} }
function httpGet(url, cb) { function httpGet(url, cb) {
const start = Date.now(); const start = Date.now();
return fetch(url).then( return fetch(url).then(
@ -365,9 +371,9 @@ function httpGet(url, cb) {
} }
); );
} }
function getOneDnsRecord(args, cb) { function getOneDnsRecord(args, cb) {
// args: { host:..., type: 'AAAA', filter: ['AAAA'] } // args: { host:..., type: 'AAAA', filter: ['AAAA'] }
if (!(args.host && args.type && cb)) { if (!(args.host && args.type && cb)) {
@ -420,9 +426,9 @@ function getOneDnsRecord(args, cb) {
return cb( err, res ); return cb( err, res );
} }
); );
}; };
function getDnsRecords(args, cb) { function getDnsRecords(args, cb) {
/* /*
Example of input: Example of input:
@ -463,11 +469,11 @@ function getDnsRecords(args, cb) {
) )
); );
Promise.all(promises).then( (answers) => cb( null, [].concat.apply([], answers) ), cb ); Promise.all(promises).then( (answers) => cb( null, [].concat.apply([], answers) ), cb );
} }
const getIpDnsRecords = (host, cb) => getDnsRecords({ host: host }, cb); const getIpDnsRecords = (host, cb) => getDnsRecords({ host: host }, cb);
function updatePacProxyIps(provider, cb) { function updatePacProxyIps(provider, cb) {
cb = asyncLogGroup('Getting IP for '+ provider.proxyHosts.join(', ') +'...', cb); cb = asyncLogGroup('Getting IP for '+ provider.proxyHosts.join(', ') +'...', cb);
let failure = { let failure = {
@ -495,9 +501,9 @@ function updatePacProxyIps(provider, cb) {
} }
) )
); );
} }
function setPacScriptFromProvider(provider, cb) { function setPacScriptFromProvider(provider, cb) {
cb = asyncLogGroup('Getting pac script from provider...', provider.pacUrl, cb); cb = asyncLogGroup('Getting pac script from provider...', provider.pacUrl, cb);
@ -525,6 +531,8 @@ function setPacScriptFromProvider(provider, cb) {
} }
); );
}
} }
window.addEventListener('error', (err) => { window.addEventListener('error', (err) => {

View File

@ -18,9 +18,9 @@ window.chrome.browserAction.setBadgeBackgroundColor({
window.tabWithError2ip = {}; // For errors only: Error? -> Check this IP! window.tabWithError2ip = {}; // For errors only: Error? -> Check this IP!
+function() { {
var _tabCallbacks = {}; const _tabCallbacks = {};
function afterTabUpdated(tabId, cb) { function afterTabUpdated(tabId, cb) {
if (_tabCallbacks[tabId]) if (_tabCallbacks[tabId])
@ -42,7 +42,7 @@ window.tabWithError2ip = {}; // For errors only: Error? -> Check this IP!
} }
chrome.webRequest.onErrorOccurred.addListener( chrome.webRequest.onErrorOccurred.addListener(
requestDetails => (requestDetails) =>
isInsideTabWithIp(requestDetails) && isInsideTabWithIp(requestDetails) &&
( (
isProxiedAndInformed(requestDetails) || requestDetails.type === 'main_frame' && ( window.tabWithError2ip[requestDetails.tabId] = requestDetails.ip ) isProxiedAndInformed(requestDetails) || requestDetails.type === 'main_frame' && ( window.tabWithError2ip[requestDetails.tabId] = requestDetails.ip )
@ -50,9 +50,9 @@ window.tabWithError2ip = {}; // For errors only: Error? -> Check this IP!
{ urls: ['<all_urls>'] } { urls: ['<all_urls>'] }
); );
chrome.tabs.onRemoved.addListener( tabId => { onTabUpdate(tabId); delete window.tabWithError2ip[tabId] } ); chrome.tabs.onRemoved.addListener( (tabId) => { onTabUpdate(tabId); delete window.tabWithError2ip[tabId] } );
var previousUpdateTitleFinished = Promise.resolve(); let previousUpdateTitleFinished = Promise.resolve();
function isProxiedAndInformed(requestDetails) { function isProxiedAndInformed(requestDetails) {
@ -62,12 +62,12 @@ window.tabWithError2ip = {}; // For errors only: Error? -> Check this IP!
return false; return false;
} }
var ifMainFrame = requestDetails.type === 'main_frame'; const ifMainFrame = requestDetails.type === 'main_frame';
previousUpdateTitleFinished = previousUpdateTitleFinished.then( previousUpdateTitleFinished = previousUpdateTitleFinished.then(
() => new Promise( () => new Promise(
resolve => { (resolve) => {
var cb = () => updateTitle( requestDetails, resolve ); const cb = () => updateTitle( requestDetails, resolve );
return ifMainFrame ? afterTabUpdated(requestDetails.tabId, cb) : cb(); return ifMainFrame ? afterTabUpdated(requestDetails.tabId, cb) : cb();
} }
) )
@ -79,15 +79,16 @@ window.tabWithError2ip = {}; // For errors only: Error? -> Check this IP!
chrome.browserAction.getTitle( chrome.browserAction.getTitle(
{ tabId: requestDetails.tabId }, { tabId: requestDetails.tabId },
title => { (title) => {
var ifTitleSetAlready = /\n/.test(title);
var proxyHost = window.antiCensorRu.pacProvider.proxyIps[ requestDetails.ip ];
var hostname = new URL( requestDetails.url ).hostname; const ifTitleSetAlready = /\n/.test(title);
const proxyHost = window.antiCensorRu.pacProvider.proxyIps[ requestDetails.ip ];
var ifShouldUpdateTitle = false; const hostname = new URL( requestDetails.url ).hostname;
var indent = ' ';
var proxyTitle = 'Прокси:'; let ifShouldUpdateTitle = false;
const indent = ' ';
const proxyTitle = 'Прокси:';
if (!ifTitleSetAlready) { if (!ifTitleSetAlready) {
title = 'Разблокированы:\n'+ indent + hostname +'\n'+ proxyTitle +'\n'+ indent + proxyHost; title = 'Разблокированы:\n'+ indent + hostname +'\n'+ proxyTitle +'\n'+ indent + proxyHost;
@ -98,7 +99,8 @@ window.tabWithError2ip = {}; // For errors only: Error? -> Check this IP!
text: ifMainFrame ? '1' : '%1' text: ifMainFrame ? '1' : '%1'
}); });
} else { }
else {
const hostsProxiesPair = title.split(proxyTitle); const hostsProxiesPair = title.split(proxyTitle);
if (hostsProxiesPair[1].indexOf(proxyHost) === -1) { if (hostsProxiesPair[1].indexOf(proxyHost) === -1) {
@ -110,10 +112,11 @@ window.tabWithError2ip = {}; // For errors only: Error? -> Check this IP!
title = title.replace(proxyTitle, indent + hostname +'\n'+ proxyTitle); title = title.replace(proxyTitle, indent + hostname +'\n'+ proxyTitle);
ifShouldUpdateTitle = true; ifShouldUpdateTitle = true;
var _cb = cb; const _cb = cb;
cb = () => chrome.browserAction.getBadgeText( cb = () => chrome.browserAction.getBadgeText(
{tabId: requestDetails.tabId}, {tabId: requestDetails.tabId},
result => { (result) => {
chrome.browserAction.setBadgeText( chrome.browserAction.setBadgeText(
{ {
tabId: requestDetails.tabId, tabId: requestDetails.tabId,
@ -121,27 +124,30 @@ window.tabWithError2ip = {}; // For errors only: Error? -> Check this IP!
} }
); );
return _cb(); return _cb();
} }
); );
} }
} }
if (ifShouldUpdateTitle) if (ifShouldUpdateTitle) {
chrome.browserAction.setTitle({ chrome.browserAction.setTitle({
title: title, title: title,
tabId: requestDetails.tabId tabId: requestDetails.tabId
}); });
}
return cb(); return cb();
} }
); );
} }
} }
chrome.webRequest.onResponseStarted.addListener( chrome.webRequest.onResponseStarted.addListener(
requestDetails => isInsideTabWithIp(requestDetails) && isProxiedAndInformed(requestDetails), (requestDetails) => isInsideTabWithIp(requestDetails) && isProxiedAndInformed(requestDetails),
{ urls: ['<all_urls>'] } { urls: ['<all_urls>'] }
); );
}(); }

View File

@ -5,7 +5,7 @@
const createMenuLinkEntry = (title, tab2url) => chrome.contextMenus.create({ const createMenuLinkEntry = (title, tab2url) => chrome.contextMenus.create({
title: title, title: title,
contexts: ['browser_action'], contexts: ['browser_action'],
onclick: (menuInfo, tab) => Promise.resolve( tab2url( tab ) ).then( url => chrome.tabs.create({url: url}) ) onclick: (menuInfo, tab) => Promise.resolve( tab2url( tab ) ).then( (url) => chrome.tabs.create({url: url}) )
}); });
createMenuLinkEntry( 'Сайт доступен из-за границы? Is up?', (tab) => 'http://isup.me/'+ new URL(tab.url).hostname ); createMenuLinkEntry( 'Сайт доступен из-за границы? Is up?', (tab) => 'http://isup.me/'+ new URL(tab.url).hostname );

View File

@ -1,7 +1,7 @@
{ {
"manifest_version": 2, "manifest_version": 2,
"name": "Обход блокировок Рунета", "name": "Обход блокировок Рунета 0.15",
"description": "Аргументы против цензуры: https://git.io/vEkI9", "description": "Аргументы против цензуры: https://git.io/vEkI9",
"version": "0.0.0.15", "version": "0.0.0.15",
"icons": { "icons": {