convert frontend javascript into revealing module pattern

This commit is contained in:
Jakob Schrettenbrunner 2017-01-27 00:44:28 +01:00
parent 344e3b4330
commit 0c1559c922
4 changed files with 301 additions and 245 deletions

View File

@ -17,60 +17,75 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE. // SOFTWARE.
$(document).ready(function () {
$('#close_reload').click(function () {
location.reload();
});
$('#do_2fa').submit(function (event) {
event.preventDefault();
$.ajax({ var TwoFactorModal = (function () {
type: 'PUT',
url: Router.route('account.security.totp'), function bindListeners() {
headers: { $(document).ready(function () {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content'), $('#close_reload').click(function () {
} location.reload();
}).done(function (data) { });
var image = new Image(); $('#do_2fa').submit(function (event) {
image.src = data.qrImage; event.preventDefault();
$(image).load(function () {
$('#hide_img_load').slideUp(function () { $.ajax({
$('#qr_image_insert').attr('src', image.src).slideDown(); type: 'PUT',
url: Router.route('account.security.totp'),
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content'),
}
}).done(function (data) {
var image = new Image();
image.src = data.qrImage;
$(image).load(function () {
$('#hide_img_load').slideUp(function () {
$('#qr_image_insert').attr('src', image.src).slideDown();
});
});
$('#2fa_secret_insert').html(data.secret);
$('#open2fa').modal('show');
}).fail(function (jqXHR) {
alert('An error occured while attempting to load the 2FA setup modal. Please try again.');
console.error(jqXHR);
});
});
$('#2fa_token_verify').submit(function (event) {
event.preventDefault();
$('#submit_action').html('<i class="fa fa-spinner fa-spin"></i> Submit').addClass('disabled');
$.ajax({
type: 'POST',
url: Router.route('account.security.totp'),
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content'),
},
data: {
token: $('#2fa_token').val()
}
}).done(function (data) {
$('#notice_box_2fa').hide();
if (data === 'true') {
$('#notice_box_2fa').html('<div class="alert alert-success">2-Factor Authentication has been enabled on your account. Press \'Close\' below to reload the page.</div>').slideDown();
} else {
$('#notice_box_2fa').html('<div class="alert alert-danger">The token provided was invalid.</div>').slideDown();
}
}).fail(function (jqXHR) {
$('#notice_box_2fa').html('<div class="alert alert-danger">There was an error while attempting to enable 2-Factor Authentication on this account.</div>').slideDown();
console.error(jqXHR);
}).always(function () {
$('#submit_action').html('Submit').removeClass('disabled');
}); });
}); });
$('#2fa_secret_insert').html(data.secret);
$('#open2fa').modal('show');
}).fail(function (jqXHR) {
alert('An error occured while attempting to load the 2FA setup modal. Please try again.');
console.error(jqXHR);
}); });
}
}); return {
$('#2fa_token_verify').submit(function (event) { init: function () {
event.preventDefault(); bindListeners();
$('#submit_action').html('<i class="fa fa-spinner fa-spin"></i> Submit').addClass('disabled'); }
}
$.ajax({
type: 'POST',
url: Router.route('account.security.totp'),
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content'),
},
data: {
token: $('#2fa_token').val()
}
}).done(function (data) {
$('#notice_box_2fa').hide();
if (data === 'true') {
$('#notice_box_2fa').html('<div class="alert alert-success">2-Factor Authentication has been enabled on your account. Press \'Close\' below to reload the page.</div>').slideDown();
} else {
$('#notice_box_2fa').html('<div class="alert alert-danger">The token provided was invalid.</div>').slideDown();
}
}).fail(function (jqXHR) {
$('#notice_box_2fa').html('<div class="alert alert-danger">There was an error while attempting to enable 2-Factor Authentication on this account.</div>').slideDown();
console.error(jqXHR);
}).always(function () {
$('#submit_action').html('Submit').removeClass('disabled');
});
});
}); });
TwoFactorModal.init();

