remade directory wathcer
This commit is contained in:
@@ -86,7 +86,8 @@ async function fetchUsersAndCreateCheckboxes() {
|
||||
);
|
||||
|
||||
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.');
|
||||
clearInterval(fetchUsersInterval);
|
||||
fetchUsersInterval = null;
|
||||
@@ -109,7 +110,7 @@ async function fetchUsersAndCreateCheckboxes() {
|
||||
}
|
||||
|
||||
const label = document.createElement('label');
|
||||
label.innerHTML = `${user.user_info.name}`;
|
||||
label.innerHTML = `${user.name}`;
|
||||
label.insertBefore(checkbox, label.firstChild);
|
||||
|
||||
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 { Database } from '../database/database'
|
||||
|
||||
export class DirectoryWatcher {
|
||||
private readonly watchers: Map<string, FSWatcher> // Stores watchers with directory ID as the key
|
||||
private readonly db: Database
|
||||
private totalSizes: Map<string, number> // Stores total sizes per directory ID
|
||||
private intervalId: NodeJS.Timeout | null = null
|
||||
|
||||
constructor(pathToDatabaseFile: string) {
|
||||
this.db = new Database(pathToDatabaseFile)
|
||||
this.watchers = new Map<string, FSWatcher>()
|
||||
this.totalSizes = new Map<string, number>()
|
||||
}
|
||||
|
||||
// Start the watcher and register all directories
|
||||
async start(): Promise<void> {
|
||||
// Start scanning directories at a fixed interval
|
||||
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 directorySchemes = dbData.local_resources?.directory_schemes
|
||||
|
||||
@@ -23,59 +34,52 @@ export class DirectoryWatcher {
|
||||
return
|
||||
}
|
||||
|
||||
// Initialize watchers for each directory
|
||||
this.registerWatcher(directorySchemes.backup?.id, directorySchemes.backup?.path)
|
||||
this.registerWatcher(directorySchemes.department?.id, directorySchemes.department?.path)
|
||||
this.registerWatcher(directorySchemes.shared?.id, directorySchemes.shared?.path)
|
||||
|
||||
this.log('Directory watcher started successfully.')
|
||||
// Scan each directory if it exists
|
||||
await this.scanDirectory('backup', directorySchemes.backup?.path)
|
||||
await this.scanDirectory('department', directorySchemes.department?.path)
|
||||
await this.scanDirectory('shared', directorySchemes.shared?.path)
|
||||
}
|
||||
|
||||
// Register a watcher for a directory with a given ID
|
||||
private registerWatcher(id: string | undefined, directoryPath: string | undefined): void {
|
||||
if (!id || !directoryPath) {
|
||||
this.log(`Skipping watcher: ID or path is missing.`, 'error')
|
||||
// Scan a specific directory and update the database
|
||||
private async scanDirectory(id: string, directoryPath: string | undefined): Promise<void> {
|
||||
if (!directoryPath) {
|
||||
this.log(`Skipping scan: No path provided for ${id}.`, 'error')
|
||||
return
|
||||
}
|
||||
|
||||
if (this.watchers.has(id)) {
|
||||
this.log(`Watcher for ID ${id} is already running.`, 'error')
|
||||
try {
|
||||
// Check if directory exists
|
||||
await fs.access(directoryPath)
|
||||
} catch {
|
||||
this.log(`Skipping scan: Directory ${directoryPath} does not exist.`, 'error')
|
||||
return
|
||||
}
|
||||
|
||||
// Create and store a new watcher
|
||||
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> {
|
||||
// If exists, build its structure
|
||||
const result = await this.buildDirectoryScheme(directoryPath)
|
||||
this.totalSizes.set(id, result.size)
|
||||
|
||||
await this.db.update((data) => {
|
||||
// @ts-ignore
|
||||
if (!data.local_resources || !data.local_resources.directory_schemes[id]) {
|
||||
this.log(`Error: Directory scheme for ID ${id} not found in database.`, 'error')
|
||||
return data
|
||||
switch (id) {
|
||||
case 'backup':
|
||||
data.local_resources.directory_schemes.backup.structure = result.structure
|
||||
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
|
||||
})
|
||||
|
||||
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
|
||||
@@ -102,25 +106,15 @@ export class DirectoryWatcher {
|
||||
return { structure: directoryScheme, size: totalSize }
|
||||
}
|
||||
|
||||
// Stop and remove a watcher for a specific directory ID
|
||||
public stopWatcher(id: string): void {
|
||||
const watcher = this.watchers.get(id)
|
||||
if (watcher) {
|
||||
watcher.close()
|
||||
this.watchers.delete(id)
|
||||
this.log(`Stopped watcher for ID: ${id}`)
|
||||
// Stop directory scanning
|
||||
public stop(): void {
|
||||
if (this.intervalId) {
|
||||
clearInterval(this.intervalId)
|
||||
this.intervalId = null
|
||||
this.log('Stopped directory scanning.')
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
private log(message: string, level: 'log' | 'error' = 'log'): void {
|
||||
const sourcePrefix = `[DirectoryWatcher]`
|
||||
|
||||
@@ -4,7 +4,6 @@ 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'
|
||||
@@ -21,7 +20,6 @@ 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
|
||||
|
||||
@@ -37,12 +35,6 @@ async function cleanupAndExit() {
|
||||
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()
|
||||
|
||||
@@ -73,7 +73,10 @@ export class UdpClient {
|
||||
}
|
||||
|
||||
// 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) => {
|
||||
const heartbeatMessage = MessageHandler.formatMessage(heartbeatCode)
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ process.on('SIGINT', async () => {
|
||||
})
|
||||
|
||||
async function cleanupAndExit() {
|
||||
watcher.stopAllWatchers()
|
||||
watcher.stop()
|
||||
|
||||
console.log('Cleanup complete. Exiting.')
|
||||
process.exit(0) // Exit with code 0 to indicate a clean exit
|
||||
|
||||
Reference in New Issue
Block a user