BACKEND DONE FOR ALL APPS
This commit is contained in:
@@ -1,115 +0,0 @@
|
||||
const crypto = require('crypto');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
async function readKeyFromFile(filePath) {
|
||||
try {
|
||||
await fs.promises.access(filePath, fs.constants.F_OK);
|
||||
return fs.promises.readFile(filePath); // Use asynchronous readFile
|
||||
} catch (error) {
|
||||
console.error('Error reading key file:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Paths to the key files remain the same
|
||||
const IV_FILE_PATH = path.join(__dirname, '..', '..', 'iv.key');
|
||||
const SECRET_KEY_FILE_PATH = path.join(__dirname, '..', '..', 'secret.key');
|
||||
|
||||
async function encryptFileInPlace(filePath) {
|
||||
// Await the resolution of these promises
|
||||
const IV = await readKeyFromFile(IV_FILE_PATH);
|
||||
const SECRET_KEY = await readKeyFromFile(SECRET_KEY_FILE_PATH);
|
||||
|
||||
if (!IV || !SECRET_KEY) {
|
||||
throw new Error('Failed to load IV or Secret Key');
|
||||
}
|
||||
|
||||
const tempEncryptedFilePath = filePath + '.enc'; // Temporary encrypted file
|
||||
return new Promise((resolve, reject) => {
|
||||
const cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(SECRET_KEY), IV);
|
||||
const input = fs.createReadStream(filePath);
|
||||
const output = fs.createWriteStream(tempEncryptedFilePath);
|
||||
|
||||
input.pipe(cipher).pipe(output);
|
||||
|
||||
output.on('finish', () => {
|
||||
fs.rename(tempEncryptedFilePath, filePath, (err) => {
|
||||
if (err) reject(err);
|
||||
else resolve('File encrypted successfully and replaced original.');
|
||||
});
|
||||
});
|
||||
output.on('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
async function decryptFileInPlace(filePath) {
|
||||
// Await the resolution of these promises
|
||||
const IV = await readKeyFromFile(IV_FILE_PATH);
|
||||
const SECRET_KEY = await readKeyFromFile(SECRET_KEY_FILE_PATH);
|
||||
|
||||
if (!IV || !SECRET_KEY) {
|
||||
throw new Error('Failed to load IV or Secret Key');
|
||||
}
|
||||
|
||||
const tempDecryptedFilePath = filePath + '.dec'; // Temporary decrypted file
|
||||
return new Promise((resolve, reject) => {
|
||||
const decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(SECRET_KEY), IV);
|
||||
const input = fs.createReadStream(filePath);
|
||||
const output = fs.createWriteStream(tempDecryptedFilePath);
|
||||
|
||||
input.pipe(decipher).pipe(output);
|
||||
|
||||
output.on('finish', () => {
|
||||
fs.rename(tempDecryptedFilePath, filePath, (err) => {
|
||||
if (err) reject(err);
|
||||
else resolve('File decrypted successfully and replaced original.');
|
||||
});
|
||||
});
|
||||
output.on('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
function cryptForKey(content, key, decrypt = false) {
|
||||
const algorithm = 'aes-256-ctr';
|
||||
const secretKey = crypto.createHash('sha256').update(String(key)).digest('base64').substr(0, 32);
|
||||
let cipher;
|
||||
|
||||
if (decrypt) {
|
||||
cipher = crypto.createDecipheriv(algorithm, secretKey, Buffer.alloc(16, 0)); // Using a zeroed IV for CTR
|
||||
} else {
|
||||
cipher = crypto.createCipheriv(algorithm, secretKey, Buffer.alloc(16, 0));
|
||||
}
|
||||
|
||||
return Buffer.concat([cipher.update(content), cipher.final()]);
|
||||
}
|
||||
|
||||
// Encrypts a file in place with a given key
|
||||
async function encryptFileWithKey(filePath, key) {
|
||||
try {
|
||||
const fileContent = await fs.promises.readFile(filePath);
|
||||
const encryptedContent = cryptForKey(fileContent, key, false);
|
||||
await fs.promises.writeFile(filePath, encryptedContent);
|
||||
console.log(`File encrypted successfully: ${filePath}`);
|
||||
} catch (error) {
|
||||
console.error(`Error encrypting file: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function decryptFileWithKey(filePath, key) {
|
||||
try {
|
||||
const fileContent = await fs.promises.readFile(filePath);
|
||||
const decryptedContent = cryptForKey(fileContent, key, true);
|
||||
await fs.promises.writeFile(filePath, decryptedContent);
|
||||
console.log(`File decrypted successfully: ${filePath}`);
|
||||
} catch (error) {
|
||||
console.error(`Error decrypting file: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
encryptFileInPlace,
|
||||
decryptFileInPlace,
|
||||
encryptFileWithKey,
|
||||
decryptFileWithKey,
|
||||
}
|
||||
@@ -1,422 +0,0 @@
|
||||
const {app, BrowserWindow, screen, ipcMain, dialog, shell} = require('electron');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const crypto = require('crypto');
|
||||
const {fork} = require('child_process');
|
||||
|
||||
const {encryptFileInPlace, decryptFileInPlace} = require('./aes_encrypt');
|
||||
const {lockFile, unlockFile} = require("../../helpers/lock_mechanism");
|
||||
const exec = require("nodemon/lib/config/exec");
|
||||
|
||||
const isMac = process.platform === 'darwin';
|
||||
let html_page = undefined;
|
||||
let mainWindow = undefined;
|
||||
let alertWindow = undefined;
|
||||
|
||||
let fetcherProcess = null;
|
||||
let backupProcess = null;
|
||||
let externalEndpointsProcess = null;
|
||||
let sendFileProcess = null;
|
||||
|
||||
const createInitialKeys = () => {
|
||||
const SECRET_KEY = crypto.randomBytes(32);
|
||||
const IV = crypto.randomBytes(16);
|
||||
|
||||
const secretKeyPath = path.join(__dirname, '..', '..', 'secret.key');
|
||||
const ivPath = path.join(__dirname, '..', '..', 'iv.key');
|
||||
|
||||
fs.writeFileSync(secretKeyPath, SECRET_KEY);
|
||||
console.log(`Secret Key saved to ${secretKeyPath}`);
|
||||
|
||||
fs.writeFileSync(ivPath, IV);
|
||||
console.log(`IV saved to ${ivPath}`);
|
||||
}
|
||||
|
||||
const checkForServerConnection = async () => {
|
||||
const pathToIpConfig = path.join(__dirname, '..', '..', 'ipConfig.json');
|
||||
|
||||
try {
|
||||
console.log('Checking for server connection');
|
||||
await fs.promises.access(pathToIpConfig);
|
||||
|
||||
await lockFile(pathToIpConfig);
|
||||
await decryptFileInPlace(pathToIpConfig);
|
||||
const ipConfig = await fs.promises.readFile(pathToIpConfig, 'utf-8');
|
||||
const { ip } = JSON.parse(ipConfig);
|
||||
|
||||
const response = await fetch(`http://${ip}/heartbeat`);
|
||||
|
||||
await encryptFileInPlace(pathToIpConfig)
|
||||
await unlockFile(pathToIpConfig);
|
||||
return response.ok;
|
||||
} catch (error) {
|
||||
console.error("Error:", error);
|
||||
try{
|
||||
fs.unlinkSync(pathToIpConfig);
|
||||
}
|
||||
catch{
|
||||
|
||||
}
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
async function runStartupChecks() {
|
||||
try {
|
||||
await fs.promises.access(path.join(__dirname, '..', '..', 'secret.key'), fs.constants.F_OK);
|
||||
await fs.promises.access(path.join(__dirname, '..', '..', 'iv.key'), fs.constants.F_OK);
|
||||
} catch (err) {
|
||||
console.error("Startup error detected:", err);
|
||||
|
||||
// Run the npm clean script
|
||||
await exec('npm run clean', { cwd: path.join(__dirname, '..', '..') }, (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
console.error('Error occurred while running npm run clean:', stderr);
|
||||
return;
|
||||
}
|
||||
console.log('npm run clean output:', stdout);
|
||||
createInitialKeys();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const createMainWindow = (async (title, width, height) => {
|
||||
mainWindow = new BrowserWindow({
|
||||
title: title,
|
||||
width: width,
|
||||
height: height,
|
||||
resizable: false,
|
||||
icon: path.join(__dirname, '..', 'renderer', 'assets', 'hard-disk.png'),
|
||||
webPreferences: {
|
||||
preload: path.join(__dirname, 'preload.js')
|
||||
}
|
||||
});
|
||||
|
||||
await runStartupChecks();
|
||||
html_page = await checkForServerConnection() ? 'login.html' : 'ip_submit.html';
|
||||
|
||||
//mainWindow.setMenu(null);
|
||||
mainWindow.loadFile(path.join(__dirname, '..', 'renderer', 'html', html_page))
|
||||
.then(() => {
|
||||
console.log('Main window loaded!')
|
||||
})
|
||||
.catch(err => console.error('Failed to load main window:', err));
|
||||
});
|
||||
|
||||
const createAlertWindow = (title, width, height) => {
|
||||
alertWindow = new BrowserWindow({
|
||||
width: width,
|
||||
height: height,
|
||||
title: title,
|
||||
icon: path.join(__dirname, '..', 'renderer', 'assets', 'hard-disk.png'),
|
||||
resizable: false,
|
||||
webPreferences: {
|
||||
nodeIntegration: false,
|
||||
preload: path.join(__dirname, 'preload.js')
|
||||
}
|
||||
});
|
||||
|
||||
//alertWindow.setMenu(null);
|
||||
|
||||
alertWindow.loadFile(path.join(__dirname, '..', 'renderer', 'html', 'alert_modal.html')).then(() => {
|
||||
console.log('Alert window loaded!')
|
||||
})
|
||||
.catch(err => console.error('Failed to load alert window:', err));
|
||||
|
||||
alertWindow.on('closed', () => {
|
||||
alertWindow = undefined;
|
||||
});
|
||||
}
|
||||
|
||||
function showAlert(message) {
|
||||
if (alertWindow === undefined) {
|
||||
const title = 'Alert';
|
||||
const mainScreen = screen.getPrimaryDisplay();
|
||||
const {width, height} = mainScreen.size;
|
||||
createAlertWindow(title, width / 4, height / 4);
|
||||
}
|
||||
|
||||
alertWindow.webContents.once('dom-ready', () => {
|
||||
alertWindow.webContents.executeJavaScript(`showAlert("${message}")`);
|
||||
});
|
||||
}
|
||||
|
||||
app.whenReady().then(() => {
|
||||
const title = "Application";
|
||||
const mainScreen = screen.getPrimaryDisplay();
|
||||
const {width, height} = mainScreen.size;
|
||||
createMainWindow(title, width / 1.5, height / 1.5);
|
||||
|
||||
app.on('activate', () => {
|
||||
if (BrowserWindow.getAllWindows().length === 0) {
|
||||
createMainWindow(title, width, height);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
app.on('before-quit', () => {
|
||||
if (backupProcess !== null) {
|
||||
backupProcess.kill();
|
||||
}
|
||||
if (externalEndpointsProcess !== null) {
|
||||
externalEndpointsProcess.kill();
|
||||
}
|
||||
if (fetcherProcess !== null) {
|
||||
fetcherProcess.kill();
|
||||
}
|
||||
|
||||
if (sendFileProcess !== null) {
|
||||
sendFileProcess.kill();
|
||||
}
|
||||
});
|
||||
|
||||
app.on('window-all-closed', () => {
|
||||
if (!isMac) {
|
||||
app.quit();
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('write-file', async (event, fileName, content) => {
|
||||
try {
|
||||
let filePath = path.join(__dirname, '..', '..', fileName);
|
||||
await lockFile(filePath);
|
||||
await fs.promises.writeFile(filePath, content);
|
||||
await encryptFileInPlace(filePath);
|
||||
await unlockFile(filePath)
|
||||
console.log(`File successfully written to ${filePath}`);
|
||||
return {success: true};
|
||||
} catch (error) {
|
||||
console.error('Failed to write file:', error);
|
||||
return {success: false, error: error.message};
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('delete-file', async (event, fileName) => {
|
||||
try {
|
||||
let filePath = path.join(__dirname, '..', '..', fileName);
|
||||
|
||||
await fs.promises.unlink(filePath);
|
||||
|
||||
console.log(`File ${filePath} successfully deleted`);
|
||||
return {success: true};
|
||||
} catch (error) {
|
||||
console.error('Failed to delete file:', error);
|
||||
return {success: false, error: error.message};
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('read-file', async (event, fileName) => {
|
||||
try {
|
||||
let filePath = path.join(__dirname, '..', '..', fileName);
|
||||
await lockFile(filePath);
|
||||
await decryptFileInPlace(filePath);
|
||||
const content = await fs.promises.readFile(filePath, 'utf-8');
|
||||
|
||||
await encryptFileInPlace(filePath);
|
||||
await unlockFile(filePath);
|
||||
return {success: true, content};
|
||||
} catch (error) {
|
||||
console.error('Error reading file:', error);
|
||||
return {success: false, error: error.message};
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('change-content', async (event, nextPage) => {
|
||||
try {
|
||||
html_page = nextPage;
|
||||
await mainWindow.loadFile(path.join(__dirname, '..', 'renderer', 'html', nextPage));
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Error changing content:', error);
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('open-dir-dialog', async (event) => {
|
||||
try {
|
||||
const result = await dialog.showOpenDialog({
|
||||
properties: ['openDirectory'],
|
||||
});
|
||||
|
||||
if (result.canceled || result.filePaths.length === 0) {
|
||||
return {canceled: true}
|
||||
}
|
||||
|
||||
return result.filePaths[0];
|
||||
} catch (error) {
|
||||
console.error('Error opening file dialog:', error);
|
||||
return null;
|
||||
}
|
||||
})
|
||||
|
||||
ipcMain.handle('open-json-dir-config', async (event, fileName) => {
|
||||
try {
|
||||
const result = await dialog.showOpenDialog({
|
||||
properties: ['openDirectory'],
|
||||
});
|
||||
|
||||
if (result.canceled || result.filePaths.length === 0) {
|
||||
return {canceled: true}
|
||||
}
|
||||
|
||||
const dirPath = result.filePaths[0];
|
||||
await fs.promises.writeFile(
|
||||
path.join(__dirname, '..', '..', fileName),
|
||||
JSON.stringify({
|
||||
path: dirPath
|
||||
}, null, 2));
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Error opening file dialog:', error);
|
||||
return {error: error.message};
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('open-file-dialog', async (event) => {
|
||||
const result = await dialog.showOpenDialog({
|
||||
properties: ['openFile']
|
||||
});
|
||||
|
||||
return result.filePaths[0] || '';
|
||||
});
|
||||
|
||||
ipcMain.handle('check-file-exists', async (event, fileName) => {
|
||||
try {
|
||||
const filePath = path.join(__dirname, '..', '..', fileName);
|
||||
return await fs.promises.access(filePath)
|
||||
.then(() => true)
|
||||
.catch(() => false);
|
||||
} catch (error) {
|
||||
console.error('Error checking file existence:', error);
|
||||
throw error; // Propagate the error to the renderer process
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('show-alert', async (event, message) => {
|
||||
showAlert(message);
|
||||
});
|
||||
|
||||
ipcMain.on('close-alert-window', () => {
|
||||
if (alertWindow) {
|
||||
alertWindow.close();
|
||||
alertWindow = undefined;
|
||||
}
|
||||
});
|
||||
|
||||
//External processes
|
||||
ipcMain.handle('start-main-processes', async (event, args) => {
|
||||
if (!backupProcess) {
|
||||
backupProcess = fork(path.join(__dirname, '..', '..', 'jobs', 'backup.js'), args, { silent: false });
|
||||
backupProcess.on('exit', () => {
|
||||
backupProcess = null;
|
||||
});
|
||||
backupProcess.on('error', (err) => {
|
||||
console.log('Backup process error:', err);
|
||||
});
|
||||
}
|
||||
|
||||
if (!fetcherProcess) {
|
||||
fetcherProcess = fork(path.join(__dirname, '..', '..', 'jobs', 'fetcher.js'), args, { silent: false });
|
||||
fetcherProcess.on('exit', () => {
|
||||
fetcherProcess = null;
|
||||
});
|
||||
fetcherProcess.on('error', (err) => {
|
||||
console.log('Fetcher process error:', err);
|
||||
});
|
||||
|
||||
fetcherProcess.on('message', (message) => {
|
||||
if (message.type === 'startBackup') {
|
||||
backupProcess.send({
|
||||
type: 'startBackup'
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (!externalEndpointsProcess) {
|
||||
externalEndpointsProcess = fork(path.join(__dirname, '..', '..', 'jobs', 'external_endpoints.js'), args, { silent: false });
|
||||
externalEndpointsProcess.on('exit', () => {
|
||||
externalEndpointsProcess = null;
|
||||
});
|
||||
externalEndpointsProcess.on('error', (err) => {
|
||||
console.log('External endpoints process error:', err);
|
||||
});
|
||||
}
|
||||
|
||||
return true; // Indicate that the operation has started
|
||||
});
|
||||
|
||||
ipcMain.handle('start-send-file-process', async (event, args) => {
|
||||
if (sendFileProcess === null) {
|
||||
sendFileProcess = fork(path.join(__dirname, '..', '..', 'jobs', 'send_file.js'), args, {silent: false});
|
||||
sendFileProcess.on('exit', () => {
|
||||
sendFileProcess = null;
|
||||
});
|
||||
}
|
||||
return true; // Indicate that the operation has started
|
||||
});
|
||||
|
||||
ipcMain.handle('kill-before-logout', async(event) =>{
|
||||
if (backupProcess !== null) {
|
||||
backupProcess.kill('SIGINT');
|
||||
}
|
||||
if (externalEndpointsProcess !== null) {
|
||||
externalEndpointsProcess.kill('SIGINT');
|
||||
}
|
||||
if (fetcherProcess !== null) {
|
||||
fetcherProcess.kill('SIGINT');
|
||||
}
|
||||
|
||||
if (sendFileProcess !== null) {
|
||||
sendFileProcess.kill('SIGINT');
|
||||
}
|
||||
})
|
||||
|
||||
ipcMain.handle('decrypt-backup-files', async(event, destPath) => {
|
||||
console.log('ai intrat in handle')
|
||||
if(backupProcess != null){
|
||||
console.log('esti in process');
|
||||
backupProcess.send({
|
||||
type: 'decryptBackup',
|
||||
decryptDestPath: destPath
|
||||
});
|
||||
}
|
||||
})
|
||||
|
||||
// Handle showing a file in the system file explorer
|
||||
ipcMain.handle('show-file-in-explorer', async (event, filePath) => {
|
||||
try {
|
||||
// Ensure the file exists before attempting to show it
|
||||
await fs.promises.access(filePath, fs.constants.F_OK);
|
||||
shell.showItemInFolder(filePath); // Opens the file explorer and highlights the file
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('File does not exist:', error);
|
||||
return false
|
||||
}
|
||||
});
|
||||
|
||||
// Handle removing a path from 'filesReceived.json'
|
||||
ipcMain.handle('remove-path-from-received-files', async (event, filePath) => {
|
||||
try {
|
||||
const jsonFilePath = path.join(__dirname, '..', '..', 'filesReceived.json');
|
||||
await lockFile(jsonFilePath);
|
||||
await decryptFileInPlace(jsonFilePath);
|
||||
const data = await fs.promises.readFile(jsonFilePath, 'utf8');
|
||||
|
||||
const jsonData = JSON.parse(data);
|
||||
|
||||
// Filter out the specified file path
|
||||
jsonData.receivedFiles = jsonData.receivedFiles.filter(file => file !== filePath);
|
||||
|
||||
await fs.promises.writeFile(jsonFilePath, JSON.stringify(jsonData, null, 2), 'utf8');
|
||||
await encryptFileInPlace(jsonFilePath);
|
||||
await unlockFile(jsonFilePath);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Error updating filesReceived.json:', error);
|
||||
throw new Error('Failed to update received files list.');
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,299 @@
|
||||
import {app, BrowserWindow, ipcMain, IpcMainInvokeEvent} from 'electron';
|
||||
import path from 'path';
|
||||
import { promises as fs } from 'fs';
|
||||
import dotenv from 'dotenv';
|
||||
|
||||
import {WorkerManager} from "../helpers/worker_manager";
|
||||
import {DirectoryWatcher} from "../helpers/directory_watcher";
|
||||
import {QueueManager} from "../helpers/queue_manager";
|
||||
import {compareFnFileItemTask, FileItemTask} from "../interfaces/file_item_task";
|
||||
import {TaskScheduler} from "../helpers/task_scheduler";
|
||||
import {WindowManager} from "../helpers/window_manager";
|
||||
import {JsonManager} from "../helpers/json_manager";
|
||||
import {MemoryManager} from "../helpers/memory_manager";
|
||||
import {TcpCommunicator} from "../helpers/tcp_communicator";
|
||||
|
||||
import {operationCodes} from "../network/operation_codes";
|
||||
|
||||
// Load environment variables
|
||||
dotenv.config({ path: path.join(__dirname, '..', '..', '.env') });
|
||||
|
||||
const UDP_PORT = process.env.UDP_PORT ? parseInt(process.env.UDP_PORT) : 41233;
|
||||
const TCP_PORT = process.env.TCP_PORT ? parseInt(process.env.TCP_PORT) : 41234;
|
||||
const HOST = process.env.HOST || '0.0.0.0';
|
||||
|
||||
let mainWindow: BrowserWindow | null = null;
|
||||
let windowManager: WindowManager | null = null;
|
||||
let tcpCommunicator: TcpCommunicator | null = null;
|
||||
let userConfig: JsonManager | null = null;
|
||||
let applicationInfo: JsonManager | null = null;
|
||||
let memoryManager: MemoryManager | null = null;
|
||||
let workerManager: WorkerManager | null = null;
|
||||
let taskScheduler: TaskScheduler | null = null;
|
||||
let backupDirectoryManager: DirectoryWatcher | null = null;
|
||||
let departmentShareManager: DirectoryWatcher | null = null;
|
||||
let sendFileQueue: QueueManager<FileItemTask> | null = null;
|
||||
|
||||
const pathToPagesDir = path.join(__dirname, '..', '..', 'render', 'html');
|
||||
const pathToWorkerDir = path.join(__dirname, '..', 'workers');
|
||||
const pathToJsons = path.join(__dirname, '..', 'json_files');
|
||||
const pathToClientsBackups = path.join(__dirname, '..', 'backups');
|
||||
|
||||
async function cleanupAndExit() {
|
||||
// Stop all workers
|
||||
if (workerManager) {
|
||||
console.log('Terminating all workers...');
|
||||
workerManager.closeAllWorkers();
|
||||
}
|
||||
|
||||
// Reset memory
|
||||
if (memoryManager) {
|
||||
await memoryManager.resetFile();
|
||||
}
|
||||
|
||||
// Close watchers
|
||||
if (backupDirectoryManager) {
|
||||
console.log('Stopping backup directory watcher...');
|
||||
backupDirectoryManager.closeWatcher(); // Add this method to DirectoryWatcher to close the watcher
|
||||
}
|
||||
|
||||
if (departmentShareManager) {
|
||||
console.log('Stopping department directory watcher...');
|
||||
departmentShareManager.closeWatcher(); // Add this method to DirectoryWatcher to close the watcher
|
||||
}
|
||||
|
||||
if(taskScheduler){
|
||||
console.log('Stopping all tasks...');
|
||||
taskScheduler.stopAllTasks()
|
||||
}
|
||||
|
||||
if(workerManager){
|
||||
console.log('Terminating all workers...');
|
||||
workerManager.closeAllWorkers()
|
||||
}
|
||||
|
||||
console.log('Cleanup complete, exiting application.');
|
||||
app.quit(); // This will properly close the application
|
||||
}
|
||||
|
||||
async function ensureDirectoryExists(dirPath: string): Promise<void> {
|
||||
try {
|
||||
await fs.access(dirPath);
|
||||
} catch (err) {
|
||||
// If the directory doesn't exist, create it
|
||||
await fs.mkdir(dirPath, { recursive: true });
|
||||
console.log(`Directory created: ${dirPath}`);
|
||||
}
|
||||
}
|
||||
|
||||
app.whenReady().then(async () => {
|
||||
const title = 'Application';
|
||||
const mainScreen = require('electron').screen.getPrimaryDisplay();
|
||||
const { width, height } = mainScreen.size;
|
||||
|
||||
mainWindow = new BrowserWindow({
|
||||
title,
|
||||
width: width / 1.5,
|
||||
height: height / 1.5,
|
||||
resizable: false,
|
||||
webPreferences: {
|
||||
preload: path.join(__dirname, 'preload.js'),
|
||||
nodeIntegration: false,
|
||||
contextIsolation: true,
|
||||
},
|
||||
});
|
||||
|
||||
await ensureDirectoryExists(pathToJsons);
|
||||
await ensureDirectoryExists(pathToClientsBackups);
|
||||
|
||||
windowManager = new WindowManager(mainWindow, pathToPagesDir);
|
||||
userConfig = new JsonManager(path.join(pathToJsons, 'userConfig.json'));
|
||||
applicationInfo = new JsonManager(path.join(pathToJsons, 'application.json'));
|
||||
memoryManager = new MemoryManager(path.join(pathToJsons, 'memory.json'));
|
||||
sendFileQueue = new QueueManager(path.join(pathToJsons, 'sendFileTasks.json'), compareFnFileItemTask);
|
||||
|
||||
taskScheduler = new TaskScheduler(applicationInfo, windowManager);
|
||||
workerManager = new WorkerManager(pathToWorkerDir, windowManager);
|
||||
|
||||
await userConfig.writeValue('app_type', 'client');
|
||||
await applicationInfo.writeValue('users_ip', []);
|
||||
await memoryManager.resetFile();
|
||||
|
||||
workerManager.startWatchersWorker(path.join(pathToJsons, 'memory.json'), path.join(pathToJsons, 'application.json'));
|
||||
workerManager.startServersWorker(HOST, UDP_PORT, TCP_PORT);
|
||||
workerManager.startResourceCoordinatorWorker(
|
||||
path.join(pathToJsons, 'userConfig.json'),
|
||||
path.join(pathToJsons, 'application.json'),
|
||||
path.join(pathToJsons, 'memory.json'),
|
||||
path.join(pathToJsons, 'sendFileTasks.json'),
|
||||
TCP_PORT
|
||||
);
|
||||
|
||||
|
||||
taskScheduler.startUCCheck(UDP_PORT, 'login', 'uc_not_found');
|
||||
taskScheduler.startUserIPLookup(UDP_PORT);
|
||||
|
||||
registerIPCHandlers();
|
||||
|
||||
await windowManager.changeContent('welcome');
|
||||
});
|
||||
|
||||
app.on('window-all-closed', async () => {
|
||||
console.log('All windows closed, starting cleanup...');
|
||||
await cleanupAndExit(); // Call cleanup when all windows are closed
|
||||
});
|
||||
|
||||
// Catch CTRL+C (SIGINT) and clean up resources
|
||||
process.on('SIGINT', async () => {
|
||||
console.log('CTRL+C pressed, starting cleanup...');
|
||||
await cleanupAndExit(); // Call cleanup on SIGINT
|
||||
});
|
||||
|
||||
app.on('before-quit', async () => {
|
||||
console.log('Application is quitting, starting cleanup...');
|
||||
await cleanupAndExit(); // Call cleanup before app quit
|
||||
});
|
||||
|
||||
// Register IPC handlers
|
||||
function registerIPCHandlers() {
|
||||
// Window Manager IPC Handlers
|
||||
ipcMain.handle('show-alert', async (event: IpcMainInvokeEvent, message: string) => {
|
||||
if (!windowManager) throw new Error('WindowManager is not initialized.');
|
||||
await windowManager.showAlert(message);
|
||||
});
|
||||
|
||||
ipcMain.handle('change-content', async (_event: IpcMainInvokeEvent, destination: string) => {
|
||||
if (!windowManager) throw new Error('WindowManager is not initialized.');
|
||||
await windowManager.changeContent(destination);
|
||||
});
|
||||
|
||||
ipcMain.handle('select-directory', async (_event: IpcMainInvokeEvent) => {
|
||||
if (!windowManager) throw new Error('WindowManager is not initialized.');
|
||||
return await windowManager.selectDirectory();
|
||||
});
|
||||
|
||||
ipcMain.handle('select-file', async (_event: IpcMainInvokeEvent) => {
|
||||
if (!windowManager) throw new Error('WindowManager is not initialized.');
|
||||
return await windowManager.selectFile();
|
||||
});
|
||||
|
||||
ipcMain.handle('show-file-in-explorer', async (_event: IpcMainInvokeEvent, path: string) => {
|
||||
if (!windowManager) throw new Error('WindowManager is not initialized.');
|
||||
return await windowManager.showFileInExplorer(path);
|
||||
});
|
||||
|
||||
// TcpMethods IPC Handlers
|
||||
ipcMain.handle('open-socket', async (_event: IpcMainInvokeEvent) => {
|
||||
if (!applicationInfo) throw new Error('TcpMethods is not initialized.');
|
||||
|
||||
const serverIp = await applicationInfo.readValue('serverIp');
|
||||
if (!serverIp) return;
|
||||
|
||||
tcpCommunicator = new TcpCommunicator(serverIp, TCP_PORT);
|
||||
return await tcpCommunicator.connect()
|
||||
});
|
||||
|
||||
ipcMain.handle('send-message', async (_event: IpcMainInvokeEvent, operationCode: string, metaInfo?: { [key: string]: any }, fileContent?: Buffer) => {
|
||||
if (!tcpCommunicator) throw new Error('TcpMethods is not initialized.');
|
||||
return await tcpCommunicator.sendMessage(operationCode, metaInfo, fileContent);
|
||||
});
|
||||
|
||||
ipcMain.handle('has-response-arrived', async (_event: IpcMainInvokeEvent) => {
|
||||
if (!tcpCommunicator) throw new Error('TcpMethods is not initialized.');
|
||||
return tcpCommunicator.hasResponseArrived();
|
||||
});
|
||||
|
||||
ipcMain.handle('close-socket', async (_event: IpcMainInvokeEvent) => {
|
||||
if (!tcpCommunicator) throw new Error('TcpMethods is not initialized.');
|
||||
return await tcpCommunicator.disconnect();
|
||||
});
|
||||
|
||||
ipcMain.handle('get-last-result', async (_event: IpcMainInvokeEvent) => {
|
||||
if (!tcpCommunicator) throw new Error('TcpMethods is not initialized.');
|
||||
return tcpCommunicator.getLastResult();
|
||||
});
|
||||
|
||||
ipcMain.handle('get-operation-codes', () => {
|
||||
return operationCodes;
|
||||
});
|
||||
|
||||
// UserConfig IPC Handlers
|
||||
ipcMain.handle('read-user-json-files', async (_event: IpcMainInvokeEvent, key: string) => {
|
||||
if (!userConfig) throw new Error('UserConfig is not initialized.');
|
||||
return await userConfig.readValue(key);
|
||||
});
|
||||
|
||||
ipcMain.handle('write-user-json-files', async (_event: IpcMainInvokeEvent, key: string, value: any) => {
|
||||
if (!userConfig) throw new Error('UserConfig is not initialized.');
|
||||
return userConfig.writeValue(key, value);
|
||||
});
|
||||
|
||||
ipcMain.handle('reset-user-json-files', async () => {
|
||||
if (!userConfig) throw new Error('UserConfig is not initialized.');
|
||||
return userConfig.resetFile();
|
||||
});
|
||||
|
||||
ipcMain.handle('remove-user-json-files-key', async (_event: IpcMainInvokeEvent, key: string) => {
|
||||
if (!userConfig) throw new Error('UserConfig is not initialized.');
|
||||
return userConfig.removeValue(key);
|
||||
});
|
||||
|
||||
// ApplicationPreferences IPC Handlers
|
||||
ipcMain.handle('read-application-json-files', async (_event: IpcMainInvokeEvent, key: string) => {
|
||||
if (!applicationInfo) throw new Error('ApplicationInfo is not initialized.');
|
||||
return await applicationInfo.readValue(key);
|
||||
});
|
||||
|
||||
ipcMain.handle('write-application-json-files', async (_event: IpcMainInvokeEvent, key: string, value: any) => {
|
||||
if (!applicationInfo) throw new Error('ApplicationInfo is not initialized.');
|
||||
return applicationInfo.writeValue(key, value);
|
||||
});
|
||||
|
||||
ipcMain.handle('reset-application-json-files', async () => {
|
||||
if (!applicationInfo) throw new Error('ApplicationInfo is not initialized.');
|
||||
return applicationInfo.resetFile();
|
||||
});
|
||||
|
||||
ipcMain.handle('remove-application-json-files-key', async (_event: IpcMainInvokeEvent, key: string) => {
|
||||
if (!applicationInfo) throw new Error('ApplicationInfo is not initialized.');
|
||||
return applicationInfo.removeValue(key);
|
||||
});
|
||||
|
||||
// Memory IPC Handlers
|
||||
ipcMain.handle('memory-create-entry', async () => {
|
||||
if (!memoryManager) throw new Error('MemoryManager is not initialized.');
|
||||
return memoryManager.storeMetaInformation({});
|
||||
});
|
||||
|
||||
ipcMain.handle('memory-read-entry', async (_event: IpcMainInvokeEvent, id: string) => {
|
||||
if (!memoryManager) throw new Error('MemoryManager is not initialized.');
|
||||
return memoryManager.retrieveMetaInformation(id);
|
||||
});
|
||||
|
||||
ipcMain.handle('memory-update-entry', async (_event: IpcMainInvokeEvent, id: string, data: any) => {
|
||||
if (!memoryManager) throw new Error('MemoryManager is not initialized.');
|
||||
return memoryManager.updateMetaInformation(id, data);
|
||||
});
|
||||
|
||||
ipcMain.handle('memory-remove-entry', async (_event: IpcMainInvokeEvent, id: string) => {
|
||||
if (!memoryManager) throw new Error('MemoryManager is not initialized.');
|
||||
return memoryManager.removeMetaInformation(id);
|
||||
});
|
||||
|
||||
// Queue IPC Handlers
|
||||
ipcMain.handle('add-task-to-send-file-queue', async (event: IpcMainInvokeEvent, task: FileItemTask) => {
|
||||
if (!sendFileQueue) throw new Error('SendFileQueue is not initialized.');
|
||||
sendFileQueue.enqueue(task);
|
||||
});
|
||||
|
||||
// BackupRetrievalWorker IPC Handler
|
||||
ipcMain.handle('start-backup-retrieval', async (_event: IpcMainInvokeEvent, destinationPath: string) => {
|
||||
if (!workerManager) throw new Error('WorkerManager is not initialized.');
|
||||
return workerManager.startBackupRetrievalWorker(
|
||||
path.join(pathToJsons, 'userConfig.json'),
|
||||
path.join(pathToJsons, 'application.json'),
|
||||
TCP_PORT,
|
||||
destinationPath
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
const {contextBridge, ipcRenderer} = require('electron');
|
||||
|
||||
contextBridge.exposeInMainWorld('electronAPI', {
|
||||
writeFile: (fileName, content) => ipcRenderer.invoke('write-file', fileName, content),
|
||||
readFile: (fileName) => ipcRenderer.invoke('read-file', fileName),
|
||||
deleteFile: (fileName) => ipcRenderer.invoke('delete-file', fileName),
|
||||
changeContent: (nextPage) => ipcRenderer.invoke('change-content', nextPage),
|
||||
showAlert: (message) => ipcRenderer.invoke('show-alert', message),
|
||||
closeAlertWindow: () => ipcRenderer.send('close-alert-window'),
|
||||
openJsonDirConfigDialog: (fileName) => ipcRenderer.invoke('open-json-dir-config', fileName),
|
||||
openDirDialog: () => ipcRenderer.invoke('open-dir-dialog'),
|
||||
openFileDialog: () => ipcRenderer.invoke('open-file-dialog'),
|
||||
checkFileExists: (fileName) => ipcRenderer.invoke('check-file-exists', fileName),
|
||||
|
||||
startMainProcesses: async (args) => ipcRenderer.invoke('start-main-processes', args),
|
||||
killBeforeLogout: async() => ipcRenderer.invoke('kill-before-logout'),
|
||||
decryptFiles: async(destPath) => ipcRenderer.invoke('decrypt-backup-files', destPath),
|
||||
|
||||
showFileInExplorer: (filePath) => ipcRenderer.invoke('show-file-in-explorer', filePath),
|
||||
removePathFromReceivedFiles: (filePath) => ipcRenderer.invoke('remove-path-from-received-files', filePath)
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import { contextBridge, ipcRenderer } from 'electron';
|
||||
import {FileItemTask} from "../interfaces/file_item_task";
|
||||
|
||||
contextBridge.exposeInMainWorld('electronAPI', {
|
||||
// UserConfig methods
|
||||
readUserConfig: (key: string): Promise<any> => ipcRenderer.invoke('read-user-json-files', key),
|
||||
writeUserConfig: (key: string, value: any): Promise<boolean> => ipcRenderer.invoke('write-user-json-files', key, value),
|
||||
removeUserConfig: (key: string) : Promise<boolean> => ipcRenderer.invoke('remove-user-json-files', key),
|
||||
resetUserConfig: (): Promise<boolean> => ipcRenderer.invoke('reset-user-json-files'),
|
||||
|
||||
// ApplicationPreferences methods
|
||||
readApplicationInfo: (key: string): Promise<any> => ipcRenderer.invoke('read-application-json-files', key),
|
||||
writeApplicationInfo: (key: string, value: any): Promise<boolean> => ipcRenderer.invoke('write-application-json-files', key, value),
|
||||
removeApplicationInfo: (key: string) : Promise<boolean> => ipcRenderer.invoke('remove-application-preferences', key),
|
||||
resetApplicationInfo: (): Promise<boolean> => ipcRenderer.invoke('reset-application-json-files'),
|
||||
|
||||
// UcCommunication methods
|
||||
openUcSocket: (): Promise<any> => ipcRenderer.invoke('open-socket'),
|
||||
sendUcMessage: (operationCode: string, metaInfo: any, fileContent: any): Promise<any> => ipcRenderer.invoke('send-message', operationCode, metaInfo, fileContent),
|
||||
closeUcSocket: (): Promise<any> => ipcRenderer.invoke('close-socket'),
|
||||
hasResponseArrived: (): Promise<boolean> => ipcRenderer.invoke('has-response-arrived'),
|
||||
getLastUcResult: (): Promise<any> => ipcRenderer.invoke('get-last-result'),
|
||||
getOperationsCodes: (): Promise<{ data: { [key: string]: string } }> => ipcRenderer.invoke('get-operation-codes'),
|
||||
|
||||
// MemoryManager methods
|
||||
createMemoryEntry: (): Promise<string> => ipcRenderer.invoke('memory-create-entry'),
|
||||
readMemoryEntry: (id: string): Promise<any> => ipcRenderer.invoke('memory-read-entry', id),
|
||||
updateMemoryEntry: (id: string, data: any): Promise<boolean> => ipcRenderer.invoke('memory-update-entry', id, data),
|
||||
removeMemoryEntry: (id: string): Promise<boolean> => ipcRenderer.invoke('memory-remove-entry', id),
|
||||
|
||||
// UI methods
|
||||
showAlert: (message: string): Promise<void> => ipcRenderer.invoke('show-alert', message),
|
||||
changeContent: (destination: string): Promise<void> => ipcRenderer.invoke('change-content', destination),
|
||||
selectDirectory: (): Promise<string | undefined> => ipcRenderer.invoke('select-directory'),
|
||||
selectFile: (): Promise<string | undefined> => ipcRenderer.invoke('select-file'),
|
||||
showFileInExplorer: (path: string): Promise<void> => ipcRenderer.invoke('show-file-in-explorer', path),
|
||||
|
||||
// Queue methods
|
||||
addTaskToSendFileQueue: (task: FileItemTask): Promise<void> => ipcRenderer.invoke('add-task-to-send-file-queue', task),
|
||||
|
||||
// BackupRetrievalWorker
|
||||
startBackupRetrieval: (destinationPath: string): Promise<void> => ipcRenderer.invoke('start-backup-retrieval', destinationPath)
|
||||
});
|
||||
Reference in New Issue
Block a user