View File

@ -17,79 +17,94 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE. // SOFTWARE.
(function initSocket() {
if (typeof $.notifyDefaults !== 'function') { var Server = (function () {
console.error('Notify does not appear to be loaded.');
return; function initSocket() {
if (typeof $.notifyDefaults !== 'function') {
console.error('Notify does not appear to be loaded.');
return;
}
if (typeof io !== 'function') {
console.error('Socket.io is reqired to use this panel.');
return;
}
$.notifyDefaults({
placement: {
from: 'bottom',
align: 'right'
},
newest_on_top: true,
delay: 2000,
animate: {
enter: 'animated zoomInDown',
exit: 'animated zoomOutDown'
}
});
var notifySocketError = false;
window.Socket = io(Pterodactyl.node.scheme + '://' + Pterodactyl.node.fqdn + ':' + Pterodactyl.node.daemonListen + '/ws/' + Pterodactyl.server.uuid, {
'query': 'token=' + Pterodactyl.server.daemonSecret,
});
Socket.io.on('connect_error', function (err) {
if(typeof notifySocketError !== 'object') {
notifySocketError = $.notify({
message: 'There was an error attempting to establish a WebSocket connection to the Daemon. This panel will not work as expected.<br /><br />' + err,
}, {
type: 'danger',
delay: 0
});
}
});
// Connected to Socket Successfully
Socket.on('connect', function () {
if (notifySocketError !== false) {
notifySocketError.close();
notifySocketError = false;
}
});
Socket.on('initial status', function (data) {
setStatusIcon(data.status);
});
Socket.on('status', function (data) {
setStatusIcon(data.status);
});
} }
if (typeof io !== 'function') { function setStatusIcon(status) {
console.error('Socket.io is reqired to use this panel.'); switch (status) {
return; case 0:
$('#server_status_icon').html('<i class="fa fa-circle text-danger"></i> Offline');
break;
case 1:
$('#server_status_icon').html('<i class="fa fa-circle text-success"></i> Online');
break;
case 2:
$('#server_status_icon').html('<i class="fa fa-circle text-warning"></i> Starting');
break;
case 3:
$('#server_status_icon').html('<i class="fa fa-circle text-warning"></i> Stopping');
break;
default:
break;
}
} }
$.notifyDefaults({ return {
placement: { init: function () {
from: 'bottom', initSocket();
align: 'right'
}, },
newest_on_top: true,
delay: 2000,
animate: {
enter: 'animated zoomInDown',
exit: 'animated zoomOutDown'
}
});
var notifySocketError = false; setStatusIcon: setStatusIcon,
}
window.Socket = io(Pterodactyl.node.scheme + '://' + Pterodactyl.node.fqdn + ':' + Pterodactyl.node.daemonListen + '/ws/' + Pterodactyl.server.uuid, {
'query': 'token=' + Pterodactyl.server.daemonSecret,
});
Socket.io.on('connect_error', function (err) {
if(typeof notifySocketError !== 'object') {
notifySocketError = $.notify({
message: 'There was an error attempting to establish a WebSocket connection to the Daemon. This panel will not work as expected.<br /><br />' + err,
}, {
type: 'danger',
delay: 0
});
}
});
// Connected to Socket Successfully
Socket.on('connect', function () {
if (notifySocketError !== false) {
notifySocketError.close();
notifySocketError = false;
}
});
Socket.on('initial status', function (data) {
setStatusIcon(data.status);
});
Socket.on('status', function (data) {
setStatusIcon(data.status);
});
})(); })();
function setStatusIcon(status) { Server.init();
switch (status) {
case 0:
$('#server_status_icon').html('<i class="fa fa-circle text-danger"></i> Offline');
break;
case 1:
$('#server_status_icon').html('<i class="fa fa-circle text-success"></i> Online');
break;
case 2:
$('#server_status_icon').html('<i class="fa fa-circle text-warning"></i> Starting');
break;
case 3:
$('#server_status_icon').html('<i class="fa fa-circle text-warning"></i> Stopping');
break;
default:
break;
}
}

