This commit is contained in:
choelzl 2022-02-09 11:30:21 +01:00
parent 4c8b17b4d1
commit 6b6cf9a2e2
Signed by: sora
GPG Key ID: A362EA0491E2EEA0

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2016-2021 phantombot.github.io/PhantomBot * Copyright (C) 2016-2019 phantombot.tv
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -15,38 +15,61 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
//NOTE: this is straight copied from panel's index.js
// Main socket and functions. // Main socket and functions.
$(function () { $(function() {
if (!helpers.isLocalPanel()) {
$.ajax(
{ var helpers = {};
type: 'GET',
url: 'https://' + helpers.getBotHost() + '/sslcheck', helpers.DEBUG_STATES = {
crossDomain: true, NONE: 0,
dataType: 'text', DEBUG: 1,
async: false, INFO: 2,
success: function (data) { FORCE: 3
if (data === 'false') { };
window.location = window.location.origin + window.location.pathname + 'login/#sslFail=true'; // Debug status. 0 = off | 1 = on.
} helpers.DEBUG_STATE = (localStorage.getItem('phantombot_debug_state') !== null ? parseInt(localStorage.getItem('phantombot_debug_state')) : helpers.DEBUG_STATES.NONE);
}, // Debug types.
error: function () { helpers.LOG_TYPE = helpers.DEBUG_STATES;
window.location = window.location.origin + window.location.pathname + 'login/#sslFail=true';
} /*
} * @function Used to print debug messages in the console.
); *
} * @param {String} message
var webSocket = new ReconnectingWebSocket((window.location.protocol === 'https:' ? 'wss://' : 'ws://') + helpers.getBotHost() + '/ws/panel?target=' + helpers.getBotHost(), null, {reconnectInterval: 500}), * @param {Number} type
callbacks = [], */
listeners = [], helpers.log = function(message, type) {
socket = {}; if (helpers.DEBUG_STATE === helpers.DEBUG_STATES.DEBUG || type === helpers.DEBUG_STATE || type === helpers.LOG_TYPE.FORCE) {
console.log('%c[PhantomBot Log]', 'color: #6441a5; font-weight: 900;', message);
}
};
/*
* @function Used to print error messages in the console.
*
* @param {String} message
* @param {Number} type
*/
helpers.logError = function(message, type) {
console.log('%c[PhantomBot Error]', 'color: red; font-weight: 900;', message);
};
var webSocket = new ReconnectingWebSocket((getProtocol() === 'https://' || window.location.protocol === 'https:' ? 'wss://' : 'ws://') + 'twitchbot.helcel.net' + '/ws/panel', null, { reconnectInterval: 500 }),
callbacks = [],
listeners = [],
familyHandlers = {},
socket = {};
/* /*
* @function Used to send messages to the socket. This should be private to this script. * @function Used to send messages to the socket. This should be private to this script.
* *
* @param {Object} message * @param {Object} message
*/ */
var sendToSocket = function (message) { var sendToSocket = function(message) {
try { try {
let json = JSON.stringify(message); let json = JSON.stringify(message);
@ -72,7 +95,7 @@ $(function () {
* @param {Function} callback * @param {Function} callback
* @param {Boolean} storeKey * @param {Boolean} storeKey
*/ */
var generateCallBack = function (id, tables, isUpdate, isArray, callback, storeKey) { var generateCallBack = function(id, tables, isUpdate, isArray, callback, storeKey) {
if (callbacks[id] !== undefined) { if (callbacks[id] !== undefined) {
helpers.logError('Callback with id "' + id + '" exists already. Aborting update.', helpers.LOG_TYPE.FORCE); helpers.logError('Callback with id "' + id + '" exists already. Aborting update.', helpers.LOG_TYPE.FORCE);
} else { } else {
@ -82,12 +105,12 @@ $(function () {
await: (tables.length === 0 ? 1 : tables.length), await: (tables.length === 0 ? 1 : tables.length),
isUpdate: isUpdate, isUpdate: isUpdate,
isArray: isArray, isArray: isArray,
func: function (e) { func: function(e) {
try { try {
callback(e); callback(e);
} catch (ex) { } catch (ex) {
// Line number won't be accurate, function will by anonymous, but we get the stack so it should be fine. // Line number won't be accurate, function will by anonymous, but we get the stack so it should be fine.
helpers.logError('Failed to run callback: (' + ex.name + ') ' + ex.message + ' >> ' + ex.stack, helpers.LOG_TYPE.FORCE); helpers.logError('Failed to run callback: ' + ex.stack, helpers.LOG_TYPE.FORCE);
} }
}, },
storeKey: storeKey, storeKey: storeKey,
@ -102,15 +125,15 @@ $(function () {
* @param {String} listener_id * @param {String} listener_id
* @param {Function} callback * @param {Function} callback
*/ */
socket.addListener = function (listener_id, callback) { socket.addListener = function(listener_id, callback) {
if (listeners[listener_id] === undefined) { if (listeners[listener_id] === undefined) {
helpers.log('Added listener with id ' + listener_id); helpers.log('Adding listener with id ' + listener_id);
listeners[listener_id] = function (e) { listeners[listener_id] = function(e) {
try { try {
callback(e); callback(e);
} catch (ex) { } catch (ex) {
// Line number won't be accurate, function will by anonymous, but we get the stack so it should be fine. // Line number won't be accurate, function will by anonymous, but we get the stack so it should be fine.
helpers.logError('Failed to run listener: (' + ex.name + ') ' + ex.message + ' >> ' + ex.stack, helpers.LOG_TYPE.FORCE); helpers.logError('Failed to run listener: ' + ex.stack, helpers.LOG_TYPE.FORCE);
} }
}; };
} }
@ -121,12 +144,29 @@ $(function () {
* *
* @param {String} listener_id * @param {String} listener_id
*/ */
socket.removeListener = function (listener_id) { socket.removeListener = function(listener_id) {
if (listeners[listener_id] !== undefined) { if (listeners[listener_id] !== undefined) {
delete listeners[listener_id]; delete listeners[listener_id];
} }
}; };
socket.addFamilyHandler = function(familyName, callback) {
familyHandlers[familyName] = function(e) {
try {
callback(e);
} catch (ex) {
// Line number won't be accurate, function will by anonymous, but we get the stack so it should be fine.
helpers.logError('Failed to run family handler: ' + ex.stack, helpers.LOG_TYPE.FORCE);
}
};
}
socket.removeFamilyHandler = function(familyName) {
if (familyHandlers[familyName] !== undefined) {
delete listeners[familyName];
}
};
/* /*
* @function Runs a bot commands as the bot in async, thus returning right away. * @function Runs a bot commands as the bot in async, thus returning right away.
* *
@ -134,7 +174,7 @@ $(function () {
* @param {String} command * @param {String} command
* @param {Function} callback * @param {Function} callback
*/ */
socket.sendCommand = function (callback_id, command, callback) { socket.sendCommand = function(callback_id, command, callback) {
// Genetate a callback. // Genetate a callback.
generateCallBack(callback_id, [], true, false, callback); generateCallBack(callback_id, [], true, false, callback);
@ -151,7 +191,7 @@ $(function () {
* @param {String} callback_id * @param {String} callback_id
* @param {Function} callback * @param {Function} callback
*/ */
socket.getBotVersion = function (callback_id, callback) { socket.getBotVersion = function(callback_id, callback) {
// Genetate a callback. // Genetate a callback.
generateCallBack(callback_id, [], true, false, callback); generateCallBack(callback_id, [], true, false, callback);
@ -168,7 +208,7 @@ $(function () {
* @param {String} command * @param {String} command
* @param {Function} callback * @param {Function} callback
*/ */
socket.sendCommandSync = function (callback_id, command, callback) { socket.sendCommandSync = function(callback_id, command, callback) {
// Genetate a callback. // Genetate a callback.
generateCallBack(callback_id, [], true, false, callback); generateCallBack(callback_id, [], true, false, callback);
@ -188,7 +228,7 @@ $(function () {
* @param {Array} args * @param {Array} args
* @param {Function} callback * @param {Function} callback
*/ */
socket.wsEvent = function (callback_id, script, argsString, args, callback) { socket.wsEvent = function(callback_id, script, argsString, args, callback) {
// Genetate a callback. // Genetate a callback.
generateCallBack(callback_id, [], true, false, callback); generateCallBack(callback_id, [], true, false, callback);
@ -203,16 +243,6 @@ $(function () {
}); });
}; };
socket.getDiscordChannelList = function (callback_id, callback) {
// Genetate a callback.
socket.addListener(callback_id, callback);
// Send event.
sendToSocket({
discordchannellist: callback_id
});
};
/* /*
* @function Updates a value in the database of the bot. * @function Updates a value in the database of the bot.
* *
@ -222,7 +252,7 @@ $(function () {
* @param {String} value * @param {String} value
* @param {Function} callback * @param {Function} callback
*/ */
socket.updateDBValue = function (callback_id, table, key, value, callback) { socket.updateDBValue = function(callback_id, table, key, value, callback) {
// Genetate a callback. // Genetate a callback.
generateCallBack(callback_id, [], true, false, callback); generateCallBack(callback_id, [], true, false, callback);
@ -244,7 +274,7 @@ $(function () {
* @param {Object} dataObj {tables: [], keys: [], values: } * @param {Object} dataObj {tables: [], keys: [], values: }
* @param {Function} callback * @param {Function} callback
*/ */
socket.updateDBValues = function (callback_id, dataObj, callback) { socket.updateDBValues = function(callback_id, dataObj, callback) {
// Genetate a callback. // Genetate a callback.
generateCallBack(callback_id, dataObj.tables, true, false, callback); generateCallBack(callback_id, dataObj.tables, true, false, callback);
@ -270,7 +300,7 @@ $(function () {
* @param {String} value * @param {String} value
* @param {Function} callback * @param {Function} callback
*/ */
socket.incrDBValue = function (callback_id, table, key, value, callback) { socket.incrDBValue = function(callback_id, table, key, value, callback) {
// Genetate a callback. // Genetate a callback.
generateCallBack(callback_id, [], true, false, callback); generateCallBack(callback_id, [], true, false, callback);
@ -294,7 +324,7 @@ $(function () {
* @param {String} value * @param {String} value
* @param {Function} callback * @param {Function} callback
*/ */
socket.decrDBValue = function (callback_id, table, key, value, callback) { socket.decrDBValue = function(callback_id, table, key, value, callback) {
// Genetate a callback. // Genetate a callback.
generateCallBack(callback_id, [], true, false, callback); generateCallBack(callback_id, [], true, false, callback);
@ -317,7 +347,7 @@ $(function () {
* @param {String} key * @param {String} key
* @param {Function} callback * @param {Function} callback
*/ */
socket.getDBValue = function (callback_id, table, key, callback) { socket.getDBValue = function(callback_id, table, key, callback) {
// Genetate a callback. // Genetate a callback.
generateCallBack(callback_id, [], false, false, callback); generateCallBack(callback_id, [], false, false, callback);
@ -339,11 +369,11 @@ $(function () {
* @param {Function} callback * @param {Function} callback
* @param {Boolean} storeKey - Store the value with the key name from the DB. Default stores it as the table, thus making it only possible to query the table once. * @param {Boolean} storeKey - Store the value with the key name from the DB. Default stores it as the table, thus making it only possible to query the table once.
*/ */
socket.getDBValues = function (callback_id, dataObj, storeKey, callback) { socket.getDBValues = function(callback_id, dataObj, storeKey, callback) {
callback = (callback === undefined ? storeKey : callback); callback = (callback === undefined ? storeKey : callback);
// Genetate a callback. // Genetate a callback.
generateCallBack(callback_id, dataObj.tables, false, false, callback, (typeof storeKey !== 'function')); generateCallBack(callback_id, dataObj.tables, false, false, callback, (typeof storeKey === 'function' ? false : true));
// Start sending the updates to the socket. // Start sending the updates to the socket.
for (let i = 0; i < dataObj.tables.length; i++) { for (let i = 0; i < dataObj.tables.length; i++) {
@ -367,7 +397,7 @@ $(function () {
* @param {String} order * @param {String} order
* @param {Function} callback * @param {Function} callback
*/ */
socket.getDBTableValuesByOrder = function (callback_id, table, limit, offset, order, isNumber, callback) { socket.getDBTableValuesByOrder = function(callback_id, table, limit, offset, order, isNumber, callback) {
// Genetate a callback. // Genetate a callback.
generateCallBack(callback_id, [], false, true, callback); generateCallBack(callback_id, [], false, true, callback);
@ -391,7 +421,7 @@ $(function () {
* @param {String} table * @param {String} table
* @param {Function} callback * @param {Function} callback
*/ */
socket.getDBTableValues = function (callback_id, table, callback) { socket.getDBTableValues = function(callback_id, table, callback) {
// Genetate a callback. // Genetate a callback.
generateCallBack(callback_id, [], false, true, callback); generateCallBack(callback_id, [], false, true, callback);
@ -411,7 +441,7 @@ $(function () {
* @param {Array Object} tables [{table: 'a'}, {table: 'b'}] * @param {Array Object} tables [{table: 'a'}, {table: 'b'}]
* @param {Function} callback * @param {Function} callback
*/ */
socket.getDBTablesValues = function (callback_id, tables, callback) { socket.getDBTablesValues = function(callback_id, tables, callback) {
// Genetate a callback. // Genetate a callback.
generateCallBack(callback_id, [], false, true, callback); generateCallBack(callback_id, [], false, true, callback);
@ -430,7 +460,7 @@ $(function () {
* @param {String} key * @param {String} key
* @param {Function} callback * @param {Function} callback
*/ */
socket.removeDBValue = function (callback_id, table, key, callback) { socket.removeDBValue = function(callback_id, table, key, callback) {
// Genetate a callback. // Genetate a callback.
generateCallBack(callback_id, [], false, true, callback); generateCallBack(callback_id, [], false, true, callback);
@ -451,7 +481,7 @@ $(function () {
* @param {Object} dataObj {tables: [], keys: []} * @param {Object} dataObj {tables: [], keys: []}
* @param {Function} callback * @param {Function} callback
*/ */
socket.removeDBValues = function (callback_id, dataObj, callback) { socket.removeDBValues = function(callback_id, dataObj, callback) {
// Genetate a callback. // Genetate a callback.
generateCallBack(callback_id, dataObj.tables, false, true, callback); generateCallBack(callback_id, dataObj.tables, false, true, callback);
@ -467,40 +497,15 @@ $(function () {
} }
}; };
/*
* @function Sends a remote panel query.
*
* @param {String} query_id
* @param {String} query
* @param {Object} params
* @param {Function} callback
*/
socket.doRemote = function (query_id, query, params, callback) {
generateCallBack(query_id, [], false, true, callback);
sendToSocket({
remote: true,
id: query_id,
query: query,
params: params
});
};
socket.close = function () {
webSocket.close(1000);
};
// WebSocket events. // WebSocket events.
socket.getReadyState = function() {return webSocket.readyState;}
/* /*
* @function Called when the socket opens. * @function Called when the socket opens.
*/ */
webSocket.onopen = function () { webSocket.onopen = function() {
helpers.log('Connection established with the websocket.', helpers.LOG_TYPE.FORCE); helpers.log('Connection established with the websocket.', helpers.LOG_TYPE.FORCE);
// Restart Pace.
Pace.restart();
// Remove all alerts.
toastr.remove();
// Auth with the socket. // Auth with the socket.
sendToSocket({ sendToSocket({
authenticate: getAuth() authenticate: getAuth()
@ -510,16 +515,14 @@ $(function () {
/* /*
* @function Socket calls when it closes * @function Socket calls when it closes
*/ */
webSocket.onclose = function () { webSocket.onclose = function() {
helpers.logError('Connection lost with the websocket.', helpers.LOG_TYPE.FORCE); helpers.logError('Connection lost with the websocket.', helpers.LOG_TYPE.FORCE);
// Add error toast.
toastr.error('Connection lost with the websocket.', '', {timeOut: 0});
}; };
/* /*
* @function Socket calls when it gets message. * @function Socket calls when it gets message.
*/ */
webSocket.onmessage = function (e) { webSocket.onmessage = function(e) {
try { try {
helpers.log('Message from socket: ' + e.data, helpers.LOG_TYPE.DEBUG); helpers.log('Message from socket: ' + e.data, helpers.LOG_TYPE.DEBUG);
@ -534,7 +537,6 @@ $(function () {
if (message.authresult !== undefined) { if (message.authresult !== undefined) {
if (message.authresult === 'false') { if (message.authresult === 'false') {
helpers.logError('Failed to auth with the socket.', helpers.LOG_TYPE.FORCE); helpers.logError('Failed to auth with the socket.', helpers.LOG_TYPE.FORCE);
toastr.error('Failed to auth with the socket.', '', {timeOut: 0});
} else { } else {
// This is to stop a reconnect loading the main page. // This is to stop a reconnect loading the main page.
if (helpers.isAuth === true) { if (helpers.isAuth === true) {
@ -543,35 +545,26 @@ $(function () {
helpers.isAuth = true; helpers.isAuth = true;
} }
sendToSocket({ // XXX: revent loading main page
remote: true, //$.loadPage('dashboard', 'dashboard.html');
id: 'initLoad.panelSettings',
query: 'panelSettings'
});
} }
return; return;
} }
if (message.id !== undefined) {
if (message.id === 'initLoad.panelSettings') {
window.panelSettings.channelName = message.channelName;
window.panelSettings.displayName = message.displayName;
$.loadPage('dashboard', 'dashboard.html');
helpers.getUserLogo();
}
}
// Make sure this isn't a version request. // Make sure this isn't a version request.
if (message.versionresult !== undefined) { if (message.versionresult !== undefined) {
// Call the callback. // Call the callback.
callbacks[message.versionresult].func(message); callbacks[message.versionresult].func(message);
// Delete the callback. // Delete the callback.
delete callbacks[message.versionresult]; delete callbacks[message.versionresult];
} else { } else if(message.query_id !== undefined) {
// console.log("base got websocket with data");
// console.log(e);
// Handle callbacks. // Handle callbacks.
let callback = callbacks[message.query_id], let callback = callbacks[message.query_id],
listener = listeners[message.query_id]; listener = listeners[message.query_id];
if (callback !== undefined) { if (callback !== undefined) {
// Add our data to the callback array. // Add our data to the callback array.
@ -601,8 +594,8 @@ $(function () {
} }
if (message.query_id.indexOf('module_toggle') !== -1 || message.query_id.indexOf('module_status') !== -1 if (message.query_id.indexOf('module_toggle') !== -1 || message.query_id.indexOf('module_status') !== -1
|| message.query_id.endsWith('module')) { || message.query_id.endsWith('module')) {
if (message.results !== undefined && message.results.value == 'false') { if (message.results.value == 'false') {
$('.load-ajax').remove(); $('.load-ajax').remove();
} }
} }
@ -613,6 +606,11 @@ $(function () {
// Call the listener. // Call the listener.
listener(message.results); listener(message.results);
} }
} else if(message.eventFamily !== undefined) {
let handler = familyHandlers[message.eventFamily];
if(handler !== undefined) {
handler(e)
}
} }
} catch (ex) { } catch (ex) {
// Line number won't be accurate, function will by anonymous, but we get the stack so it should be fine. // Line number won't be accurate, function will by anonymous, but we get the stack so it should be fine.
@ -624,4 +622,4 @@ $(function () {
window.socket = socket; window.socket = socket;
// Store all timers in here so we can destroy them. // Store all timers in here so we can destroy them.
window.timers = []; window.timers = [];
}); });