Spaces:
Sleeping
Sleeping
Download backend/src/services/ugaEventsService.js from edichat/edi.chat.test: direct link, hf CLI and curl.
- Browser
- Download file 17.4 kB
-
https://huggingface.co/spaces/edichat/edi.chat.test/resolve/main/backend/src/services/ugaEventsService.js
- Command line
-
hf download hf://spaces/edichat/edi.chat.test/backend/src/services/ugaEventsService.js
-
curl -L -o ugaEventsService.js https://huggingface.co/spaces/edichat/edi.chat.test/resolve/main/backend/src/services/ugaEventsService.js
17.4 kB
| const UGAEvent = require('../models/UGAEvent'); | |
| const ugaLocalistService = require('./ugaLocalistService'); | |
| const ugaEventsScrapingService = require('./ugaEventsScrapingService'); | |
| const logger = require('../utils/logger'); | |
| const { redisUtils } = require('../utils/redis'); | |
| const cron = require('node-cron'); | |
| class UGAEventsService { | |
| constructor() { | |
| this.syncInProgress = false; | |
| this.lastSyncTime = null; | |
| this.syncInterval = '0 */6 * * *'; // Every 6 hours | |
| this.cacheTimeout = 1800; // 30 minutes | |
| // Start scheduled sync | |
| this.initializeScheduledSync(); | |
| } | |
| // Initialize scheduled data synchronization | |
| initializeScheduledSync() { | |
| // Sync every 6 hours | |
| cron.schedule(this.syncInterval, async () => { | |
| logger.info('Starting scheduled UGA events sync'); | |
| await this.syncAllEvents(); | |
| }); | |
| // Initial sync on startup (delayed) | |
| setTimeout(async () => { | |
| logger.info('Starting initial UGA events sync'); | |
| await this.syncAllEvents(); | |
| }, 30000); // 30 second delay | |
| } | |
| // Main method to sync all events from all sources | |
| async syncAllEvents(forceSync = false) { | |
| if (this.syncInProgress && !forceSync) { | |
| logger.info('Sync already in progress, skipping'); | |
| return { success: false, message: 'Sync already in progress' }; | |
| } | |
| try { | |
| this.syncInProgress = true; | |
| logger.info('Starting comprehensive UGA events sync'); | |
| const results = { | |
| localist: { success: false, count: 0, errors: [] }, | |
| registrar: { success: false, count: 0, errors: [] }, | |
| totalProcessed: 0, | |
| totalSaved: 0, | |
| totalUpdated: 0, | |
| totalErrors: 0 | |
| }; | |
| // 1. Sync Localist events | |
| try { | |
| const localistResult = await this.syncLocalistEvents(); | |
| results.localist = localistResult; | |
| results.totalProcessed += localistResult.count; | |
| } catch (error) { | |
| logger.error('Error syncing Localist events:', error.message); | |
| results.localist.errors.push(error.message); | |
| } | |
| // 2. Sync Registrar data | |
| try { | |
| const registrarResult = await this.syncRegistrarEvents(); | |
| results.registrar = registrarResult; | |
| results.totalProcessed += registrarResult.count; | |
| } catch (error) { | |
| logger.error('Error syncing Registrar events:', error.message); | |
| results.registrar.errors.push(error.message); | |
| } | |
| // 3. Clean up old events | |
| const cleanupResult = await this.cleanupOldEvents(); | |
| results.cleanupCount = cleanupResult.deletedCount; | |
| // 4. Update cache | |
| await this.updateCache(); | |
| this.lastSyncTime = new Date(); | |
| results.syncTime = this.lastSyncTime; | |
| logger.info('UGA events sync completed', results); | |
| return { success: true, results }; | |
| } catch (error) { | |
| logger.error('Error in comprehensive sync:', error.message); | |
| return { success: false, error: error.message }; | |
| } finally { | |
| this.syncInProgress = false; | |
| } | |
| } | |
| // Sync events from Localist API | |
| async syncLocalistEvents() { | |
| logger.info('Syncing Localist events'); | |
| try { | |
| // Fetch upcoming events (next 6 months) | |
| const localistResult = await ugaLocalistService.fetchUpcomingEvents(180, 200); | |
| if (!localistResult.success) { | |
| return { success: false, count: 0, errors: [localistResult.error] }; | |
| } | |
| let savedCount = 0; | |
| let updatedCount = 0; | |
| const errors = []; | |
| for (const eventData of localistResult.data) { | |
| try { | |
| const result = await this.saveOrUpdateEvent(eventData); | |
| if (result.created) { | |
| savedCount++; | |
| } else if (result.updated) { | |
| updatedCount++; | |
| } | |
| } catch (error) { | |
| errors.push(`Error processing event ${eventData.title}: ${error.message}`); | |
| logger.warn('Error processing Localist event:', error.message); | |
| } | |
| } | |
| return { | |
| success: true, | |
| count: localistResult.data.length, | |
| saved: savedCount, | |
| updated: updatedCount, | |
| errors: errors | |
| }; | |
| } catch (error) { | |
| logger.error('Error in Localist sync:', error.message); | |
| return { success: false, count: 0, errors: [error.message] }; | |
| } | |
| } | |
| // Sync events from Registrar scraping | |
| async syncRegistrarEvents() { | |
| logger.info('Syncing Registrar events'); | |
| try { | |
| const registrarResult = await ugaEventsScrapingService.scrapeAllRegistrarData(); | |
| if (!registrarResult.success) { | |
| return { success: false, count: 0, errors: ['Registrar scraping failed'] }; | |
| } | |
| let savedCount = 0; | |
| let updatedCount = 0; | |
| const errors = []; | |
| for (const eventData of registrarResult.data) { | |
| try { | |
| // Ensure proper format for registrar events | |
| const formattedEvent = this.formatRegistrarEvent(eventData); | |
| const result = await this.saveOrUpdateEvent(formattedEvent); | |
| if (result.created) { | |
| savedCount++; | |
| } else if (result.updated) { | |
| updatedCount++; | |
| } | |
| } catch (error) { | |
| errors.push(`Error processing registrar event ${eventData.title}: ${error.message}`); | |
| logger.warn('Error processing Registrar event:', error.message); | |
| } | |
| } | |
| return { | |
| success: true, | |
| count: registrarResult.data.length, | |
| saved: savedCount, | |
| updated: updatedCount, | |
| errors: errors | |
| }; | |
| } catch (error) { | |
| logger.error('Error in Registrar sync:', error.message); | |
| return { success: false, count: 0, errors: [error.message] }; | |
| } | |
| } | |
| // Format registrar event data to match our schema | |
| formatRegistrarEvent(eventData) { | |
| return { | |
| ...eventData, | |
| location: eventData.location || { | |
| name: 'University of Georgia', | |
| isVirtual: false | |
| }, | |
| links: eventData.links || [], | |
| images: eventData.images || [], | |
| tags: eventData.tags || [], | |
| keywords: eventData.keywords || [], | |
| organizer: eventData.organizer || { | |
| name: 'UGA Office of the Registrar', | |
| department: 'Registrar' | |
| }, | |
| analytics: { | |
| views: 0, | |
| clicks: 0, | |
| shares: 0, | |
| registrations: 0 | |
| } | |
| }; | |
| } | |
| // Save or update an event in the database | |
| async saveOrUpdateEvent(eventData) { | |
| try { | |
| // Create a unique identifier for deduplication | |
| const uniqueKey = this.createEventUniqueKey(eventData); | |
| // Look for existing event | |
| let existingEvent = null; | |
| if (eventData.metadata?.sourceId) { | |
| existingEvent = await UGAEvent.findOne({ | |
| 'metadata.sourceId': eventData.metadata.sourceId, | |
| 'metadata.source': eventData.metadata.source | |
| }); | |
| } | |
| if (!existingEvent) { | |
| // Try to find by title and date (for events without sourceId) | |
| existingEvent = await UGAEvent.findOne({ | |
| title: eventData.title, | |
| startDate: { | |
| $gte: new Date(eventData.startDate.getTime() - 24 * 60 * 60 * 1000), // 1 day before | |
| $lte: new Date(eventData.startDate.getTime() + 24 * 60 * 60 * 1000) // 1 day after | |
| } | |
| }); | |
| } | |
| if (existingEvent) { | |
| // Update existing event | |
| const hasChanges = this.hasEventChanged(existingEvent, eventData); | |
| if (hasChanges) { | |
| Object.assign(existingEvent, eventData); | |
| existingEvent.metadata.lastUpdated = new Date(); | |
| await existingEvent.save(); | |
| logger.debug(`Updated event: ${eventData.title}`); | |
| return { updated: true, created: false, event: existingEvent }; | |
| } else { | |
| // Just update sync time | |
| existingEvent.metadata.lastSynced = new Date(); | |
| await existingEvent.save(); | |
| return { updated: false, created: false, event: existingEvent }; | |
| } | |
| } else { | |
| // Create new event | |
| const newEvent = new UGAEvent(eventData); | |
| await newEvent.save(); | |
| logger.debug(`Created event: ${eventData.title}`); | |
| return { updated: false, created: true, event: newEvent }; | |
| } | |
| } catch (error) { | |
| logger.error('Error saving/updating event:', error.message); | |
| throw error; | |
| } | |
| } | |
| // Create unique key for event deduplication | |
| createEventUniqueKey(eventData) { | |
| const title = eventData.title?.toLowerCase().replace(/\s+/g, '') || ''; | |
| const date = eventData.startDate?.toISOString().split('T')[0] || ''; | |
| const source = eventData.metadata?.source || ''; | |
| return `${source}-${title}-${date}`; | |
| } | |
| // Check if event data has changed | |
| hasEventChanged(existingEvent, newEventData) { | |
| const fields = ['title', 'description', 'startDate', 'endDate', 'location']; | |
| for (const field of fields) { | |
| if (field === 'startDate' || field === 'endDate') { | |
| const existingDate = existingEvent[field]?.getTime(); | |
| const newDate = newEventData[field]?.getTime(); | |
| if (existingDate !== newDate) { | |
| return true; | |
| } | |
| } else if (field === 'location') { | |
| const existingLocation = JSON.stringify(existingEvent[field] || {}); | |
| const newLocation = JSON.stringify(newEventData[field] || {}); | |
| if (existingLocation !== newLocation) { | |
| return true; | |
| } | |
| } else { | |
| if (existingEvent[field] !== newEventData[field]) { | |
| return true; | |
| } | |
| } | |
| } | |
| return false; | |
| } | |
| // Clean up old events | |
| async cleanupOldEvents() { | |
| try { | |
| const sixMonthsAgo = new Date(); | |
| sixMonthsAgo.setMonth(sixMonthsAgo.getMonth() - 6); | |
| const result = await UGAEvent.deleteMany({ | |
| endDate: { $lt: sixMonthsAgo }, | |
| eventType: { $ne: 'academic-calendar' } // Keep academic calendar events | |
| }); | |
| logger.info(`Cleaned up ${result.deletedCount} old events`); | |
| return result; | |
| } catch (error) { | |
| logger.error('Error cleaning up old events:', error.message); | |
| return { deletedCount: 0 }; | |
| } | |
| } | |
| // Update cache with fresh data | |
| async updateCache() { | |
| try { | |
| // Cache upcoming events | |
| const upcomingEvents = await this.getUpcomingEvents(50); | |
| await redisUtils.setex('uga:events:upcoming', this.cacheTimeout, upcomingEvents); | |
| // Cache important dates | |
| const importantDates = await this.getImportantDates(); | |
| await redisUtils.setex('uga:events:important', this.cacheTimeout, importantDates); | |
| // Cache events by category | |
| const categories = ['academics', 'athletics', 'arts', 'career-services', 'student-affairs']; | |
| for (const category of categories) { | |
| const categoryEvents = await this.getEventsByCategory(category, 30); | |
| await redisUtils.setex(`uga:events:category:${category}`, this.cacheTimeout, categoryEvents); | |
| } | |
| logger.info('Updated events cache'); | |
| } catch (error) { | |
| logger.error('Error updating cache:', error.message); | |
| } | |
| } | |
| // Public API methods | |
| // Get upcoming events | |
| async getUpcomingEvents(limit = 50, eventTypes = []) { | |
| try { | |
| const cacheKey = `uga:events:upcoming:${limit}:${eventTypes.join(',')}`; | |
| const cached = await redisUtils.get(cacheKey); | |
| if (cached) { | |
| return { success: true, data: cached, source: 'cache' }; | |
| } | |
| const events = await UGAEvent.findUpcoming(limit, eventTypes); | |
| await redisUtils.setex(cacheKey, 900, events); // 15 minutes cache | |
| return { success: true, data: events, source: 'database' }; | |
| } catch (error) { | |
| logger.error('Error getting upcoming events:', error.message); | |
| return { success: false, error: error.message }; | |
| } | |
| } | |
| // Get events by date range | |
| async getEventsByDateRange(startDate, endDate, options = {}) { | |
| try { | |
| const events = await UGAEvent.findByDateRange(startDate, endDate, options); | |
| return { success: true, data: events }; | |
| } catch (error) { | |
| logger.error('Error getting events by date range:', error.message); | |
| return { success: false, error: error.message }; | |
| } | |
| } | |
| // Get important dates | |
| async getImportantDates(semester = null, year = null) { | |
| try { | |
| const cacheKey = `uga:events:important:${semester}:${year}`; | |
| const cached = await redisUtils.get(cacheKey); | |
| if (cached) { | |
| return { success: true, data: cached, source: 'cache' }; | |
| } | |
| const events = await UGAEvent.findImportantDates(semester, year); | |
| await redisUtils.setex(cacheKey, 1800, events); // 30 minutes cache | |
| return { success: true, data: events, source: 'database' }; | |
| } catch (error) { | |
| logger.error('Error getting important dates:', error.message); | |
| return { success: false, error: error.message }; | |
| } | |
| } | |
| // Get events by category | |
| async getEventsByCategory(category, days = 30) { | |
| try { | |
| const startDate = new Date(); | |
| const endDate = new Date(); | |
| endDate.setDate(endDate.getDate() + days); | |
| const events = await UGAEvent.findByDateRange(startDate, endDate, { | |
| categories: [category] | |
| }); | |
| return { success: true, data: events }; | |
| } catch (error) { | |
| logger.error('Error getting events by category:', error.message); | |
| return { success: false, error: error.message }; | |
| } | |
| } | |
| // Get events by audience | |
| async getEventsByAudience(audience, limit = 20) { | |
| try { | |
| const events = await UGAEvent.findByAudience(audience, limit); | |
| return { success: true, data: events }; | |
| } catch (error) { | |
| logger.error('Error getting events by audience:', error.message); | |
| return { success: false, error: error.message }; | |
| } | |
| } | |
| // Search events | |
| async searchEvents(query, options = {}) { | |
| try { | |
| const events = await UGAEvent.searchEvents(query, options); | |
| return { success: true, data: events }; | |
| } catch (error) { | |
| logger.error('Error searching events:', error.message); | |
| return { success: false, error: error.message }; | |
| } | |
| } | |
| // Get event statistics | |
| async getEventStatistics() { | |
| try { | |
| const cacheKey = 'uga:events:statistics'; | |
| const cached = await redisUtils.get(cacheKey); | |
| if (cached) { | |
| return { success: true, data: cached, source: 'cache' }; | |
| } | |
| const now = new Date(); | |
| const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1); | |
| const endOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0); | |
| const stats = await UGAEvent.aggregate([ | |
| { | |
| $facet: { | |
| totalEvents: [{ $count: 'count' }], | |
| upcomingEvents: [ | |
| { $match: { startDate: { $gte: now }, status: 'published' } }, | |
| { $count: 'count' } | |
| ], | |
| thisMonthEvents: [ | |
| { $match: { startDate: { $gte: startOfMonth, $lte: endOfMonth } } }, | |
| { $count: 'count' } | |
| ], | |
| eventsByType: [ | |
| { $group: { _id: '$eventType', count: { $sum: 1 } } }, | |
| { $sort: { count: -1 } } | |
| ], | |
| eventsByCategory: [ | |
| { $group: { _id: '$category', count: { $sum: 1 } } }, | |
| { $sort: { count: -1 } } | |
| ], | |
| importantDates: [ | |
| { $match: { isImportantDate: true, startDate: { $gte: now } } }, | |
| { $count: 'count' } | |
| ] | |
| } | |
| } | |
| ]); | |
| const result = { | |
| totalEvents: stats[0].totalEvents[0]?.count || 0, | |
| upcomingEvents: stats[0].upcomingEvents[0]?.count || 0, | |
| thisMonthEvents: stats[0].thisMonthEvents[0]?.count || 0, | |
| importantDates: stats[0].importantDates[0]?.count || 0, | |
| eventsByType: stats[0].eventsByType, | |
| eventsByCategory: stats[0].eventsByCategory, | |
| lastSyncTime: this.lastSyncTime | |
| }; | |
| await redisUtils.setex(cacheKey, 1800, result); // 30 minutes cache | |
| return { success: true, data: result, source: 'database' }; | |
| } catch (error) { | |
| logger.error('Error getting event statistics:', error.message); | |
| return { success: false, error: error.message }; | |
| } | |
| } | |
| // Get sync status | |
| getSyncStatus() { | |
| return { | |
| syncInProgress: this.syncInProgress, | |
| lastSyncTime: this.lastSyncTime, | |
| nextSyncEstimate: this.getNextSyncTime() | |
| }; | |
| } | |
| // Calculate next sync time | |
| getNextSyncTime() { | |
| if (!this.lastSyncTime) { | |
| return new Date(); | |
| } | |
| const nextSync = new Date(this.lastSyncTime); | |
| nextSync.setHours(nextSync.getHours() + 6); // Every 6 hours | |
| return nextSync; | |
| } | |
| // Manual sync trigger | |
| async triggerManualSync() { | |
| if (this.syncInProgress) { | |
| return { success: false, message: 'Sync already in progress' }; | |
| } | |
| logger.info('Manual sync triggered'); | |
| return await this.syncAllEvents(true); | |
| } | |
| // Test all connections | |
| async testConnections() { | |
| const results = { | |
| localist: await ugaLocalistService.testConnection(), | |
| scraping: await ugaEventsScrapingService.testScrapingConnection(), | |
| database: await this.testDatabaseConnection() | |
| }; | |
| return results; | |
| } | |
| // Test database connection | |
| async testDatabaseConnection() { | |
| try { | |
| await UGAEvent.findOne().limit(1); | |
| return { success: true, message: 'Database connection successful' }; | |
| } catch (error) { | |
| return { success: false, error: error.message }; | |
| } | |
| } | |
| } | |
| module.exports = new UGAEventsService(); |