View File

@ -17,59 +17,72 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE. // SOFTWARE.
var Status = {
0: 'Offline',
1: 'Online',
2: 'Starting',
3: 'Stopping'
};
(function updateServerStatus () { var ServerList = (function () {
$('.dynamic-update').each(function (index, data) {
var element = $(this); var Status = {
var serverShortUUID = $(this).data('server'); 0: 'Offline',
$.ajax({ 1: 'Online',
type: 'GET', 2: 'Starting',
url: Router.route('server.ajax.status', { server: serverShortUUID }), 3: 'Stopping'
timeout: 5000, };
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content'), function updateServerStatus () {
} $('.dynamic-update').each(function (index, data) {
}).done(function (data) { var element = $(this);
if (typeof data.status === 'undefined') { var serverShortUUID = $(this).data('server');
element.find('[data-action="status"]').html('<span class="label label-default">Error</span>'); $.ajax({
return; type: 'GET',
} url: Router.route('server.ajax.status', { server: serverShortUUID }),
switch (data.status) { timeout: 5000,
case 0: headers: {
element.find('[data-action="status"]').html('<span class="label label-danger">Offline</span>'); 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content'),
break;
case 1:
element.find('[data-action="status"]').html('<span class="label label-success">Online</span>');
break;
case 2:
element.find('[data-action="status"]').html('<span class="label label-info">Starting</span>');
break;
case 3:
element.find('[data-action="status"]').html('<span class="label label-info">Stopping</span>');
break;
}
if (data.status !== 0) {
var cpuMax = element.find('[data-action="cpu"]').data('cpumax');
var currentCpu = data.proc.cpu.total;
if (cpuMax !== 0) {
currentCpu = parseFloat(((data.proc.cpu.total / cpuMax) * 100).toFixed(2).toString());
} }
element.find('[data-action="memory"]').html(parseInt(data.proc.memory.total / (1024 * 1024))); }).done(function (data) {
element.find('[data-action="cpu"]').html(currentCpu); if (typeof data.status === 'undefined') {
} else { element.find('[data-action="status"]').html('<span class="label label-default">Error</span>');
element.find('[data-action="memory"]').html('--'); return;
element.find('[data-action="cpu"]').html('--'); }
} switch (data.status) {
}).fail(function (jqXHR) { case 0:
console.error(jqXHR); element.find('[data-action="status"]').html('<span class="label label-danger">Offline</span>');
element.find('[data-action="status"]').html('<span class="label label-default">Error</span>'); break;
case 1:
element.find('[data-action="status"]').html('<span class="label label-success">Online</span>');
break;
case 2:
element.find('[data-action="status"]').html('<span class="label label-info">Starting</span>');
break;
case 3:
element.find('[data-action="status"]').html('<span class="label label-info">Stopping</span>');
break;
}
if (data.status !== 0) {
var cpuMax = element.find('[data-action="cpu"]').data('cpumax');
var currentCpu = data.proc.cpu.total;
if (cpuMax !== 0) {
currentCpu = parseFloat(((data.proc.cpu.total / cpuMax) * 100).toFixed(2).toString());
}
element.find('[data-action="memory"]').html(parseInt(data.proc.memory.total / (1024 * 1024)));
element.find('[data-action="cpu"]').html(currentCpu);
} else {
element.find('[data-action="memory"]').html('--');
element.find('[data-action="cpu"]').html('--');
}
}).fail(function (jqXHR) {
console.error(jqXHR);
element.find('[data-action="status"]').html('<span class="label label-default">Error</span>');
});
}); });
}); setTimeout(updateServerStatus, 10000);
setTimeout(updateServerStatus, 10000); }
return {
init: function () {
updateServerStatus();
}
};
})(); })();
ServerList.init();

View File

