remade directory wathcer
This commit is contained in:
@@ -86,7 +86,8 @@ async function fetchUsersAndCreateCheckboxes() {
|
|||||||
);
|
);
|
||||||
|
|
||||||
const usersInfo = await window.databaseAPI.getActiveUsers();
|
const usersInfo = await window.databaseAPI.getActiveUsers();
|
||||||
if (!usersInfo || usersInfo.length === 0) {
|
const filteredUsers = usersInfo.filter(user => user.id !== '');
|
||||||
|
if (!filteredUsers.length === 0) {
|
||||||
await window.uiAPI.showAlert('No active users found.');
|
await window.uiAPI.showAlert('No active users found.');
|
||||||
clearInterval(fetchUsersInterval);
|
clearInterval(fetchUsersInterval);
|
||||||
fetchUsersInterval = null;
|
fetchUsersInterval = null;
|
||||||
@@ -109,7 +110,7 @@ async function fetchUsersAndCreateCheckboxes() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const label = document.createElement('label');
|
const label = document.createElement('label');
|
||||||
label.innerHTML = `${user.user_info.name}`;
|
label.innerHTML = `${user.name}`;
|
||||||
label.insertBefore(checkbox, label.firstChild);
|
label.insertBefore(checkbox, label.firstChild);
|
||||||
|
|
||||||
usersDiv.appendChild(label);
|
usersDiv.appendChild(label);
|
||||||
|
|||||||
@@ -1,20 +1,31 @@
|
|||||||
import { promises as fs, watch, FSWatcher } from 'fs'
|
import { promises as fs } from 'fs'
|
||||||
import path from 'path'
|
import path from 'path'
|
||||||
import { Database } from '../database/database'
|
import { Database } from '../database/database'
|
||||||
|
|
||||||
export class DirectoryWatcher {
|
export class DirectoryWatcher {
|
||||||
private readonly watchers: Map<string, FSWatcher> // Stores watchers with directory ID as the key
|
|
||||||
private readonly db: Database
|
private readonly db: Database
|
||||||
private totalSizes: Map<string, number> // Stores total sizes per directory ID
|
private intervalId: NodeJS.Timeout | null = null
|
||||||
|
|
||||||
constructor(pathToDatabaseFile: string) {
|
constructor(pathToDatabaseFile: string) {
|
||||||
this.db = new Database(pathToDatabaseFile)
|
this.db = new Database(pathToDatabaseFile)
|
||||||
this.watchers = new Map<string, FSWatcher>()
|
|
||||||
this.totalSizes = new Map<string, number>()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Start the watcher and register all directories
|
// Start scanning directories at a fixed interval
|
||||||
async start(): Promise<void> {
|
async start(scanInterval: number = 10000): Promise<void> {
|
||||||
|
if (this.intervalId) {
|
||||||
|
this.log('Directory watcher is already running.', 'error')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
this.intervalId = setInterval(async () => {
|
||||||
|
await this.scanDirectories()
|
||||||
|
}, scanInterval)
|
||||||
|
|
||||||
|
this.log('Directory scanning started successfully.')
|
||||||
|
}
|
||||||
|
|
||||||
|
// Scan all directories from the database
|
||||||
|
private async scanDirectories(): Promise<void> {
|
||||||
const dbData = await this.db.read()
|
const dbData = await this.db.read()
|
||||||
const directorySchemes = dbData.local_resources?.directory_schemes
|
const directorySchemes = dbData.local_resources?.directory_schemes
|
||||||
|
|
||||||
@@ -23,59 +34,52 @@ export class DirectoryWatcher {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Initialize watchers for each directory
|
// Scan each directory if it exists
|
||||||
this.registerWatcher(directorySchemes.backup?.id, directorySchemes.backup?.path)
|
await this.scanDirectory('backup', directorySchemes.backup?.path)
|
||||||
this.registerWatcher(directorySchemes.department?.id, directorySchemes.department?.path)
|
await this.scanDirectory('department', directorySchemes.department?.path)
|
||||||
this.registerWatcher(directorySchemes.shared?.id, directorySchemes.shared?.path)
|
await this.scanDirectory('shared', directorySchemes.shared?.path)
|
||||||
|
|
||||||
this.log('Directory watcher started successfully.')
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Register a watcher for a directory with a given ID
|
// Scan a specific directory and update the database
|
||||||
private registerWatcher(id: string | undefined, directoryPath: string | undefined): void {
|
private async scanDirectory(id: string, directoryPath: string | undefined): Promise<void> {
|
||||||
if (!id || !directoryPath) {
|
if (!directoryPath) {
|
||||||
this.log(`Skipping watcher: ID or path is missing.`, 'error')
|
this.log(`Skipping scan: No path provided for ${id}.`, 'error')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.watchers.has(id)) {
|
try {
|
||||||
this.log(`Watcher for ID ${id} is already running.`, 'error')
|
// Check if directory exists
|
||||||
|
await fs.access(directoryPath)
|
||||||
|
} catch {
|
||||||
|
this.log(`Skipping scan: Directory ${directoryPath} does not exist.`, 'error')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create and store a new watcher
|
// If exists, build its structure
|
||||||
const watcher = watch(directoryPath, { recursive: true }, async (eventType, filename) => {
|
|
||||||
if (filename) {
|
|
||||||
this.log(`File change detected in ${directoryPath}: ${eventType} - ${filename}`)
|
|
||||||
await this.handleDirectoryChange(id, directoryPath)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
this.watchers.set(id, watcher)
|
|
||||||
this.log(`Watching directory: ${directoryPath} (ID: ${id})`)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Handle directory change and update the correct entry in the database
|
|
||||||
private async handleDirectoryChange(id: string, directoryPath: string): Promise<void> {
|
|
||||||
const result = await this.buildDirectoryScheme(directoryPath)
|
const result = await this.buildDirectoryScheme(directoryPath)
|
||||||
this.totalSizes.set(id, result.size)
|
|
||||||
|
|
||||||
await this.db.update((data) => {
|
await this.db.update((data) => {
|
||||||
// @ts-ignore
|
switch (id) {
|
||||||
if (!data.local_resources || !data.local_resources.directory_schemes[id]) {
|
case 'backup':
|
||||||
this.log(`Error: Directory scheme for ID ${id} not found in database.`, 'error')
|
data.local_resources.directory_schemes.backup.structure = result.structure
|
||||||
return data
|
data.local_resources.directory_schemes.backup.totalSize = result.size
|
||||||
|
break
|
||||||
|
case 'department':
|
||||||
|
data.local_resources.directory_schemes.department.structure = result.structure
|
||||||
|
data.local_resources.directory_schemes.department.totalSize = result.size
|
||||||
|
break
|
||||||
|
case 'shared':
|
||||||
|
data.local_resources.directory_schemes.shared.structure = result.structure
|
||||||
|
data.local_resources.directory_schemes.shared.totalSize = result.size
|
||||||
|
break
|
||||||
|
default:
|
||||||
|
break
|
||||||
}
|
}
|
||||||
|
|
||||||
// @ts-ignore
|
|
||||||
data.local_resources.directory_schemes[id].structure = result.structure
|
|
||||||
// @ts-ignore
|
|
||||||
data.local_resources.directory_schemes[id].totalSize = result.size
|
|
||||||
|
|
||||||
return data
|
return data
|
||||||
})
|
})
|
||||||
|
|
||||||
this.log(`Updated directory scheme for ID: ${id}`)
|
this.log(`Scanned and updated directory: ${directoryPath} (ID: ${id})`)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Recursively build the directory structure and calculate total size
|
// Recursively build the directory structure and calculate total size
|
||||||
@@ -102,25 +106,15 @@ export class DirectoryWatcher {
|
|||||||
return { structure: directoryScheme, size: totalSize }
|
return { structure: directoryScheme, size: totalSize }
|
||||||
}
|
}
|
||||||
|
|
||||||
// Stop and remove a watcher for a specific directory ID
|
// Stop directory scanning
|
||||||
public stopWatcher(id: string): void {
|
public stop(): void {
|
||||||
const watcher = this.watchers.get(id)
|
if (this.intervalId) {
|
||||||
if (watcher) {
|
clearInterval(this.intervalId)
|
||||||
watcher.close()
|
this.intervalId = null
|
||||||
this.watchers.delete(id)
|
this.log('Stopped directory scanning.')
|
||||||
this.log(`Stopped watcher for ID: ${id}`)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Stop all watchers
|
|
||||||
public stopAllWatchers(): void {
|
|
||||||
for (const [id, watcher] of this.watchers) {
|
|
||||||
watcher.close()
|
|
||||||
this.log(`Stopped watcher for ID: ${id}`)
|
|
||||||
}
|
|
||||||
this.watchers.clear()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Unified logging function
|
// Unified logging function
|
||||||
private log(message: string, level: 'log' | 'error' = 'log'): void {
|
private log(message: string, level: 'log' | 'error' = 'log'): void {
|
||||||
const sourcePrefix = `[DirectoryWatcher]`
|
const sourcePrefix = `[DirectoryWatcher]`
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import { promises as fs } from 'fs'
|
|||||||
import dotenv from 'dotenv'
|
import dotenv from 'dotenv'
|
||||||
|
|
||||||
import { WorkerManager } from '../helpers/worker_manager'
|
import { WorkerManager } from '../helpers/worker_manager'
|
||||||
import { DirectoryWatcher } from '../helpers/directory_watcher'
|
|
||||||
import { WindowManager } from '../helpers/window_manager'
|
import { WindowManager } from '../helpers/window_manager'
|
||||||
|
|
||||||
import os from 'os'
|
import os from 'os'
|
||||||
@@ -21,7 +20,6 @@ let mainWindow: BrowserWindow | null = null
|
|||||||
let windowManager: WindowManager | null = null
|
let windowManager: WindowManager | null = null
|
||||||
let db: Database | null = null
|
let db: Database | null = null
|
||||||
let workerManager: WorkerManager | null = null
|
let workerManager: WorkerManager | null = null
|
||||||
let directoryWatcher: DirectoryWatcher | null = null
|
|
||||||
let announcementWatcher: NodeJS.Timeout | null = null
|
let announcementWatcher: NodeJS.Timeout | null = null
|
||||||
let resetApplicationWatcher: NodeJS.Timeout | null = null
|
let resetApplicationWatcher: NodeJS.Timeout | null = null
|
||||||
|
|
||||||
@@ -37,12 +35,6 @@ async function cleanupAndExit() {
|
|||||||
workerManager.closeAllWorkers()
|
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) {
|
if (workerManager) {
|
||||||
console.log('Terminating all workers...')
|
console.log('Terminating all workers...')
|
||||||
workerManager.closeAllWorkers()
|
workerManager.closeAllWorkers()
|
||||||
|
|||||||
@@ -73,7 +73,10 @@ export class UdpClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Send heartbeat to an IP
|
// Send heartbeat to an IP
|
||||||
private async sendHeartbeat(ip: string, heartbeatCode: string): Promise<{ found: boolean, data?: any }> {
|
private async sendHeartbeat(
|
||||||
|
ip: string,
|
||||||
|
heartbeatCode: string,
|
||||||
|
): Promise<{ found: boolean; data?: any }> {
|
||||||
return new Promise((resolve) => {
|
return new Promise((resolve) => {
|
||||||
const heartbeatMessage = MessageHandler.formatMessage(heartbeatCode)
|
const heartbeatMessage = MessageHandler.formatMessage(heartbeatCode)
|
||||||
|
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ process.on('SIGINT', async () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
async function cleanupAndExit() {
|
async function cleanupAndExit() {
|
||||||
watcher.stopAllWatchers()
|
watcher.stop()
|
||||||
|
|
||||||
console.log('Cleanup complete. Exiting.')
|
console.log('Cleanup complete. Exiting.')
|
||||||
process.exit(0) // Exit with code 0 to indicate a clean exit
|
process.exit(0) // Exit with code 0 to indicate a clean exit
|
||||||
|
|||||||
Reference in New Issue
Block a user