243 lines
7.7 KiB
TypeScript
243 lines
7.7 KiB
TypeScript
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 { WindowManager } from '../helpers/window_manager'
|
|
|
|
import os from 'os'
|
|
import { Database } from '../database/database'
|
|
|
|
// 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 = getLocalIp()
|
|
|
|
let mainWindow: BrowserWindow | null = null
|
|
let windowManager: WindowManager | null = null
|
|
let db: Database | null = null
|
|
let workerManager: WorkerManager | null = null
|
|
let directoryWatcher: DirectoryWatcher | null = null
|
|
let announcementWatcher: NodeJS.Timeout | null = null
|
|
let resetApplicationWatcher: NodeJS.Timeout | null = null
|
|
|
|
const pathToPagesDir = path.join(__dirname, '..', '..', 'render', 'html')
|
|
const pathToWorkerDir = path.join(__dirname, '..', 'workers')
|
|
const pathToDatabaseFile = path.join(__dirname, '..', 'database.json')
|
|
const pathToClientsBackups = path.join(__dirname, '..', 'backups')
|
|
|
|
async function cleanupAndExit() {
|
|
// Stop all workers
|
|
if (workerManager) {
|
|
console.log('Terminating all workers...')
|
|
workerManager.closeAllWorkers()
|
|
}
|
|
|
|
// Close watchers
|
|
if (directoryWatcher) {
|
|
console.log('Stopping backup directory watcher...')
|
|
directoryWatcher.stopAllWatchers() // Add this method to DirectoryWatcher to close the watcher
|
|
}
|
|
|
|
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}`)
|
|
}
|
|
}
|
|
|
|
function getLocalIp() {
|
|
const interfaces = os.networkInterfaces()
|
|
for (let interfaceName in interfaces) {
|
|
const addresses = interfaces[interfaceName]
|
|
if (!addresses) continue
|
|
for (let address of addresses) {
|
|
// Filter for IPv4 and ignore internal (127.0.0.1) addresses
|
|
if (address.family === 'IPv4' && !address.internal) {
|
|
return address.address
|
|
}
|
|
}
|
|
}
|
|
return '' // Fallback if no IP is found
|
|
}
|
|
|
|
function startAnnouncementWatcher() {
|
|
const checkInterval = 5000 // Check every 5 seconds
|
|
|
|
announcementWatcher = setInterval(async () => {
|
|
if (!windowManager || !db) return
|
|
const data = await db.read()
|
|
|
|
if (data.network.announcement) await windowManager.displayAnnouncement()
|
|
}, checkInterval)
|
|
}
|
|
|
|
function startResetApplicationWatcher() {
|
|
const checkInterval = 5000 // Check every 5 seconds
|
|
|
|
resetApplicationWatcher = setInterval(async () => {
|
|
/*
|
|
if (!applicationInfo || !windowManager) return
|
|
const resetApplicationPreferences = await applicationInfo.readValue(
|
|
'reset_application_preferences',
|
|
)
|
|
|
|
if (resetApplicationPreferences) await windowManager.changeContent('reset-database')
|
|
*/
|
|
}, checkInterval)
|
|
}
|
|
|
|
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,
|
|
sandbox: false,
|
|
},
|
|
})
|
|
|
|
//mainWindow.removeMenu()
|
|
|
|
await ensureDirectoryExists(pathToClientsBackups)
|
|
|
|
windowManager = new WindowManager(mainWindow, pathToPagesDir)
|
|
workerManager = new WorkerManager(pathToWorkerDir, windowManager)
|
|
db = new Database(pathToDatabaseFile)
|
|
|
|
await db.update((data) => {
|
|
data.app_config.server_found = false
|
|
data.app_config.logged_in = false
|
|
return data
|
|
})
|
|
|
|
startAnnouncementWatcher()
|
|
startResetApplicationWatcher()
|
|
|
|
workerManager.startNetworkScannerWorker(
|
|
UDP_PORT,
|
|
TCP_PORT,
|
|
'login',
|
|
'uc_not_found',
|
|
'reset_database',
|
|
pathToDatabaseFile,
|
|
)
|
|
workerManager.startServersWorker(HOST, UDP_PORT, TCP_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 ipc-handlers
|
|
function registerIPCHandlers() {
|
|
ipcMain.handle('show-alert', async (event: IpcMainInvokeEvent, message: string) => {
|
|
if (!windowManager) throw new Error('WindowManager is not initialized.')
|
|
await windowManager.showAlert(message)
|
|
})
|
|
|
|
ipcMain.handle('start-workers', async (_event: IpcMainInvokeEvent) => {
|
|
if (!workerManager) throw new Error('WorkerManager is not initialized.')
|
|
workerManager.startDirectoriesWatchersWorker(pathToDatabaseFile)
|
|
workerManager.startResourceCoordinatorWorker(pathToDatabaseFile, TCP_PORT)
|
|
})
|
|
|
|
ipcMain.handle('stop-workers', async (_event: IpcMainInvokeEvent) => {
|
|
if (!workerManager) throw new Error('WorkerManager is not initialized.')
|
|
workerManager.closeAllWorkers()
|
|
|
|
workerManager.startNetworkScannerWorker(
|
|
UDP_PORT,
|
|
TCP_PORT,
|
|
'login',
|
|
'uc_not_found',
|
|
'reset_database',
|
|
pathToDatabaseFile,
|
|
)
|
|
workerManager.startServersWorker(HOST, UDP_PORT, TCP_PORT)
|
|
})
|
|
|
|
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)
|
|
})
|
|
|
|
ipcMain.handle('read-announcement', async (_event: IpcMainInvokeEvent) => {
|
|
if (!db) throw new Error('Database is not initialized.')
|
|
const data = await db.read()
|
|
const announcement = data.network.announcement
|
|
data.network.announcement = ''
|
|
|
|
return announcement
|
|
})
|
|
|
|
ipcMain.handle('close-announcement-window', async (_event: IpcMainInvokeEvent) => {
|
|
if (!windowManager) throw new Error('WindowManager is not initialized.')
|
|
return await windowManager.closeAnnouncementWindow()
|
|
})
|
|
|
|
// Workers IPC Handlers
|
|
ipcMain.handle(
|
|
'start-backup-retrieval',
|
|
async (_event: IpcMainInvokeEvent, destinationPath: string) => {
|
|
if (!workerManager) throw new Error('WorkerManager is not initialized.')
|
|
return workerManager.startBackupRetrievalWorker(TCP_PORT, destinationPath, pathToDatabaseFile)
|
|
},
|
|
)
|
|
}
|