@ -17,86 +17,99 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE. // SOFTWARE.
(function initTaskFunctions() {
$('[data-action="delete-task"]').click(function (event) { var Tasks = (function () {
var self = $(this);
swal({ function initTaskFunctions() {
type: 'error', $('[data-action="delete-task"]').click(function (event) {
title: 'Delete Task?', var self = $(this);
text: 'Are you sure you want to delete this task? There is no undo.', swal({
showCancelButton: true, type: 'error',
allowOutsideClick: true, title: 'Delete Task?',
closeOnConfirm: false, text: 'Are you sure you want to delete this task? There is no undo.',
confirmButtonText: 'Delete Task', showCancelButton: true,
confirmButtonColor: '#d9534f', allowOutsideClick: true,
showLoaderOnConfirm: true closeOnConfirm: false,
}, function () { confirmButtonText: 'Delete Task',
$.ajax({ confirmButtonColor: '#d9534f',
method: 'DELETE', showLoaderOnConfirm: true
url: Router.route('server.tasks.delete', { }, function () {
server: Pterodactyl.server.uuidShort, $.ajax({
id: self.data('id'), method: 'DELETE',
}), url: Router.route('server.tasks.delete', {
headers: { server: Pterodactyl.server.uuidShort,
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content'), id: self.data('id'),
} }),
}).done(function (data) { headers: {
swal({ 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content'),
type: 'success', }
title: '', }).done(function (data) {
text: 'Task has been deleted.' swal({
}); type: 'success',
self.parent().parent().slideUp(); title: '',
}).fail(function (jqXHR) { text: 'Task has been deleted.'
console.error(jqXHR); });
swal({ self.parent().parent().slideUp();
type: 'error', }).fail(function (jqXHR) {
title: 'Whoops!', console.error(jqXHR);
text: 'An error occured while attempting to delete this task.' swal({
type: 'error',
title: 'Whoops!',
text: 'An error occured while attempting to delete this task.'
});
}); });
}); });
}); });
}); $('[data-action="toggle-task"]').click(function (event) {
$('[data-action="toggle-task"]').click(function (event) { var self = $(this);
var self = $(this); swal({
swal({ type: 'info',
type: 'info', title: 'Toggle Task',
title: 'Toggle Task', text: 'This will toggle the selected task.',
text: 'This will toggle the selected task.', showCancelButton: true,
showCancelButton: true, allowOutsideClick: true,
allowOutsideClick: true, closeOnConfirm: false,
closeOnConfirm: false, confirmButtonText: 'Continue',
confirmButtonText: 'Continue', showLoaderOnConfirm: true
showLoaderOnConfirm: true }, function () {
}, function () { $.ajax({
$.ajax({ method: 'POST',
method: 'POST', url: Router.route('server.tasks.toggle', {
url: Router.route('server.tasks.toggle', { server: Pterodactyl.server.uuidShort,
server: Pterodactyl.server.uuidShort, id: self.data('id'),
id: self.data('id'), }),
}), headers: {
headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content'),
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content'), }
} }).done(function (data) {
}).done(function (data) { swal({
swal({ type: 'success',
type: 'success', title: '',
title: '', text: 'Task has been toggled.'
text: 'Task has been toggled.' });
}); if (data.status !== 1) {
if (data.status !== 1) { self.parent().parent().addClass('muted muted-hover');
self.parent().parent().addClass('muted muted-hover'); } else {
} else { self.parent().parent().removeClass('muted muted-hover');
self.parent().parent().removeClass('muted muted-hover'); }
} }).fail(function (jqXHR) {
}).fail(function (jqXHR) { console.error(jqXHR);
console.error(jqXHR); swal({
swal({ type: 'error',
type: 'error', title: 'Whoops!',
title: 'Whoops!', text: 'An error occured while attempting to toggle this task.'
text: 'An error occured while attempting to toggle this task.' });
}); });
}); });
}); });
}); }
return {
init: function () {
initTaskFunctions();
}
}
})(); })();
Tasks.init();