Spaces:
Sleeping
Sleeping
Download backend/src/services/ugaLocalistService.js from edichat/edi.chat.test: direct link, hf CLI and curl.
- Browser
- Download file 19.7 kB
-
https://huggingface.co/spaces/edichat/edi.chat.test/resolve/main/backend/src/services/ugaLocalistService.js
- Command line
-
hf download hf://spaces/edichat/edi.chat.test/backend/src/services/ugaLocalistService.js
-
curl -L -o ugaLocalistService.js https://huggingface.co/spaces/edichat/edi.chat.test/resolve/main/backend/src/services/ugaLocalistService.js
19.7 kB
| const axios = require('axios'); | |
| const logger = require('../utils/logger'); | |
| const { redisUtils } = require('../utils/redis'); | |
| class UGALocalistService { | |
| constructor() { | |
| this.baseUrl = process.env.UGA_LOCALIST_API || 'https://calendar.uga.edu/api/2'; | |
| this.publicBaseUrl = 'https://calendar.uga.edu'; | |
| this.cacheTimeout = 900; // 15 minutes | |
| this.requestHeaders = { | |
| 'User-Agent': 'UGA-EdiChat/1.0 (+https://edi.chat)', | |
| 'Accept': 'application/json', | |
| 'Content-Type': 'application/json' | |
| }; | |
| // Common parameters for API requests | |
| this.defaultParams = { | |
| pp: 100, // events per page | |
| days: 365, // look ahead days | |
| format: 'json' | |
| }; | |
| } | |
| // Fetch events from Localist API | |
| async fetchEvents(options = {}) { | |
| try { | |
| const cacheKey = `localist:events:${JSON.stringify(options)}`; | |
| const cached = await redisUtils.get(cacheKey); | |
| if (cached) { | |
| return { success: true, data: cached, source: 'cache' }; | |
| } | |
| const params = { | |
| ...this.defaultParams, | |
| ...options | |
| }; | |
| logger.info('Fetching events from Localist API', { params }); | |
| const response = await axios.get(`${this.baseUrl}/events`, { | |
| params, | |
| headers: this.requestHeaders, | |
| timeout: 30000 | |
| }); | |
| if (response.data && response.data.events) { | |
| const processedEvents = this.processLocalistEvents(response.data.events); | |
| // Cache for 15 minutes | |
| await redisUtils.setex(cacheKey, this.cacheTimeout, processedEvents); | |
| logger.info(`Fetched ${processedEvents.length} events from Localist API`); | |
| return { | |
| success: true, | |
| data: processedEvents, | |
| source: 'api', | |
| pagination: response.data.page || {} | |
| }; | |
| } | |
| return { success: false, error: 'No events data in response' }; | |
| } catch (error) { | |
| logger.error('Error fetching Localist events:', error.message); | |
| // Try fallback RSS if API fails | |
| if (error.response?.status >= 400) { | |
| logger.info('Attempting RSS fallback for Localist events'); | |
| return await this.fetchEventsRSSFallback(options); | |
| } | |
| return { success: false, error: error.message }; | |
| } | |
| } | |
| // Fetch upcoming events | |
| async fetchUpcomingEvents(days = 30, limit = 50) { | |
| const options = { | |
| start: new Date().toISOString().split('T')[0], | |
| days: days, | |
| pp: limit, | |
| distinct: true | |
| }; | |
| return await this.fetchEvents(options); | |
| } | |
| // Fetch events by category | |
| async fetchEventsByCategory(categoryIds = [], days = 30) { | |
| if (!Array.isArray(categoryIds) || categoryIds.length === 0) { | |
| return await this.fetchUpcomingEvents(days); | |
| } | |
| const options = { | |
| filter: `categories: ${categoryIds.join(',')}`, | |
| days: days, | |
| distinct: true | |
| }; | |
| return await this.fetchEvents(options); | |
| } | |
| // Fetch events by keyword search | |
| async searchEvents(keyword, days = 90) { | |
| const options = { | |
| keyword: keyword, | |
| days: days, | |
| distinct: true | |
| }; | |
| return await this.fetchEvents(options); | |
| } | |
| // Fetch student-specific events | |
| async fetchStudentEvents(audience = 'students', days = 30) { | |
| const options = { | |
| audience: audience, | |
| days: days, | |
| distinct: true | |
| }; | |
| return await this.fetchEvents(options); | |
| } | |
| // Fetch academic events | |
| async fetchAcademicEvents(days = 365) { | |
| const academicKeywords = [ | |
| 'academic', 'registration', 'deadline', 'exam', 'final', | |
| 'orientation', 'advising', 'commencement', 'graduation' | |
| ]; | |
| const allEvents = []; | |
| // Fetch events for each academic keyword | |
| for (const keyword of academicKeywords) { | |
| try { | |
| const result = await this.searchEvents(keyword, days); | |
| if (result.success && result.data) { | |
| allEvents.push(...result.data); | |
| } | |
| } catch (error) { | |
| logger.warn(`Failed to fetch academic events for keyword: ${keyword}`, error); | |
| } | |
| } | |
| // Remove duplicates based on event ID | |
| const uniqueEvents = allEvents.filter((event, index, self) => | |
| index === self.findIndex(e => e.metadata?.sourceId === event.metadata?.sourceId) | |
| ); | |
| return { | |
| success: true, | |
| data: uniqueEvents, | |
| source: 'search-aggregation' | |
| }; | |
| } | |
| // RSS Fallback when API is unavailable | |
| async fetchEventsRSSFallback(options = {}) { | |
| try { | |
| const rssUrl = `${this.publicBaseUrl}/calendar.rss`; | |
| logger.info('Fetching events via RSS fallback'); | |
| const response = await axios.get(rssUrl, { | |
| headers: { | |
| 'User-Agent': this.requestHeaders['User-Agent'], | |
| 'Accept': 'application/rss+xml, application/xml, text/xml' | |
| }, | |
| timeout: 30000 | |
| }); | |
| // Parse RSS data (basic implementation) | |
| const events = this.parseRSSEvents(response.data); | |
| return { | |
| success: true, | |
| data: events, | |
| source: 'rss-fallback' | |
| }; | |
| } catch (error) { | |
| logger.error('RSS fallback also failed:', error.message); | |
| return { | |
| success: false, | |
| error: 'Both API and RSS fallback failed', | |
| fallback: this.getStaticEventsFallback() | |
| }; | |
| } | |
| } | |
| // Process raw Localist events into our schema format | |
| processLocalistEvents(localistEvents) { | |
| return localistEvents.map(event => this.transformLocalistEvent(event)); | |
| } | |
| // Transform single Localist event to our schema | |
| transformLocalistEvent(localistEvent) { | |
| try { | |
| const startDate = new Date(localistEvent.event.datetime_start); | |
| const endDate = localistEvent.event.datetime_end ? | |
| new Date(localistEvent.event.datetime_end) : null; | |
| // Determine event type and category | |
| const eventType = this.determineEventType(localistEvent); | |
| const category = this.determineCategory(localistEvent); | |
| const audience = this.determineAudience(localistEvent); | |
| // Process location | |
| const location = this.processLocation(localistEvent.event.location); | |
| return { | |
| title: localistEvent.event.title || 'Untitled Event', | |
| description: localistEvent.event.description_text || localistEvent.event.description || '', | |
| shortDescription: this.createShortDescription(localistEvent.event.description_text || localistEvent.event.description || ''), | |
| eventType: eventType, | |
| category: category, | |
| startDate: startDate, | |
| endDate: endDate, | |
| allDay: localistEvent.event.all_day || false, | |
| timezone: 'America/New_York', | |
| location: location, | |
| audience: audience, | |
| academic: this.extractAcademicInfo(localistEvent, startDate), | |
| priority: this.determinePriority(localistEvent), | |
| isImportantDate: this.isImportantDate(localistEvent), | |
| isFeatured: localistEvent.event.featured || false, | |
| // Contact and organizer info | |
| organizer: this.extractOrganizerInfo(localistEvent), | |
| // Media and links | |
| images: this.extractImages(localistEvent), | |
| links: this.extractLinks(localistEvent), | |
| // Tags and keywords | |
| tags: this.extractTags(localistEvent), | |
| keywords: this.extractKeywords(localistEvent), | |
| // Metadata | |
| metadata: { | |
| source: 'localist-api', | |
| sourceUrl: localistEvent.event.localist_url || `${this.publicBaseUrl}/event/${localistEvent.event.id}`, | |
| sourceId: localistEvent.event.id?.toString(), | |
| lastSynced: new Date(), | |
| localistData: { | |
| eventId: localistEvent.event.id, | |
| instanceId: localistEvent.event.instance_id, | |
| groupId: localistEvent.event.group_id | |
| } | |
| }, | |
| status: this.determineStatus(localistEvent), | |
| visibility: 'public', | |
| analytics: { | |
| views: 0, | |
| clicks: 0, | |
| shares: 0, | |
| registrations: 0 | |
| } | |
| }; | |
| } catch (error) { | |
| logger.warn('Error transforming Localist event:', error.message, { event: localistEvent.event?.id }); | |
| return null; | |
| } | |
| } | |
| // Determine event type from Localist data | |
| determineEventType(localistEvent) { | |
| const title = (localistEvent.event.title || '').toLowerCase(); | |
| const description = (localistEvent.event.description_text || localistEvent.event.description || '').toLowerCase(); | |
| const combined = title + ' ' + description; | |
| if (combined.includes('registration') || combined.includes('deadline')) { | |
| return 'registration-deadline'; | |
| } else if (combined.includes('orientation')) { | |
| return 'orientation'; | |
| } else if (combined.includes('commencement') || combined.includes('graduation')) { | |
| return 'commencement'; | |
| } else if (combined.includes('exam') || combined.includes('final')) { | |
| return 'exam-period'; | |
| } else if (combined.includes('lecture') || combined.includes('seminar')) { | |
| return 'lecture-seminar'; | |
| } else if (combined.includes('workshop')) { | |
| return 'workshop'; | |
| } else if (combined.includes('sports') || combined.includes('game') || combined.includes('athletic')) { | |
| return 'sports'; | |
| } else if (combined.includes('concert') || combined.includes('theater') || combined.includes('art')) { | |
| return 'arts-culture'; | |
| } else if (combined.includes('career') || combined.includes('job')) { | |
| return 'career-fair'; | |
| } else { | |
| return 'campus-event'; | |
| } | |
| } | |
| // Determine category from Localist data | |
| determineCategory(localistEvent) { | |
| const categories = localistEvent.event.filters?.event_types || []; | |
| const title = (localistEvent.event.title || '').toLowerCase(); | |
| // Map Localist categories to our categories | |
| const categoryMap = { | |
| 'academic': 'academics', | |
| 'athletics': 'athletics', | |
| 'arts': 'arts', | |
| 'career': 'career-services', | |
| 'dining': 'dining', | |
| 'housing': 'housing', | |
| 'recreation': 'recreation', | |
| 'research': 'research', | |
| 'student': 'student-affairs' | |
| }; | |
| // Check if any Localist categories match our mapping | |
| for (const cat of categories) { | |
| const catName = (cat.name || '').toLowerCase(); | |
| for (const [key, value] of Object.entries(categoryMap)) { | |
| if (catName.includes(key)) { | |
| return value; | |
| } | |
| } | |
| } | |
| // Fallback based on title keywords | |
| if (title.includes('academic') || title.includes('class') || title.includes('course')) { | |
| return 'academics'; | |
| } else if (title.includes('sport') || title.includes('game') || title.includes('athletic')) { | |
| return 'athletics'; | |
| } else if (title.includes('art') || title.includes('music') || title.includes('theater')) { | |
| return 'arts'; | |
| } else if (title.includes('career') || title.includes('job')) { | |
| return 'career-services'; | |
| } else { | |
| return 'student-affairs'; | |
| } | |
| } | |
| // Determine target audience | |
| determineAudience(localistEvent) { | |
| const audiences = localistEvent.event.filters?.audiences || []; | |
| const title = (localistEvent.event.title || '').toLowerCase(); | |
| const description = (localistEvent.event.description_text || '').toLowerCase(); | |
| const ugaAudience = []; | |
| // Map Localist audiences to our audiences | |
| audiences.forEach(aud => { | |
| const audName = (aud.name || '').toLowerCase(); | |
| if (audName.includes('student')) { | |
| ugaAudience.push('all-students'); | |
| } else if (audName.includes('faculty')) { | |
| ugaAudience.push('faculty'); | |
| } else if (audName.includes('staff')) { | |
| ugaAudience.push('staff'); | |
| } else if (audName.includes('graduate')) { | |
| ugaAudience.push('graduate'); | |
| } else if (audName.includes('undergraduate')) { | |
| ugaAudience.push('undergraduate'); | |
| } | |
| }); | |
| // Fallback based on content | |
| if (ugaAudience.length === 0) { | |
| if (title.includes('student') || description.includes('student')) { | |
| ugaAudience.push('all-students'); | |
| } else { | |
| ugaAudience.push('public'); | |
| } | |
| } | |
| return ugaAudience.length > 0 ? ugaAudience : ['public']; | |
| } | |
| // Process location information | |
| processLocation(localistLocation) { | |
| if (!localistLocation) { | |
| return { | |
| name: 'TBD', | |
| isVirtual: false | |
| }; | |
| } | |
| return { | |
| name: localistLocation.name || 'TBD', | |
| address: localistLocation.address || '', | |
| room: localistLocation.room || '', | |
| coordinates: { | |
| latitude: localistLocation.latitude || null, | |
| longitude: localistLocation.longitude || null | |
| }, | |
| isVirtual: (localistLocation.name || '').toLowerCase().includes('virtual') || | |
| (localistLocation.name || '').toLowerCase().includes('online') | |
| }; | |
| } | |
| // Extract academic information | |
| extractAcademicInfo(localistEvent, startDate) { | |
| const year = startDate.getFullYear(); | |
| const month = startDate.getMonth(); | |
| // Determine semester based on month | |
| let semester = 'fall'; | |
| let academicYear = year; | |
| if (month >= 0 && month <= 4) { // Jan-May | |
| semester = 'spring'; | |
| academicYear = year - 1; // Spring semester belongs to previous academic year | |
| } else if (month >= 5 && month <= 7) { // Jun-Aug | |
| semester = 'summer'; | |
| academicYear = year - 1; | |
| } else { // Sep-Dec | |
| semester = 'fall'; | |
| academicYear = year; | |
| } | |
| return { | |
| semester: semester, | |
| year: academicYear, | |
| colleges: [], | |
| departments: [], | |
| courses: [] | |
| }; | |
| } | |
| // Determine priority level | |
| determinePriority(localistEvent) { | |
| const title = (localistEvent.event.title || '').toLowerCase(); | |
| const featured = localistEvent.event.featured || false; | |
| if (featured || title.includes('deadline') || title.includes('registration')) { | |
| return 'critical'; | |
| } else if (title.includes('orientation') || title.includes('important')) { | |
| return 'high'; | |
| } else { | |
| return 'medium'; | |
| } | |
| } | |
| // Check if event is an important date | |
| isImportantDate(localistEvent) { | |
| const title = (localistEvent.event.title || '').toLowerCase(); | |
| const importantKeywords = [ | |
| 'deadline', 'registration', 'final', 'exam', 'commencement', | |
| 'orientation', 'move-in', 'payment due', 'application' | |
| ]; | |
| return importantKeywords.some(keyword => title.includes(keyword)); | |
| } | |
| // Extract organizer information | |
| extractOrganizerInfo(localistEvent) { | |
| const organizer = localistEvent.event.department || localistEvent.event.group; | |
| if (organizer) { | |
| return { | |
| name: organizer.name || '', | |
| email: organizer.email || '', | |
| phone: organizer.phone || '', | |
| department: organizer.name || '' | |
| }; | |
| } | |
| return {}; | |
| } | |
| // Extract images | |
| extractImages(localistEvent) { | |
| const images = []; | |
| if (localistEvent.event.photo_url) { | |
| images.push({ | |
| url: localistEvent.event.photo_url, | |
| alt: localistEvent.event.title || 'Event image', | |
| caption: '' | |
| }); | |
| } | |
| return images; | |
| } | |
| // Extract links | |
| extractLinks(localistEvent) { | |
| const links = []; | |
| if (localistEvent.event.localist_url) { | |
| links.push({ | |
| url: localistEvent.event.localist_url, | |
| text: 'View Event Details', | |
| type: 'website' | |
| }); | |
| } | |
| if (localistEvent.event.ticket_url) { | |
| links.push({ | |
| url: localistEvent.event.ticket_url, | |
| text: 'Get Tickets', | |
| type: 'tickets' | |
| }); | |
| } | |
| return links; | |
| } | |
| // Extract tags | |
| extractTags(localistEvent) { | |
| const tags = []; | |
| // Add event type tags | |
| if (localistEvent.event.filters?.event_types) { | |
| localistEvent.event.filters.event_types.forEach(type => { | |
| if (type.name) { | |
| tags.push(type.name.toLowerCase().replace(/\s+/g, '-')); | |
| } | |
| }); | |
| } | |
| return tags; | |
| } | |
| // Extract keywords | |
| extractKeywords(localistEvent) { | |
| const keywords = []; | |
| const title = localistEvent.event.title || ''; | |
| const description = localistEvent.event.description_text || ''; | |
| // Extract meaningful words from title and description | |
| const text = (title + ' ' + description).toLowerCase(); | |
| const words = text.match(/\b\w{4,}\b/g) || []; | |
| // Filter out common words and keep unique keywords | |
| const commonWords = ['this', 'that', 'with', 'from', 'they', 'have', 'will', 'been', 'their']; | |
| const filteredWords = [...new Set(words)].filter(word => | |
| !commonWords.includes(word) && word.length >= 4 | |
| ).slice(0, 10); | |
| return filteredWords; | |
| } | |
| // Determine event status | |
| determineStatus(localistEvent) { | |
| // Most Localist events are published if they appear in the API | |
| return 'published'; | |
| } | |
| // Create short description | |
| createShortDescription(description) { | |
| if (!description) return ''; | |
| // Remove HTML tags and limit to 200 characters | |
| const cleanDesc = description.replace(/<[^>]*>/g, '').trim(); | |
| return cleanDesc.length > 200 ? cleanDesc.substring(0, 197) + '...' : cleanDesc; | |
| } | |
| // Basic RSS parsing (fallback) | |
| parseRSSEvents(rssData) { | |
| // This is a simplified RSS parser | |
| // In production, you might want to use a proper RSS parsing library | |
| const events = []; | |
| try { | |
| // Extract basic event information from RSS XML | |
| const titleMatches = rssData.match(/<title><!\[CDATA\[(.*?)\]\]><\/title>/g) || []; | |
| const linkMatches = rssData.match(/<link>(.*?)<\/link>/g) || []; | |
| const descMatches = rssData.match(/<description><!\[CDATA\[(.*?)\]\]><\/description>/g) || []; | |
| for (let i = 1; i < titleMatches.length && i <= 20; i++) { // Skip first title (channel title) | |
| const title = titleMatches[i].replace(/<title><!\[CDATA\[/, '').replace(/\]\]><\/title>/, ''); | |
| const link = linkMatches[i]?.replace(/<link>/, '').replace(/<\/link>/, '') || ''; | |
| const description = descMatches[i]?.replace(/<description><!\[CDATA\[/, '').replace(/\]\]><\/description>/, '') || ''; | |
| events.push({ | |
| title: title, | |
| description: description, | |
| shortDescription: description.substring(0, 200), | |
| eventType: 'campus-event', | |
| category: 'student-affairs', | |
| startDate: new Date(), | |
| audience: ['all-students'], | |
| metadata: { | |
| source: 'rss-fallback', | |
| sourceUrl: link, | |
| lastSynced: new Date() | |
| }, | |
| status: 'published', | |
| visibility: 'public' | |
| }); | |
| } | |
| } catch (error) { | |
| logger.warn('Error parsing RSS data:', error.message); | |
| } | |
| return events; | |
| } | |
| // Static fallback events when all else fails | |
| getStaticEventsFallback() { | |
| const today = new Date(); | |
| const nextWeek = new Date(today.getTime() + 7 * 24 * 60 * 60 * 1000); | |
| return [ | |
| { | |
| title: 'UGA Events System Maintenance', | |
| description: 'The events calendar is temporarily unavailable. Please check back later.', | |
| eventType: 'announcement', | |
| category: 'student-affairs', | |
| startDate: today, | |
| endDate: nextWeek, | |
| audience: ['all-students'], | |
| metadata: { source: 'fallback' }, | |
| status: 'published', | |
| visibility: 'public' | |
| } | |
| ]; | |
| } | |
| // Test Localist API connectivity | |
| async testConnection() { | |
| try { | |
| const response = await axios.get(`${this.baseUrl}/events`, { | |
| params: { pp: 1, days: 1 }, | |
| headers: this.requestHeaders, | |
| timeout: 10000 | |
| }); | |
| return { | |
| success: true, | |
| status: response.status, | |
| message: 'Localist API is accessible' | |
| }; | |
| } catch (error) { | |
| return { | |
| success: false, | |
| error: error.message, | |
| code: error.code | |
| }; | |
| } | |
| } | |
| } | |
| module.exports = new UGALocalistService(); |