updated relative location for production and dev

This commit is contained in:
Khyretos 2023-08-08 08:42:59 +02:00
parent 039a16711f
commit 66d8322346
10 changed files with 101 additions and 96 deletions

View file

@ -1,6 +1,6 @@
{ {
"name": "loquendo-bot", "name": "loquendo-bot",
"version": "2.1.0", "version": "2.2.0",
"description": "Bot assistant for streamers over different platforms", "description": "Bot assistant for streamers over different platforms",
"main": "src/main.js", "main": "src/main.js",
"scripts": { "scripts": {

View file

@ -6,76 +6,75 @@ const path = require('path');
const consoleloggerLevel = process.env.WINSTON_LOGGER_LEVEL || 'info'; const consoleloggerLevel = process.env.WINSTON_LOGGER_LEVEL || 'info';
const consoleFormat = format.combine( const consoleFormat = format.combine(
format.colorize(), format.colorize(),
format.timestamp(), format.timestamp(),
format.align(), format.align(),
format.printf((info) => `${info.timestamp} - ${info.level}: ${info.message format.printf((info) => `${info.timestamp} - ${info.level}: ${info.message} ${JSON.stringify(info.metadata)}`),
} ${JSON.stringify(info.metadata)}`),
); );
const fileFormat = format.combine( const fileFormat = format.combine(
format.timestamp(), format.timestamp(),
format.metadata({ fillExcept: ['message', 'level', 'timestamp', 'label'] }), format.metadata({ fillExcept: ['message', 'level', 'timestamp', 'label'] }),
format.json(), format.json(),
); );
const logger = createLogger({ const logger = createLogger({
level: 'info', level: 'info',
format: fileFormat, format: fileFormat,
transports: [ transports: [
new transports.File({ new transports.File({
filename: path.join(resourcesPath, '../logs/error.log'), filename: path.join(__dirname, '../logs/error.log'),
level: 'error', level: 'error',
}), }),
new transports.File({ new transports.File({
filename: path.join(resourcesPath, '../logs/activity.log'), filename: path.join(__dirname, '../logs/activity.log'),
maxsize: 5242880, maxsize: 5242880,
maxFiles: 5, maxFiles: 5,
}), }),
], ],
}); });
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
logger.add( logger.add(
new transports.Console({ new transports.Console({
level: consoleloggerLevel, level: consoleloggerLevel,
format: consoleFormat, format: consoleFormat,
}), }),
); );
} }
fetch(path.join(resourcesPath, '../logs/activity.log')) fetch(path.join(__dirname, '../logs/activity.log'))
.then((response) => response.text()) .then((response) => response.text())
.then((logData) => { .then((logData) => {
const logLines = logData.trim().split('\n'); const logLines = logData.trim().split('\n');
const tableBody = document.getElementById('logContent'); const tableBody = document.getElementById('logContent');
logLines.forEach((logLine) => { logLines.forEach((logLine) => {
const logObject = JSON.parse(logLine); const logObject = JSON.parse(logLine);
const row = document.createElement('tr'); const row = document.createElement('tr');
const levelCell = document.createElement('td'); const levelCell = document.createElement('td');
levelCell.textContent = logObject.level; levelCell.textContent = logObject.level;
levelCell.classList.add(logObject.level); // Add class for styling levelCell.classList.add(logObject.level); // Add class for styling
row.appendChild(levelCell); row.appendChild(levelCell);
const messageCell = document.createElement('td'); const messageCell = document.createElement('td');
messageCell.textContent = logObject.message; messageCell.textContent = logObject.message;
row.appendChild(messageCell); row.appendChild(messageCell);
const metadataCell = document.createElement('td'); const metadataCell = document.createElement('td');
metadataCell.textContent = JSON.stringify(logObject.metadata, null, 2); metadataCell.textContent = JSON.stringify(logObject.metadata, null, 2);
row.appendChild(metadataCell); row.appendChild(metadataCell);
const timestampCell = document.createElement('td'); const timestampCell = document.createElement('td');
timestampCell.textContent = logObject.timestamp; timestampCell.textContent = logObject.timestamp;
row.appendChild(timestampCell); row.appendChild(timestampCell);
tableBody.appendChild(row); tableBody.appendChild(row);
}); });
}) })
.catch((error) => { .catch((error) => {
// console.error('Error fetching log file:', error); // console.error('Error fetching log file:', error);
}); });
module.exports = logger; module.exports = logger;

View file

@ -23,11 +23,11 @@ const settingsPath = main.settingsPath.toString();
const settings = main.settings; const settings = main.settings;
// TODO: remove gooogle voices txt and use api instead // TODO: remove gooogle voices txt and use api instead
const googleVoices = fs.readFileSync(path.join(resourcesPath, './config/googleVoices.txt')).toString().split('\r\n'); const googleVoices = fs.readFileSync(path.join(__dirname, './config/googleVoices.txt')).toString().split('\r\n');
// TODO: remove amazon voices txt and use api instead (sakura project has it) // TODO: remove amazon voices txt and use api instead (sakura project has it)
const amazonVoices = fs.readFileSync(path.join(resourcesPath, './config/amazonVoices.txt')).toString().split('\r\n'); const amazonVoices = fs.readFileSync(path.join(__dirname, './config/amazonVoices.txt')).toString().split('\r\n');
const languagesObject = fs.readFileSync(path.join(resourcesPath, './config/languages.txt')).toString().split('\r\n'); const languagesObject = fs.readFileSync(path.join(__dirname, './config/languages.txt')).toString().split('\r\n');
// html elements // html elements
const root = document.documentElement; const root = document.documentElement;
@ -39,17 +39,15 @@ const notificationSound = document.querySelector('#notification'); // obtain the
const ttsAudioDevices = document.querySelector('#ttsAudioDevice'); // obtain the html reference of the installedTTS comboBox const ttsAudioDevices = document.querySelector('#ttsAudioDevice'); // obtain the html reference of the installedTTS comboBox
// laod local javascript files // laod local javascript files
const chat = require(path.join(resourcesPath, './js/chat')); const chat = require(path.join(__dirname, './js/chat'));
const messageTemplates = require(path.join(resourcesPath, './js/messageTemplates')); const messageTemplates = require(path.join(__dirname, './js/messageTemplates'));
const logger = require(path.join(resourcesPath, './js/logger')); const logger = require(path.join(__dirname, './js/logger'));
const sound = require(path.join(resourcesPath, './js/sound')); const sound = require(path.join(__dirname, './js/sound'));
const talk = require(path.join(resourcesPath, './js/voiceQueue')); // Voice queue system const talk = require(path.join(__dirname, './js/voiceQueue')); // Voice queue system
const config = require(path.join(resourcesPath, './js/settings')); const config = require(path.join(__dirname, './js/settings'));
let notificationSounds = path.join(resourcesPath, './sounds/notifications'); let notificationSounds = path.join(__dirname, './sounds/notifications');
let twitch = require(path.join(resourcesPath, './js/twitch'));
function reset() { function reset() {
ipcRenderer.send('restart'); ipcRenderer.send('restart');
@ -62,16 +60,17 @@ function setServer() {
if (!settings.SERVER.USE_SERVER) { if (!settings.SERVER.USE_SERVER) {
return; return;
} }
server = require(path.join(resourcesPath, './js/server')); server = require(path.join(__dirname, './js/server'));
socket = io(`http://localhost:${settings.SERVER.PORT}`); // Connect to your Socket.IO server socket = io(`http://localhost:${settings.SERVER.PORT}`); // Connect to your Socket.IO server
} }
setServer(); setServer();
const Polly = settings.AMAZON.USE_AMAZON ? require(path.join(resourcesPath, './js/amazon')) : ''; let twitch = settings.TWITCH.USE_TWITCH ? require(path.join(__dirname, './js/twitch')) : '';
const google = settings.GOOGLE.USE_GOOGLE ? require(path.join(resourcesPath, './js/amazon')) : ''; const Polly = settings.AMAZON.USE_AMAZON ? require(path.join(__dirname, './js/amazon')) : '';
const google = settings.GOOGLE.USE_GOOGLE ? require(path.join(__dirname, './js/google')) : '';
const theme = require(path.join(resourcesPath, './js/theme')); const theme = require(path.join(__dirname, './js/theme'));
// initialize values // initialize values
config.getGeneralSettings(); config.getGeneralSettings();

View file

@ -19,7 +19,7 @@ function startVtuber() {
return; return;
} }
app.use('/vtuber', express.static(path.join(resourcesPath, './modules/vtuber/'))); app.use('/vtuber', express.static(path.join(__dirname, '../modules/vtuber/')));
let vtuber = document.body.querySelector('#BrowsersourceVtuber'); let vtuber = document.body.querySelector('#BrowsersourceVtuber');
let vtuberframe = document.createElement('iframe'); let vtuberframe = document.createElement('iframe');
@ -37,7 +37,7 @@ function startChatBubble() {
return; return;
} }
app.use('/chat', express.static(path.join(resourcesPath, './modules/chat'))); app.use('/chat', express.static(path.join(__dirname, '../modules/chat')));
let chat = document.body.querySelector('#BrowsersourceChat'); let chat = document.body.querySelector('#BrowsersourceChat');
let chatframe = document.createElement('iframe'); let chatframe = document.createElement('iframe');

View file

@ -204,6 +204,11 @@ document.body.querySelector('#Info_USERNAME').addEventListener('click', () => {
let element = document.body.querySelector('#TWITCH_OAUTH_TOKEN'); let element = document.body.querySelector('#TWITCH_OAUTH_TOKEN');
element.value = key; element.value = key;
settings.TWITCH.OAUTH_TOKEN = key;
fs.writeFileSync(settingsPath, ini.stringify(settings));
createNotification('Saved OAuth token!', 'success');
}); });
document.body.querySelector('#Info_VTUBER').addEventListener('click', () => { document.body.querySelector('#Info_VTUBER').addEventListener('click', () => {
@ -226,7 +231,7 @@ document.body.querySelector('#close-button').addEventListener('click', (event) =
// #region Notification sound test // #region Notification sound test
document.body.querySelector('#SoundTestButton').addEventListener('click', () => { document.body.querySelector('#SoundTestButton').addEventListener('click', () => {
sound.playAudio(); sound.playNotificationSound();
}); });
document.body.querySelector('#TestTwitchCredentials').addEventListener('click', () => { document.body.querySelector('#TestTwitchCredentials').addEventListener('click', () => {
@ -248,7 +253,7 @@ document.body.querySelector('#USE_TWITCH').addEventListener('click', () => {
fs.writeFileSync(settingsPath, ini.stringify(settings)); fs.writeFileSync(settingsPath, ini.stringify(settings));
const inputs = document.getElementsByClassName('inputTwitch'); const inputs = document.getElementsByClassName('inputTwitch');
toggleRadio(toggle, inputs); toggleRadio(toggle, inputs);
twitch = settings.TWITCH.USE_TWITCH ? require(path.join(resourcesPath, './js/twitch')) : null; twitch = settings.TWITCH.USE_TWITCH ? require(path.join(__dirname, './twitch')) : null;
createNotification(`${toggle ? 'Enabled' : 'Disabled'} Twitch settings!`, 'success'); createNotification(`${toggle ? 'Enabled' : 'Disabled'} Twitch settings!`, 'success');
}); });

View file

@ -47,19 +47,21 @@ function add(ttsData) {
} }
} }
// Play sound function function playNotificationSound() {
function playAudio(data) {
if (settings.AUDIO.USE_NOTIFICATION_SOUNDS) { if (settings.AUDIO.USE_NOTIFICATION_SOUNDS) {
let notfication = new Audio( let notfication = new Audio(
path.join(resourcesPath, `../src/sounds/notifications/${notificationSound.options[settings.AUDIO.NOTIFICATION_SOUND].text}`), path.join(resourcesPath, `./sounds/notifications/${notificationSound.options[settings.AUDIO.NOTIFICATION_SOUND].text}`),
); );
notfication.volume = settings.AUDIO.NOTIFICATION_VOLUME / 100; notfication.volume = settings.AUDIO.NOTIFICATION_VOLUME / 100;
notfication.play(); notfication.play();
} }
}
// Play sound function
function playAudio(data) {
if (settings.TTS.USE_TTS) { if (settings.TTS.USE_TTS) {
add(data); add(data);
} else if (settings.SERVER.USE_SERVER) { } else if (settings.SERVER.USE_SERVER && settings.SERVER.USE_CHATBUBBLE) {
socket.emit('xxx', currentLogoUrl, currentUsername, data); socket.emit('xxx', currentLogoUrl, currentUsername, data);
} }
} }
@ -86,8 +88,8 @@ function playVoice(filteredMessage, logoUrl, username, message) {
if (settings.TTS.USE_TTS) { if (settings.TTS.USE_TTS) {
talk.add(textObject, voice); talk.add(textObject, voice);
} else { } else {
playAudio(textObject); playNotificationSound();
} }
} }
module.exports = { playAudio, playVoice }; module.exports = { playAudio, playVoice, playNotificationSound };

View file

@ -29,13 +29,10 @@ function ping(element) {
client client
.ping() .ping()
.then((data) => { .then((data) => {
console.log(client.readyState());
console.log(data);
value.classList.add('success'); value.classList.add('success');
value.innerText = 'Success!'; value.innerText = 'Success!';
}) })
.catch((e) => { .catch((e) => {
console.log(e);
value.classList.add('error'); value.classList.add('error');
value.innerText = 'Failed!'; value.innerText = 'Failed!';
}); });

View file

@ -6,13 +6,14 @@ const speak = (textObject) =>
new Promise((resolve) => { new Promise((resolve) => {
// say.setEncoding(Encoding); // say.setEncoding(Encoding);
counter += 1; counter += 1;
let savePath = path.join(resourcesPath, '../src/sounds/tts/internal_audio_' + counter + '.mp3'); let savePath = path.join(resourcesPath, './sounds/tts/internal_audio_' + counter + '.mp3');
say.export(textObject.filtered, SelectedVoice, 1, savePath, (err) => { say.export(textObject.filtered, SelectedVoice, 1, savePath, (err) => {
if (err) { if (err) {
console.error(err); console.error(err);
} else { } else {
sound.playAudio({ path: savePath, message: textObject }); sound.playAudio({ path: savePath, message: textObject });
sound.playNotificationSound();
} }
resolve('finished'); resolve('finished');
}); });

View file

@ -1,19 +1,21 @@
const { app, shell, BrowserWindow, ipcMain } = require('electron'); const { app, shell, BrowserWindow, ipcMain } = require('electron');
const writeIniFile = require('write-ini-file'); const { writeIniFile } = require('write-ini-file');
const path = require('path'); const path = require('path');
const ini = require('ini'); const ini = require('ini');
const fs = require('fs'); const fs = require('fs');
let resourcesPath; let resourcesPath = __dirname;
let settingsPath; let settingsPath;
let settings; let settings;
let window; let window;
if (app.isPackaged) { if (app.isPackaged) {
settingsPath = path.join(process.resourcesPath, './settings.ini');
resourcesPath = process.resourcesPath; resourcesPath = process.resourcesPath;
} else { } else {
resourcesPath = __dirname; settingsPath = path.join(resourcesPath, './config/settings.ini');
} }
// Handle creating/removing shortcuts on Windows when installing/uninstalling. // Handle creating/removing shortcuts on Windows when installing/uninstalling.
@ -22,15 +24,15 @@ if (require('electron-squirrel-startup')) {
} }
async function createWindow() { async function createWindow() {
if (!fs.existsSync(resourcesPath)) { if (!fs.existsSync(settingsPath)) {
await createIniFile(path.join(resourcesPath, '../config/settings.ini')); console.log(resourcesPath);
await createIniFile();
} else { } else {
settingsPath = path.join(resourcesPath, './config/settings.ini');
settings = ini.parse(fs.readFileSync(settingsPath, 'utf-8')); settings = ini.parse(fs.readFileSync(settingsPath, 'utf-8'));
} }
window = new BrowserWindow({ window = new BrowserWindow({
icon: path.join(resourcesPath, '/images/icon.png'), icon: path.join(__dirname, '/images/icon.png'),
width: parseInt(settings.SETTINGS.WIDTH), width: parseInt(settings.SETTINGS.WIDTH),
height: parseInt(settings.SETTINGS.HEIGHT), height: parseInt(settings.SETTINGS.HEIGHT),
x: parseInt(settings.SETTINGS.POSITION_X), x: parseInt(settings.SETTINGS.POSITION_X),
@ -44,7 +46,7 @@ async function createWindow() {
}); });
window.loadURL('https://github.com'); window.loadURL('https://github.com');
window.loadFile(path.join(resourcesPath, 'index.html')); window.loadFile(path.join(__dirname, 'index.html'));
if (!app.isPackaged) { if (!app.isPackaged) {
window.webContents.openDevTools(); window.webContents.openDevTools();
@ -112,7 +114,7 @@ ipcMain.on('restart', (event) => {
}); });
ipcMain.on('environment', (event) => { ipcMain.on('environment', (event) => {
event.returnValue = { resourcesPath: resourcesPath, settingsPath: settingsPath, settings: settings }; event.returnValue = { resourcesPath: resourcesPath, settingsPath: settingsPath, settings: settings, isPackaged: app.isPackaged };
}); });
let twitchAuthentication = () => let twitchAuthentication = () =>
@ -203,7 +205,7 @@ ipcMain.on('chatBubble', async (event) => {
}); });
async function createIniFile() { async function createIniFile() {
await writeIniFile(resourcesPath, { await writeIniFile(settingsPath, {
SETTINGS: { SETTINGS: {
VOICE_ENABLED: true, VOICE_ENABLED: true,
NOTIFICATION_ENABLED: true, NOTIFICATION_ENABLED: true,
@ -268,6 +270,6 @@ async function createIniFile() {
API_KEY: '', API_KEY: '',
}, },
}).then(() => { }).then(() => {
settings = ini.parse(fs.readFileSync(resourcesPath, 'utf-8')); settings = ini.parse(fs.readFileSync(settingsPath, 'utf-8'));
}); });
} }

Binary file not shown.