Promisifed syncWithPac, added error reports

This commit is contained in:
Ilya Ig. Petrov 2016-01-27 01:05:21 +05:00
parent 6c2b2eba30
commit 7c4e78efac
3 changed files with 96 additions and 25 deletions

View File

@ -25,12 +25,14 @@
.link-button, .link-button:visited { .link-button, .link-button:visited {
color: #0000EE; color: #0000EE;
text-decoration: none; text-decoration: none;
display: none;
} }
.link-button:hover { .link-button:hover {
text-decoration: underline; text-decoration: underline;
} }
input:checked ~ .link-button { .checked-radio-panel {
display: none;
}
input:checked ~ .checked-radio-panel {
display: inline; display: inline;
} }
.button-panel { .button-panel {

View File

@ -5,8 +5,12 @@ renderPage();
function renderPage() { function renderPage() {
console.log('Rendering started.'); console.log('Rendering started.');
function getStatus() {
return document.querySelector('#status');
}
function setStatusTo(msg) { function setStatusTo(msg) {
var status = document.querySelector('#status'); var status = getStatus();
if (msg) { if (msg) {
status.classList.remove('off'); status.classList.remove('off');
status.innerHTML = msg; status.innerHTML = msg;
@ -21,7 +25,7 @@ function renderPage() {
// SET DATE // SET DATE
function setDate() { function setDate() {
var dateForUser = '...'; var dateForUser = 'никогда';
if( antiCensorRu.lastPacUpdateStamp ) { if( antiCensorRu.lastPacUpdateStamp ) {
var diff = Date.now() - antiCensorRu.lastPacUpdateStamp; var diff = Date.now() - antiCensorRu.lastPacUpdateStamp;
var units = ' мс'; var units = ' мс';
@ -76,7 +80,7 @@ function renderPage() {
var _firstChild = ul.firstChild; var _firstChild = ul.firstChild;
for( var providerKey of Object.keys(antiCensorRu.pacProviders) ) { for( var providerKey of Object.keys(antiCensorRu.pacProviders) ) {
var li = document.createElement('li'); var li = document.createElement('li');
li.innerHTML = '<input type="radio" name="pacProvider" id="'+providerKey+'"> <label for="'+providerKey+'">'+providerKey+'</label> <a href class="link-button">[обновить]</a>'; li.innerHTML = '<input type="radio" name="pacProvider" id="'+providerKey+'"> <label for="'+providerKey+'">'+providerKey+'</label> <a href class="link-button checked-radio-panel">[обновить]</a>';
li.querySelector('.link-button').onclick = () => {triggerChosenProvider(); return false;}; li.querySelector('.link-button').onclick = () => {triggerChosenProvider(); return false;};
ul.insertBefore( li, _firstChild ); ul.insertBefore( li, _firstChild );
} }
@ -97,7 +101,38 @@ function renderPage() {
enableDisableInputs(); enableDisableInputs();
setStatusTo('Установка...'); setStatusTo('Установка...');
antiCensorRu.installPac(pacKey, () => { antiCensorRu.installPac(pacKey, err => {
if (err) {
var ifNotCritical = err.clarification && err.clarification.ifNotCritical;
var message = '';
var clarification = err.clarification;
do {
message = message +' '+ (clarification && clarification.message || err.message || '');
clarification = clarification.prev;
} while( clarification && clarification.prev );
message = message.trim();
message = '<span style="font-size: 0.9em; color: darkred">'+ message +'</span>';
var label = ifNotCritical ? 'Некритичная ошибка.' : 'Ошибка!';
label = '<span style="color:red">'+ label +'</span>';
setStatusTo(
label +'<br/>'+ message +' <a href class="link-button">[Ещё подробнее]</a>'
);
var btn = getStatus().querySelector('.link-button');
btn.onclick = function() {
var div = document.createElement('div');
div.innerHTML = '\
Более подробную информацию можно узнать из логов фоновой страницы:<br/>\
<a href class="ext">chrome://extensions</a> Это расширение Отладка страниц: фоновая страница Console (DevTools)';
getStatus().replaceChild(div, this);
div.querySelector('.ext').onclick = () => {
chrome.tabs.create({ url: "chrome://extensions" });
return false;
}
return false;
};
} else
setStatusTo('PAC-скрипт установлен.'); setStatusTo('PAC-скрипт установлен.');
enableDisableInputs(); enableDisableInputs();
}); });

View File

@ -80,19 +80,34 @@ window.antiCensorRu = {
lastPacUpdateStamp: 0, lastPacUpdateStamp: 0,
syncWithPacProvider(cb) { syncWithPacProvider(cb) {
setPacScriptFromProvider( var cb = cb || (() => {});
var pacSetPromise = new Promise(
(resolve, reject) => setPacScriptFromProvider(
this.pacProvider, this.pacProvider,
err => { (err, res) => {
if (!err) if (err)
return reject(err);
this.lastPacUpdateStamp = Date.now(); this.lastPacUpdateStamp = Date.now();
updatePacProxyIps(
this.pacProvider,
() => {
this.ifFirstInstall = false; this.ifFirstInstall = false;
this.pushToStorage(cb) return resolve(res);
} }
)}
) )
);
return updatePacProxyIps(
this.pacProvider,
ipsError => {
if (ipsError && ipsError.clarification)
ipsError.clarification.ifNotCritical = true;
pacSetPromise.then(
res => this.pushToStorage(
pushError => pushError ? cb(pushError) : cb(ipsError, res)
),
err => cb(err)
)
}
);
}, },
_periodicUpdateAlarmReason: 'Периодичное обновление PAC-скрипта Антизапрет', _periodicUpdateAlarmReason: 'Периодичное обновление PAC-скрипта Антизапрет',
@ -191,18 +206,24 @@ function asyncLogGroup() {
} }
} }
function ifSuccessfulCode(status) {
return status >= 200 && status < 300 || status === 304;
}
function httpGet(url, cb) { function httpGet(url, cb) {
var cb = cb || (() => {}); var cb = cb || (() => {});
var req = new XMLHttpRequest(); var req = new XMLHttpRequest();
var ifAsync = true; var ifAsync = true;
req.open('GET', url, ifAsync); req.open('GET', url, ifAsync);
req.onload = event => { req.onload = event => {
if (req.status !== 200) if (!ifSuccessfulCode(req.status)) {
return cb(event); req.clarification = {message: 'Получен ответ с неудачным HTTP-кодом '+req.status+ '.'};
return cb(req);
}
console.log('GETed with success.'); console.log('GETed with success.');
return cb(null, req.responseText) return cb(null, req.responseText)
}; };
req.onerror = cb; req.onerror = event => { event.clarification = {message: 'Что-то не так с сетью, проверьте соединение.'}; return cb(event); };
req.send(); req.send();
} }
@ -212,6 +233,10 @@ function updatePacProxyIps(provider, cb) {
return cb(null, null); return cb(null, null);
} }
var cb = asyncLogGroup('Getting IP for '+ provider.proxyHosts.join(', ') +'...', cb); var cb = asyncLogGroup('Getting IP for '+ provider.proxyHosts.join(', ') +'...', cb);
var failure = {
clarification: {message:'Не удалось получить один или несколько IP адресов для прокси-серверов. Иконка для уведомления об обходе блокировок может не отображаться.'},
errors: {}
};
var i = 0; var i = 0;
for (var proxyHost of provider.proxyHosts) { for (var proxyHost of provider.proxyHosts) {
httpGet( httpGet(
@ -220,9 +245,13 @@ function updatePacProxyIps(provider, cb) {
if (!err) { if (!err) {
provider.proxyIps = provider.proxyIps || {}; provider.proxyIps = provider.proxyIps || {};
provider.proxyIps[ JSON.parse(res).answer[0].rdata ] = true; provider.proxyIps[ JSON.parse(res).answer[0].rdata ] = true;
} else
failure.errors[proxyHost] = err;
if ( ++i == provider.proxyHosts.length ) {
failure = Object.keys(failure.errors).length ? failure : null;
return cb(failure, provider.proxyIps);
} }
if ( ++i == provider.proxyHosts.length )
return cb(err, 'Complete.');
} }
); );
} }
@ -234,8 +263,13 @@ function setPacScriptFromProvider(provider, cb) {
httpGet( httpGet(
provider.pacUrl, provider.pacUrl,
(err, res) => { (err, res) => {
if (err) if (err) {
err.clarification = {
message: 'Не удалось скачать PAC-скрипт с адреса: ' +provider.pacUrl+ '.',
prev: err.clarification
};
return cb(err); return cb(err);
}
console.log('Clearing chrome proxy settings...'); console.log('Clearing chrome proxy settings...');
return chrome.proxy.settings.clear({}, () => { return chrome.proxy.settings.clear({}, () => {
var config = { var config = {