diff --git a/User/src/database/database.ts b/User/src/database/database.ts index a77f64e..9a08106 100644 --- a/User/src/database/database.ts +++ b/User/src/database/database.ts @@ -1,16 +1,15 @@ import jsonfile from 'jsonfile' import { promises as fs } from 'fs' import { v4 as uuidv4 } from 'uuid' -import { MemoryManager } from './helpers/memory_manager' -import { QueueManager, FileItemTask } from './helpers/queue_manager' +import { DatabaseScheme } from './schemes/database_scheme' +import { FileItemTask } from './schemes/local_resources_scheme' -const defaultData = { +const defaultData: DatabaseScheme = { app_config: { app_type: 'client', user_info: { id: '', email: '', - password: '', departmentId: '', name: '', }, @@ -25,6 +24,7 @@ const defaultData = { network: { usersInLan: [], serverIp: '', + announcement: '', }, local_resources: { directory_schemes: { @@ -32,18 +32,18 @@ const defaultData = { department: { id: uuidv4(), path: '', structure: {}, totalSize: 0 }, shared: { id: uuidv4(), path: '', structure: {}, totalSize: 0 }, }, + task_schemes: { + send_file_queue: [], + receive_file_queue: [], + }, }, } -export class JsonDatabase { +export class Database { private readonly filePath: string - private memoryStore: MemoryManager - private queueStore: QueueManager constructor(filePath: string) { this.filePath = filePath - this.memoryStore = new MemoryManager() - this.queueStore = new QueueManager() // Ensure the file exists and is not empty this.ensureFileExists().then(() => { @@ -76,12 +76,12 @@ export class JsonDatabase { } // Read JSON from file - async read(): Promise { + async read(): Promise { try { return await jsonfile.readFile(this.filePath) } catch (error: any) { if (error.code === 'ENOENT') { - return defaultData as T // Return defaultData if file does not exist + return defaultData } throw error } @@ -89,53 +89,90 @@ export class JsonDatabase { // Update JSON file with atomic write async update( - updateCallback: (data: Awaited) => Awaited | Promise>, + updateCallback: ( + data: Awaited, + ) => Awaited | Promise>, ): Promise { let data = await this.read() data = await updateCallback(data) await jsonfile.writeFile(this.filePath, data, { spaces: 2 }) } - // Generate and return a new UUID - generateUUID(): string { - return uuidv4() + // **Queue Methods Integrated Here** + + /** Push a task to the send queue */ + async pushToSendQueue(task: FileItemTask): Promise { + await this.update((data) => { + data.local_resources.task_schemes.send_file_queue.push(task) + return data + }) } - // MemoryStore Operations - setMemory(uuid: string, value: Q): void { - this.memoryStore.set(uuid, value) + /** Push a task to the receive queue */ + async pushToReceiveQueue(task: FileItemTask): Promise { + await this.update((data) => { + data.local_resources.task_schemes.receive_file_queue.push(task) + return data + }) } - getMemory(uuid: string): Q | undefined { - return this.memoryStore.get(uuid) + /** Pop (remove) the first task from the send queue */ + async popFromSendQueue(): Promise { + let poppedTask: FileItemTask | undefined + await this.update((data) => { + poppedTask = data.local_resources.task_schemes.send_file_queue.shift() + return data + }) + return poppedTask } - deleteMemory(uuid: string): boolean { - return this.memoryStore.delete(uuid) + /** Pop (remove) the first task from the receive queue */ + async popFromReceiveQueue(): Promise { + let poppedTask: FileItemTask | undefined + await this.update((data) => { + poppedTask = data.local_resources.task_schemes.receive_file_queue.shift() + return data + }) + return poppedTask } - hasMemory(uuid: string): boolean { - return this.memoryStore.has(uuid) + /** View the first task in the send queue without removing it */ + async seekSendQueue(): Promise { + const data = await this.read() + return data.local_resources.task_schemes.send_file_queue[0] } - // Queue Operations - pushQueue(task: FileItemTask): void { - this.queueStore.push(task) + /** View the first task in the receive queue without removing it */ + async seekReceiveQueue(): Promise { + const data = await this.read() + return data.local_resources.task_schemes.receive_file_queue[0] } - popQueue(): FileItemTask | undefined { - return this.queueStore.pop() + /** Get the length of the send queue */ + async sendQueueSize(): Promise { + const data = await this.read() + return data.local_resources.task_schemes.send_file_queue.length } - seekQueue(): FileItemTask | undefined { - return this.queueStore.seek() + /** Get the length of the receive queue */ + async receiveQueueSize(): Promise { + const data = await this.read() + return data.local_resources.task_schemes.receive_file_queue.length } - queueSize(): number { - return this.queueStore.size() + /** Clear all tasks from the send queue */ + async clearSendQueue(): Promise { + await this.update((data) => { + data.local_resources.task_schemes.send_file_queue = [] + return data + }) } - clearQueue(): void { - this.queueStore.clear() + /** Clear all tasks from the receive queue */ + async clearReceiveQueue(): Promise { + await this.update((data) => { + data.local_resources.task_schemes.receive_file_queue = [] + return data + }) } } diff --git a/User/src/database/helpers/memory_manager.ts b/User/src/database/helpers/memory_manager.ts deleted file mode 100644 index 9ffa909..0000000 --- a/User/src/database/helpers/memory_manager.ts +++ /dev/null @@ -1,42 +0,0 @@ -export class MemoryManager { - private storage: Map - - constructor() { - this.storage = new Map() - } - - // Set a value in the memory store - set(uuid: string, value: T): void { - this.storage.set(uuid, value) - } - - // Get a value from the memory store - get(uuid: string): T | undefined { - return this.storage.get(uuid) - } - - // Check if a key exists - has(uuid: string): boolean { - return this.storage.has(uuid) - } - - // Delete a key-value pair - delete(uuid: string): boolean { - return this.storage.delete(uuid) - } - - // Get all keys - keys(): string[] { - return Array.from(this.storage.keys()) - } - - // Get all values - values(): T[] { - return Array.from(this.storage.values()) - } - - // Clear all stored values - clear(): void { - this.storage.clear() - } -} diff --git a/User/src/database/helpers/queue_manager.ts b/User/src/database/helpers/queue_manager.ts deleted file mode 100644 index 4b5e07d..0000000 --- a/User/src/database/helpers/queue_manager.ts +++ /dev/null @@ -1,38 +0,0 @@ -export interface FileItemTask { - ip: string - path: string - userName: string -} - -export class QueueManager { - private queue: FileItemTask[] - - constructor() { - this.queue = [] - } - - // Add a new task to the queue - push(task: FileItemTask): void { - this.queue.push(task) - } - - // Remove and return the first task (FIFO) - pop(): FileItemTask | undefined { - return this.queue.shift() - } - - // View the first task without removing it - seek(): FileItemTask | undefined { - return this.queue[0] - } - - // Get queue length - size(): number { - return this.queue.length - } - - // Clear all tasks - clear(): void { - this.queue = [] - } -} diff --git a/User/src/database/schemes/local_resources_scheme.ts b/User/src/database/schemes/local_resources_scheme.ts index 793712d..0dc5efb 100644 --- a/User/src/database/schemes/local_resources_scheme.ts +++ b/User/src/database/schemes/local_resources_scheme.ts @@ -1,5 +1,6 @@ export interface LocalResourcesScheme { directory_schemes: DirectorySchemes + task_schemes: TaskSchemes } export interface DirectorySchemes { @@ -14,3 +15,14 @@ export interface DirectoryInfo { structure: any totalSize: number } + +export interface TaskSchemes { + send_file_queue: FileItemTask[] + receive_file_queue: FileItemTask[] +} + +export interface FileItemTask { + ip: string + path: string + userName: string +} diff --git a/User/src/helpers/backup_manager.ts b/User/src/helpers/backup_manager.ts index 4f32074..3f24852 100644 --- a/User/src/helpers/backup_manager.ts +++ b/User/src/helpers/backup_manager.ts @@ -4,20 +4,19 @@ import { FileEncryptor } from './file_encryptor' import { TcpCommunicator } from './tcp_communicator' import { operationCodes } from '../network/operation_codes' import { ParsedMessage } from '../network/message_handler' -import { JsonDatabase } from '../database/database' -import { DatabaseScheme } from '../database/schemes/database_scheme' +import { Database } from '../database/database' import { NetworkUserScheme } from '../database/schemes/network_scheme' export class BackupManager { private fileEncryptor: FileEncryptor | null = null - private readonly db: JsonDatabase + private readonly db: Database private readonly clientPort: number private isBusy: boolean = false private intervalId: NodeJS.Timeout | null = null private stopRequested: boolean = false constructor(pathToDatabaseFile: string, clientPort: number) { - this.db = new JsonDatabase(pathToDatabaseFile) + this.db = new Database(pathToDatabaseFile) this.clientPort = clientPort } diff --git a/User/src/helpers/backup_retrieval.ts b/User/src/helpers/backup_retrieval.ts index 159369d..56d63ed 100644 --- a/User/src/helpers/backup_retrieval.ts +++ b/User/src/helpers/backup_retrieval.ts @@ -4,11 +4,10 @@ import path from 'path' import fs from 'fs' import crypto from 'crypto' import { ParsedMessage } from '../network/message_handler' -import { JsonDatabase } from '../database/database' -import { DatabaseScheme } from '../database/schemes/database_scheme' +import { Database } from '../database/database' export class BackupRetrievalWorker { - private db: JsonDatabase + private db: Database private readonly clientPort: number private readonly destinationPath: string private encryptionKey: Buffer | null = null @@ -18,7 +17,7 @@ export class BackupRetrievalWorker { private isBusy: boolean = false constructor(pathToDatabaseFile: string, clientPort: number, destinationPath: string) { - this.db = new JsonDatabase(pathToDatabaseFile) + this.db = new Database(pathToDatabaseFile) this.clientPort = clientPort this.destinationPath = destinationPath } diff --git a/User/src/helpers/department_sharer.ts b/User/src/helpers/department_sharer.ts index 96adb4f..580907a 100644 --- a/User/src/helpers/department_sharer.ts +++ b/User/src/helpers/department_sharer.ts @@ -3,11 +3,10 @@ import path from 'path' import { TcpCommunicator } from './tcp_communicator' import { operationCodes } from '../network/operation_codes' import { ParsedMessage } from '../network/message_handler' -import { JsonDatabase } from '../database/database' -import { DatabaseScheme } from '../database/schemes/database_scheme' +import { Database } from '../database/database' export class DepartmentSharer { - private readonly db: JsonDatabase + private readonly db: Database private departmentDirectory: string | null = null private readonly clientPort: number private isBusy: boolean = false @@ -16,7 +15,7 @@ export class DepartmentSharer { private intervalId: NodeJS.Timeout | null = null constructor(pathToDatabaseFile: string, clientPort: number) { - this.db = new JsonDatabase(pathToDatabaseFile) + this.db = new Database(pathToDatabaseFile) this.clientPort = clientPort } diff --git a/User/src/helpers/directory_watcher.ts b/User/src/helpers/directory_watcher.ts index ed905c7..ce6478b 100644 --- a/User/src/helpers/directory_watcher.ts +++ b/User/src/helpers/directory_watcher.ts @@ -1,15 +1,14 @@ import { promises as fs, watch, FSWatcher } from 'fs' import path from 'path' -import { JsonDatabase } from '../database/database' -import { DatabaseScheme } from '../database/schemes/database_scheme' +import { Database } from '../database/database' export class DirectoryWatcher { private readonly watchers: Map // Stores watchers with directory ID as the key - private readonly db: JsonDatabase + private readonly db: Database private totalSizes: Map // Stores total sizes per directory ID constructor(pathToDatabaseFile: string) { - this.db = new JsonDatabase(pathToDatabaseFile) + this.db = new Database(pathToDatabaseFile) this.watchers = new Map() this.totalSizes = new Map() } diff --git a/User/src/helpers/file_sharer.ts b/User/src/helpers/file_sharer.ts index b921ea6..8179516 100644 --- a/User/src/helpers/file_sharer.ts +++ b/User/src/helpers/file_sharer.ts @@ -3,8 +3,7 @@ import path from 'path' import { TcpCommunicator } from './tcp_communicator' import { operationCodes } from '../network/operation_codes' import { ParsedMessage } from '../network/message_handler' -import { JsonDatabase } from '../database/database' -import { DatabaseScheme } from '../database/schemes/database_scheme' +import { Database } from '../database/database' interface FileSendTask { ip: string @@ -13,7 +12,7 @@ interface FileSendTask { } export class FileSharer { - private readonly db: JsonDatabase + private readonly db: Database private readonly clientPort: number private isBusy: boolean = false private tcpCommunicator: TcpCommunicator | null = null @@ -21,7 +20,7 @@ export class FileSharer { private intervalId: NodeJS.Timeout | null = null constructor(pathToDatabaseFile: string, clientPort: number) { - this.db = new JsonDatabase(pathToDatabaseFile) + this.db = new Database(pathToDatabaseFile) this.clientPort = clientPort } @@ -43,8 +42,9 @@ export class FileSharer { // Method to process the queue private async processQueue(): Promise { - for (let i = 0; i < this.db.queueSize(); i++) { - const task = this.db.popQueue() + const queueSize = await this.db.sendQueueSize() + for (let i = 0; i < queueSize; i++) { + const task = await this.db.popFromSendQueue() if (task) { this.log(`Processing task for file: ${task.path} to IP: ${task.ip}`) const success = await this.sendFile(task) @@ -54,7 +54,7 @@ export class FileSharer { `Failed to send file: ${task.path} to IP: ${task.ip}. Re-adding to queue.`, 'error', ) - this.db.pushQueue(task) + await this.db.pushToSendQueue(task) } else { this.log(`File sent successfully: ${task.path} to IP: ${task.ip}`) } diff --git a/User/src/helpers/network_scanner.ts b/User/src/helpers/network_scanner.ts index bcc6fa6..aa6dff9 100644 --- a/User/src/helpers/network_scanner.ts +++ b/User/src/helpers/network_scanner.ts @@ -2,11 +2,10 @@ import { UdpClient } from '../network/udp/udp_client' import { TcpCommunicator } from './tcp_communicator' import { operationCodes } from '../network/operation_codes' import { ParsedMessage } from '../network/message_handler' -import { JsonDatabase } from '../database/database' -import { DatabaseScheme } from '../database/schemes/database_scheme' +import { Database } from '../database/database' export class NetworkScanner { - private db: JsonDatabase + private db: Database private readonly udpPort: number private readonly tcpPort: number private readonly okPage: string @@ -27,7 +26,7 @@ export class NetworkScanner { errorPage: string, databaseResetPage: string, ) { - this.db = new JsonDatabase(pathToDatabaseFile) + this.db = new Database(pathToDatabaseFile) this.udpPort = udpPort this.tcpPort = tcpPort this.okPage = okPage diff --git a/User/src/helpers/users_info_fetcher.ts b/User/src/helpers/users_info_fetcher.ts index e0c8973..a43d0a9 100644 --- a/User/src/helpers/users_info_fetcher.ts +++ b/User/src/helpers/users_info_fetcher.ts @@ -1,18 +1,17 @@ -import { JsonDatabase } from '../database/database' -import { DatabaseScheme } from '../database/schemes/database_scheme' +import { Database } from '../database/database' import { NetworkUserScheme } from '../database/schemes/network_scheme' import { TcpCommunicator } from './tcp_communicator' import { operationCodes } from '../network/operation_codes' import { ParsedMessage } from '../network/message_handler' export class UsersInfoFetcher { - private db: JsonDatabase + private db: Database private tcpCommunicator: TcpCommunicator | null = null private readonly clientPort: number private intervalId: NodeJS.Timeout | null = null constructor(pathToDatabaseFile: string, clientPort: number) { - this.db = new JsonDatabase(pathToDatabaseFile) + this.db = new Database(pathToDatabaseFile) this.clientPort = clientPort this.tcpCommunicator = null } @@ -39,21 +38,21 @@ export class UsersInfoFetcher { const response = await this.waitForResponse() if (response && response.metaInfo) { - await this.db.update((dbData) => { - const userIndex = dbData.network.usersInLan.findIndex((user) => user.ip === ip) + await this.db.update((data) => { + const userIndex = data.network.usersInLan.findIndex((user) => user.ip === ip) if (userIndex !== -1) { // @ts-ignore - dbData.network.usersInLan[userIndex].id = response.metaInfo.id + data.network.usersInLan[userIndex].id = response.metaInfo.id // @ts-ignore - dbData.network.usersInLan[userIndex].name = response.metaInfo.name + data.network.usersInLan[userIndex].name = response.metaInfo.name // @ts-ignore - dbData.network.usersInLan[userIndex].departmentId = response.metaInfo.departmentId + data.network.usersInLan[userIndex].departmentId = response.metaInfo.departmentId } else { this.log(`User with IP ${ip} not found in the database.`, 'error') } - return dbData + return data }) } diff --git a/User/src/interfaces/file_item_task.ts b/User/src/interfaces/file_item_task.ts deleted file mode 100644 index b05a61f..0000000 --- a/User/src/interfaces/file_item_task.ts +++ /dev/null @@ -1,8 +0,0 @@ -export interface FileItemTask { - ip: string - path: string - userName: string -} - -export const compareFnFileItemTask = (task1: FileItemTask, task2: FileItemTask) => - task1.ip === task2.ip && task1.path === task2.path diff --git a/User/src/interfaces/pool_request.ts b/User/src/interfaces/pool_request.ts deleted file mode 100644 index b7abe1f..0000000 --- a/User/src/interfaces/pool_request.ts +++ /dev/null @@ -1,15 +0,0 @@ -interface PoolRequest { - type: PoolOperation // Renamed to PoolOperation - clientId: string // Add clientId to the request - data: PoolDataBundle -} - -interface PoolDataBundle { - port?: number - ip?: string - operationCode?: string // Keep operationCode here - metaInfo?: { [key: string]: any } - fileContent?: Buffer -} - -type PoolOperation = 'open' | 'send' | 'close' // Define the allowed PoolOperations diff --git a/User/src/interfaces/registered_client.ts b/User/src/interfaces/registered_client.ts deleted file mode 100644 index c5e8205..0000000 --- a/User/src/interfaces/registered_client.ts +++ /dev/null @@ -1,5 +0,0 @@ -interface RegisteredClient { - id: string - ip: string - port: number -} diff --git a/User/src/interfaces/worker_message.ts b/User/src/interfaces/worker_message.ts deleted file mode 100644 index 74ab069..0000000 --- a/User/src/interfaces/worker_message.ts +++ /dev/null @@ -1,6 +0,0 @@ -// Define a type for the message structure -interface WorkerMessage { - type: 'changeContent' | 'showAlert' | 'log' - page?: string - message?: string -} diff --git a/User/src/ipc-handlers/database_handler.ts b/User/src/ipc-handlers/database_handler.ts index e488cf3..375db28 100644 --- a/User/src/ipc-handlers/database_handler.ts +++ b/User/src/ipc-handlers/database_handler.ts @@ -1,17 +1,16 @@ -import { JsonDatabase } from '../database/database' +import { Database } from '../database/database' import { DatabaseScheme } from '../database/schemes/database_scheme' import path from 'path' import { EncryptionKeyScheme, UserInfoScheme } from '../database/schemes/app_config_scheme' -import { FileItemTask } from '../database/helpers/queue_manager' -import { DirectoryInfo, DirectorySchemes } from '../database/schemes/local_resources_scheme' +import {DirectoryInfo, DirectorySchemes, FileItemTask} from '../database/schemes/local_resources_scheme' const pathToDatabaseFile = path.join(__dirname, '..', 'database.json') class IpcDatabaseHandler { - private readonly db: JsonDatabase + private readonly db: Database constructor(pathToDatabaseFile: string) { - this.db = new JsonDatabase(pathToDatabaseFile) + this.db = new Database(pathToDatabaseFile) } async getAppType(): Promise { @@ -86,8 +85,7 @@ class IpcDatabaseHandler { }) return true - } - catch (e) { + } catch (e) { return false } } @@ -125,7 +123,7 @@ class IpcDatabaseHandler { } async addTaskToSendFileQueue(task: FileItemTask) { - this.db.pushQueue(task) + await this.db.pushToSendQueue(task) } async resetInternalDatabase(): Promise { diff --git a/User/src/ipc-handlers/uc_handler.ts b/User/src/ipc-handlers/uc_handler.ts index 83f8002..eea1920 100644 --- a/User/src/ipc-handlers/uc_handler.ts +++ b/User/src/ipc-handlers/uc_handler.ts @@ -1,8 +1,7 @@ import { TcpCommunicator } from '../helpers/tcp_communicator' import dotenv from 'dotenv' import path from 'path' -import { JsonDatabase } from '../database/database' -import { DatabaseScheme } from '../database/schemes/database_scheme' +import { Database } from '../database/database' import { operationCodes } from '../network/operation_codes' dotenv.config({ path: path.join(__dirname, '..', '..', '.env') }) @@ -10,12 +9,12 @@ const pathToDatabaseFile = path.join(__dirname, '..', 'database.json') class IpcUCHandler { private readonly TCP_PORT: number - private readonly db: JsonDatabase + private readonly db: Database private tcpCommunicator: TcpCommunicator | null = null constructor(pathToDatabaseFile: string) { this.TCP_PORT = process.env.TCP_PORT ? parseInt(process.env.TCP_PORT) : 41234 - this.db = new JsonDatabase(pathToDatabaseFile) + this.db = new Database(pathToDatabaseFile) } async openUcSocket(): Promise { diff --git a/User/src/main/main.ts b/User/src/main/main.ts index 52aebcb..a537a80 100644 --- a/User/src/main/main.ts +++ b/User/src/main/main.ts @@ -2,15 +2,13 @@ import { app, BrowserWindow, ipcMain, IpcMainInvokeEvent } from 'electron' import path from 'path' import { promises as fs } from 'fs' import dotenv from 'dotenv' -import { v4 as uuidv4 } from 'uuid' import { WorkerManager } from '../helpers/worker_manager' import { DirectoryWatcher } from '../helpers/directory_watcher' import { WindowManager } from '../helpers/window_manager' import os from 'os' -import { JsonDatabase } from '../database/database' -import { DatabaseScheme } from '../database/schemes/database_scheme' +import { Database } from '../database/database' // Load environment variables dotenv.config({ path: path.join(__dirname, '..', '..', '.env') }) @@ -21,7 +19,7 @@ const HOST = getLocalIp() let mainWindow: BrowserWindow | null = null let windowManager: WindowManager | null = null -let db: JsonDatabase | null = null +let db: Database | null = null let workerManager: WorkerManager | null = null let directoryWatcher: DirectoryWatcher | null = null let announcementWatcher: NodeJS.Timeout | null = null @@ -129,7 +127,7 @@ app.whenReady().then(async () => { windowManager = new WindowManager(mainWindow, pathToPagesDir) workerManager = new WorkerManager(pathToWorkerDir, windowManager) - db = new JsonDatabase(pathToDatabaseFile) + db = new Database(pathToDatabaseFile) await db.update((data) => { data.app_config.server_found = false diff --git a/User/src/main/preload.ts b/User/src/main/preload.ts index cb43ac0..bc41361 100644 --- a/User/src/main/preload.ts +++ b/User/src/main/preload.ts @@ -1,11 +1,10 @@ import { contextBridge, ipcRenderer } from 'electron' -import { FileItemTask } from '../interfaces/file_item_task' import { ipcDatabaseHandler } from '../ipc-handlers/database_handler' import { EncryptionKeyScheme, UserInfoScheme } from '../database/schemes/app_config_scheme' import { ipcUCHandler } from '../ipc-handlers/uc_handler' import { ParsedMessage } from '../network/message_handler' import { NetworkUserScheme } from '../database/schemes/network_scheme' -import { DirectoryInfo, DirectorySchemes } from "../database/schemes/local_resources_scheme"; +import {DirectoryInfo, DirectorySchemes, FileItemTask} from '../database/schemes/local_resources_scheme' contextBridge.exposeInMainWorld('databaseAPI', { getAppType: (): Promise => ipcDatabaseHandler.getAppType(), @@ -19,7 +18,8 @@ contextBridge.exposeInMainWorld('databaseAPI', { ipcDatabaseHandler.writeUserInfo(userInfo), writeEncryptionKey: (encryptionKey: EncryptionKeyScheme): Promise => ipcDatabaseHandler.writeEncryptionKey(encryptionKey), - writeDirectoryPath: (id: string, path: string): Promise => ipcDatabaseHandler.writeDirectoryPath(id, path), + writeDirectoryPath: (id: string, path: string): Promise => + ipcDatabaseHandler.writeDirectoryPath(id, path), addTaskToSendFileQueue: (task: FileItemTask): Promise => ipcDatabaseHandler.addTaskToSendFileQueue(task), resetInternalDatabase: (): Promise => ipcDatabaseHandler.resetInternalDatabase(), diff --git a/User/src/network/operations_custom/user_to_user_operations.ts b/User/src/network/operations_custom/user_to_user_operations.ts index a13621c..0d8ab28 100644 --- a/User/src/network/operations_custom/user_to_user_operations.ts +++ b/User/src/network/operations_custom/user_to_user_operations.ts @@ -4,8 +4,10 @@ import { operationCodes } from '../operation_codes' import path from 'path' import fs from 'fs/promises' import checkDiskSpace from 'check-disk-space' -import { JsonManager } from '../../helpers/json_manager' import { OperationPlugin } from '../operations_base/operation_plugin' +import {Database} from "../../database/database"; + +const pathToDatabaseFile = path.join(__dirname, '..', '..', 'database.json') export class UserToUserOperations implements OperationPlugin { public static readonly operationCodes = { @@ -46,12 +48,14 @@ export class UserToUserOperations implements OperationPlugin { } } - const jsonManager = new JsonManager( - path.join(__dirname, '..', '..', 'json_files', 'application.json'), - ) + const database = new Database(pathToDatabaseFile) try { - await jsonManager.writeValue('announcement', parsedMessage.metaInfo.message) - console.log(`Announcement saved: ${parsedMessage.metaInfo.message}`) + await database.update((data: any) => { + if(!parsedMessage.metaInfo) return data; + + data.app_config.announcement = parsedMessage.metaInfo.message + return data + }) return { operationCode: operationCodes.OK, metaInfo: { message: 'Announcement saved.' } } } catch (error: any) { console.error(`Error saving announcement: ${error.message}`) @@ -62,11 +66,10 @@ export class UserToUserOperations implements OperationPlugin { public static async handleGetUserInformation( parsedMessage: ParsedMessage, ): Promise { - const jsonManager = new JsonManager( - path.join(__dirname, '..', '..', 'json_files', 'userConfig.json'), - ) + const database = new Database(pathToDatabaseFile) try { - const userInfo = await jsonManager.readValue('user_info') + const data = await database.read() + const userInfo = data.app_config.user_info return { operationCode: operationCodes.OK, metaInfo: userInfo } } catch (error: any) { console.error(`Error fetching user info: ${error.message}`) @@ -154,18 +157,16 @@ export class UserToUserOperations implements OperationPlugin { return { operationCode: operationCodes.ERR, metaInfo: { message: 'Missing share info.' } } } - const jsonManager = new JsonManager( - path.join(__dirname, '..', '..', 'json_files', 'application.json'), - ) + const database = new Database(pathToDatabaseFile) const { userName, relativeFilePath } = parsedMessage.metaInfo try { - const appInfo = await jsonManager.readValue('shareDirectory') - const shareDirectory = appInfo?.path || '' + const data = await database.read() + const shareDirectory = data.local_resources.directory_schemes.shared.path console.log(`\n\nShare directory: ${shareDirectory}\n\n`) - if (!shareDirectory) { + if (!shareDirectory || shareDirectory === '') { return { operationCode: operationCodes.ERR, metaInfo: { message: 'Share directory missing.' }, @@ -175,6 +176,11 @@ export class UserToUserOperations implements OperationPlugin { const fullFilePath = path.join(shareDirectory, userName, relativeFilePath) await fs.mkdir(path.dirname(fullFilePath), { recursive: true }) await fs.writeFile(fullFilePath, parsedMessage.fileContent as Buffer) + await database.pushToReceiveQueue({ + ip: '', + path: fullFilePath, + userName, + }) console.log(`File shared: ${fullFilePath}`) return { @@ -195,14 +201,12 @@ export class UserToUserOperations implements OperationPlugin { return { operationCode: operationCodes.ERR, metaInfo: { message: 'Missing user name.' } } } - const jsonManager = new JsonManager( - path.join(__dirname, '..', '..', 'json_files', 'application.json'), - ) + const database = new Database(pathToDatabaseFile) const { userName } = parsedMessage.metaInfo try { - const appInfo = await jsonManager.readValue('departmentDirectory') - const departmentDir = appInfo?.path || '' + const data = await database.read() + const departmentDir = data.local_resources.directory_schemes.department.path const userDepartmentDir = path.join(departmentDir, '..', 'DEPARTMENT_SHARE', userName) try { @@ -245,19 +249,9 @@ export class UserToUserOperations implements OperationPlugin { } // Path to the application.json to read the shareDirectory field - const pathToApplicationJson = path.join(__dirname, '..', '..', 'json_files', 'application.json') - const jsonManager = new JsonManager(pathToApplicationJson) - - // Read application configuration asynchronously - let appInfo - try { - appInfo = await jsonManager.readValue('departmentDirectory') - } catch (error: any) { - return { - operationCode: operationCodes.ERR, - metaInfo: { message: `Error reading application config: ${error.message}` }, - } - } + const database = new Database(pathToDatabaseFile) + const data = await database.read() + let appInfo = data.local_resources.directory_schemes.department if (!appInfo || !appInfo.path) { return {