const axios = require('axios'); const cheerio = require('cheerio'); const logger = require('../utils/logger'); const { redisUtils } = require('../utils/redis'); class UGAEventsScrapingService { constructor() { this.baseUrls = { registrar: 'https://reg.uga.edu', calendar: 'https://calendar.uga.edu', localist: 'https://calendar.uga.edu/api/2', studentAffairs: 'https://studentaffairs.uga.edu', athletics: 'https://georgiadogs.com' }; this.cacheTimeout = 1800; // 30 minutes this.requestHeaders = { 'User-Agent': 'Mozilla/5.0 (compatible; UGA-EdiChat/1.0; +https://edi.chat)', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.5', 'Accept-Encoding': 'gzip, deflate', 'DNT': '1', 'Connection': 'keep-alive', 'Upgrade-Insecure-Requests': '1' }; } // Scrape UGA Registrar Academic Calendar async scrapeRegistrarCalendar(year = new Date().getFullYear()) { try { const cacheKey = `registrar:calendar:${year}`; const cached = await redisUtils.get(cacheKey); if (cached) { return { success: true, data: cached, source: 'cache' }; } const url = `${this.baseUrls.registrar}/general-information/calendars/academic-calendars/`; logger.info(`Scraping Registrar calendar from: ${url}`); const response = await axios.get(url, { headers: this.requestHeaders, timeout: 30000 }); const $ = cheerio.load(response.data); const events = []; // Look for academic calendar tables or sections $('.calendar-section, .academic-calendar, .important-dates').each((index, element) => { const $section = $(element); const sectionTitle = $section.find('h2, h3, .section-title').first().text().trim(); // Extract semester information let semester = 'fall'; let academicYear = year; if (sectionTitle.toLowerCase().includes('spring')) { semester = 'spring'; academicYear = sectionTitle.includes('2025') ? 2024 : year - 1; } else if (sectionTitle.toLowerCase().includes('summer')) { semester = 'summer'; } else if (sectionTitle.toLowerCase().includes('fall')) { semester = 'fall'; } // Extract date entries $section.find('tr, .date-entry, .calendar-item').each((i, item) => { const $item = $(item); const dateText = $item.find('td:first-child, .date, .calendar-date').text().trim(); const eventText = $item.find('td:last-child, .event, .calendar-event').text().trim(); if (dateText && eventText && dateText.length > 3 && eventText.length > 3) { const parsedDate = this.parseAcademicDate(dateText, year); if (parsedDate) { events.push({ title: eventText, startDate: parsedDate, eventType: this.categorizeRegistrarEvent(eventText), category: 'academics', priority: this.determinePriority(eventText), isImportantDate: true, academic: { semester: semester, year: academicYear }, audience: ['all-students'], metadata: { source: 'registrar-scrape', sourceUrl: url, lastSynced: new Date() }, status: 'published', visibility: 'public' }); } } }); }); // Cache the results await redisUtils.setex(cacheKey, this.cacheTimeout, events); logger.info(`Scraped ${events.length} registrar calendar events`); return { success: true, data: events, source: 'scrape' }; } catch (error) { logger.error('Error scraping registrar calendar:', error.message); return { success: false, error: error.message, fallback: this.getRegistrarFallbackData(year) }; } } // Scrape UGA Key Dates page async scrapeKeyDates() { try { const cacheKey = 'registrar:key-dates'; const cached = await redisUtils.get(cacheKey); if (cached) { return { success: true, data: cached, source: 'cache' }; } const url = `${this.baseUrls.registrar}/general-information/calendars/key-dates/`; logger.info(`Scraping key dates from: ${url}`); const response = await axios.get(url, { headers: this.requestHeaders, timeout: 30000 }); const $ = cheerio.load(response.data); const events = []; // Extract key dates $('.key-dates-section, .semester-dates, .important-dates-list').each((index, section) => { const $section = $(section); $section.find('.date-item, tr, .deadline-item').each((i, item) => { const $item = $(item); const dateText = $item.find('.date, td:first-child').text().trim(); const eventText = $item.find('.event, .description, td:last-child').text().trim(); const deadlineType = $item.find('.type, .category').text().trim(); if (dateText && eventText) { const parsedDate = this.parseAcademicDate(dateText); if (parsedDate) { events.push({ title: eventText, startDate: parsedDate, eventType: 'registration-deadline', category: this.categorizeKeyDate(eventText, deadlineType), priority: 'high', isImportantDate: true, audience: ['all-students'], metadata: { source: 'registrar-scrape', sourceUrl: url, lastSynced: new Date() }, status: 'published', visibility: 'public' }); } } }); }); await redisUtils.setex(cacheKey, this.cacheTimeout, events); logger.info(`Scraped ${events.length} key dates`); return { success: true, data: events, source: 'scrape' }; } catch (error) { logger.error('Error scraping key dates:', error.message); return { success: false, error: error.message }; } } // Scrape UGA Registration Dates async scrapeRegistrationDates() { try { const cacheKey = 'registrar:registration-dates'; const cached = await redisUtils.get(cacheKey); if (cached) { return { success: true, data: cached, source: 'cache' }; } const url = `${this.baseUrls.registrar}/general-information/calendars/registration-dates/`; logger.info(`Scraping registration dates from: ${url}`); const response = await axios.get(url, { headers: this.requestHeaders, timeout: 30000 }); const $ = cheerio.load(response.data); const events = []; // Extract registration periods $('.registration-periods, .registration-schedule').each((index, section) => { const $section = $(section); $section.find('tr, .registration-period').each((i, row) => { const $row = $(row); const classification = $row.find('.classification, td:first-child').text().trim(); const dateRange = $row.find('.date-range, td:nth-child(2)').text().trim(); const time = $row.find('.time, td:last-child').text().trim(); if (classification && dateRange) { const dates = this.parseRegistrationDateRange(dateRange); if (dates.start) { events.push({ title: `Registration Opens - ${classification}`, description: `Registration period begins for ${classification.toLowerCase()} students`, startDate: dates.start, endDate: dates.end, eventType: 'registration-deadline', category: 'academics', priority: 'critical', isImportantDate: true, audience: this.mapClassificationToAudience(classification), metadata: { source: 'registrar-scrape', sourceUrl: url, lastSynced: new Date(), additionalInfo: { time: time } }, status: 'published', visibility: 'students-only' }); } } }); }); await redisUtils.setex(cacheKey, this.cacheTimeout, events); logger.info(`Scraped ${events.length} registration dates`); return { success: true, data: events, source: 'scrape' }; } catch (error) { logger.error('Error scraping registration dates:', error.message); return { success: false, error: error.message }; } } // Parse academic calendar dates parseAcademicDate(dateString, year = new Date().getFullYear()) { try { // Remove extra whitespace and normalize const cleanDate = dateString.replace(/\s+/g, ' ').trim(); // Common patterns in UGA calendar const patterns = [ // "March 25, 2024" or "March 25" /^([A-Za-z]+)\s+(\d{1,2}),?\s*(\d{4})?/, // "March 25-29, 2024" /^([A-Za-z]+)\s+(\d{1,2})-\d{1,2},?\s*(\d{4})?/, // "December 9-16, 2024" /^([A-Za-z]+)\s+(\d{1,2})-(\d{1,2}),?\s*(\d{4})?/ ]; for (const pattern of patterns) { const match = cleanDate.match(pattern); if (match) { const month = match[1]; const day = parseInt(match[2]); const eventYear = match[3] ? parseInt(match[3]) : year; // Convert month name to number const monthIndex = new Date(`${month} 1, 2000`).getMonth(); if (monthIndex >= 0 && day >= 1 && day <= 31) { return new Date(eventYear, monthIndex, day); } } } return null; } catch (error) { logger.debug(`Error parsing date: ${dateString}`, error); return null; } } // Parse registration date ranges parseRegistrationDateRange(dateRange) { try { // Patterns like "March 25 - April 15, 2024" const rangePattern = /^([A-Za-z]+\s+\d{1,2})\s*-\s*([A-Za-z]+\s+\d{1,2}),?\s*(\d{4})?/; const match = dateRange.match(rangePattern); if (match) { const startDateStr = match[1]; const endDateStr = match[2]; const year = match[3] ? parseInt(match[3]) : new Date().getFullYear(); const startDate = this.parseAcademicDate(`${startDateStr}, ${year}`); const endDate = this.parseAcademicDate(`${endDateStr}, ${year}`); return { start: startDate, end: endDate }; } // Single date const singleDate = this.parseAcademicDate(dateRange); return { start: singleDate, end: singleDate }; } catch (error) { logger.debug(`Error parsing date range: ${dateRange}`, error); return { start: null, end: null }; } } // Categorize registrar events categorizeRegistrarEvent(eventText) { const text = eventText.toLowerCase(); if (text.includes('registration') || text.includes('enroll')) { return 'registration-deadline'; } else if (text.includes('final') || text.includes('exam')) { return 'exam-period'; } else if (text.includes('break') || text.includes('holiday')) { return 'break'; } else if (text.includes('commencement') || text.includes('graduation')) { return 'commencement'; } else if (text.includes('orientation')) { return 'orientation'; } else { return 'academic-calendar'; } } // Categorize key dates categorizeKeyDate(eventText, deadlineType = '') { const text = (eventText + ' ' + deadlineType).toLowerCase(); if (text.includes('financial') || text.includes('billing') || text.includes('payment')) { return 'student-affairs'; } else if (text.includes('housing') || text.includes('residence')) { return 'housing'; } else if (text.includes('meal') || text.includes('dining')) { return 'dining'; } else if (text.includes('aid') || text.includes('scholarship')) { return 'student-affairs'; } else { return 'academics'; } } // Determine event priority determinePriority(eventText) { const text = eventText.toLowerCase(); if (text.includes('deadline') || text.includes('registration') || text.includes('final')) { return 'critical'; } else if (text.includes('orientation') || text.includes('advising')) { return 'high'; } else if (text.includes('break') || text.includes('holiday')) { return 'medium'; } else { return 'medium'; } } // Map classification to audience mapClassificationToAudience(classification) { const text = classification.toLowerCase(); if (text.includes('graduate')) { return ['graduate']; } else if (text.includes('senior')) { return ['senior']; } else if (text.includes('junior')) { return ['junior']; } else if (text.includes('sophomore')) { return ['sophomore']; } else if (text.includes('freshman')) { return ['freshman']; } else { return ['all-students']; } } // Get fallback data when scraping fails getRegistrarFallbackData(year = new Date().getFullYear()) { const currentYear = new Date().getFullYear(); const isCurrentAcademicYear = year >= currentYear - 1 && year <= currentYear + 1; if (!isCurrentAcademicYear) { return []; } // Provide basic academic calendar structure return [ { title: 'Fall Semester Classes Begin', startDate: new Date(year, 7, 19), // August 19 eventType: 'academic-calendar', category: 'academics', priority: 'high', isImportantDate: true, academic: { semester: 'fall', year: year }, audience: ['all-students'], metadata: { source: 'fallback' } }, { title: 'Fall Registration Begins', startDate: new Date(year, 2, 25), // March 25 eventType: 'registration-deadline', category: 'academics', priority: 'critical', isImportantDate: true, academic: { semester: 'fall', year: year }, audience: ['all-students'], metadata: { source: 'fallback' } }, { title: 'Spring Semester Classes Begin', startDate: new Date(year + 1, 0, 13), // January 13 eventType: 'academic-calendar', category: 'academics', priority: 'high', isImportantDate: true, academic: { semester: 'spring', year: year }, audience: ['all-students'], metadata: { source: 'fallback' } } ]; } // Utility method to test scraping capabilities async testScrapingConnection() { const tests = [ { name: 'Registrar Base', url: this.baseUrls.registrar }, { name: 'Calendar Base', url: this.baseUrls.calendar }, { name: 'Academic Calendar', url: `${this.baseUrls.registrar}/general-information/calendars/academic-calendars/` } ]; const results = {}; for (const test of tests) { try { const response = await axios.get(test.url, { headers: this.requestHeaders, timeout: 10000 }); results[test.name] = { status: 'success', statusCode: response.status, contentLength: response.data.length }; } catch (error) { results[test.name] = { status: 'error', error: error.message, code: error.code }; } } return results; } // Method to scrape all registrar data async scrapeAllRegistrarData() { const results = { calendar: await this.scrapeRegistrarCalendar(), keyDates: await this.scrapeKeyDates(), registration: await this.scrapeRegistrationDates() }; // Combine all events const allEvents = []; Object.values(results).forEach(result => { if (result.success && Array.isArray(result.data)) { allEvents.push(...result.data); } }); return { success: allEvents.length > 0, data: allEvents, details: results, summary: { totalEvents: allEvents.length, bySource: { calendar: results.calendar.success ? results.calendar.data.length : 0, keyDates: results.keyDates.success ? results.keyDates.data.length : 0, registration: results.registration.success ? results.registration.data.length : 0 } } }; } } module.exports = new UGAEventsScrapingService();