Files
p2ns/plugin-sites/file.drop/watcher.js
T
2026-05-30 22:27:42 -04:00

92 lines
2.7 KiB
JavaScript

/**
* File Drop Plugin - Database Watcher
*
* Handles database change watching for file metadata updates
*/
const sdk = require('../../includes/plugins/sdk');
let dbWatchCallback = null;
/**
* Watch for database changes and log updates
*/
async function setupDatabaseWatcher() {
// Wait for database to be available with retries
let retries = 30;
while (retries > 0) {
try {
await sdk.db.ready();
if (!sdk.db.closed) {
dbWatchCallback = async (...args) => {
try {
const update = args[0];
// Check if we have a valid update for file changes
if (update && typeof update === 'object' && update.collection === '@filedrop/files') {
sdk.log.info('file.drop', `Database watcher detected file change: ${JSON.stringify(update)}`);
// For now, just log the change. Future enhancements could include:
// - Broadcasting file updates via WebSocket
// - Notifying other peers of file changes
// - Updating UI with real-time file status
const fileId = update.key?.id;
if (fileId) {
sdk.log.info('file.drop', `File metadata updated: ${fileId}`);
} else {
sdk.log.debug('file.drop', 'File change detected but no file ID available');
}
} else if (update) {
sdk.log.debug('file.drop', `Database watcher received update for different collection: ${update.collection || 'unknown'}`);
}
// Ignore other update types or setup calls
} catch (err) {
sdk.log.error('file.drop', `Error in database watcher: ${err.message}`);
}
};
sdk.db.watch(dbWatchCallback);
sdk.log.info('file.drop', 'Database watcher set up');
return;
}
} catch (err) {
// Database not ready yet, continue waiting
if (err.message && err.message.includes('Database not initialized')) {
retries--;
await new Promise(resolve => setTimeout(resolve, 1000)); // Wait 1 second
continue;
}
// Other error - log and return
sdk.log.error('file.drop', `Error setting up database watcher: ${err.message}`);
return;
}
break;
}
if (retries === 0) {
sdk.log.warn('file.drop', 'Database watcher setup timed out - database not available after 30 seconds');
}
}
function teardownDatabaseWatcher() {
if (dbWatchCallback) {
try {
sdk.db.unwatch(dbWatchCallback);
} catch (err) {
sdk.log.debug('file.drop', `Failed to unwatch DB: ${err.message}`);
}
dbWatchCallback = null;
}
}
module.exports = {
setupDatabaseWatcher,
teardownDatabaseWatcher
};