Spaces:
Sleeping
Sleeping
File size: 16,703 Bytes
7851df6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 | 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(); |