i-darrshan's picture
initial push of the update
8b105ad
const { google } = require('googleapis');
const { oAuth2Client } = require('../config/googleOAuth');
const { checkAndRefreshAccessToken } = require('../utils/refreshToken');
let holidays = [];
let allHolidayDates = [];
async function getIndiaTamilHolidays() {
try {
const userTokens = await checkAndRefreshAccessToken();
// Check if OAuth tokens are available
if (!userTokens || !userTokens.access_token) {
console.log("OAuth credentials missing. Please authorize the app first.");
return { error: 'OAuth credentials missing. Please authorize the app first.' };
}
// Set OAuth2 credentials
oAuth2Client.setCredentials(userTokens);
// Initialize Google Calendar API
const calendar = google.calendar({ version: 'v3', auth: oAuth2Client });
// Define the Indian Holidays calendar ID and time range
// const calendarId = 'en.indian#[email protected]';
const calendarId = '[email protected]'; //Tamil Nadu holidays
const currentYear = new Date().getFullYear(); //works in Indian server only mostly I guess
const timeMin = `${currentYear}-01-01T00:00:00Z`;
const timeMax = `${currentYear + 50}-12-31T23:59:59Z`;
// Fetch holiday events
const response = await calendar.events.list({
calendarId,
timeMin,
timeMax,
singleEvents: true,
orderBy: 'startTime',
});
// Extract and format holiday details
const holidays = [];
response.data.items.forEach(event => {
const summary = event.summary;
const startDate = event.start.date;
const endDate = event.end?.date || event.start.date;
// Handle single-day or multi-day holidays
const start = new Date(startDate);
const end = new Date(endDate);
// Iterate through all dates for multi-day holidays
for (let d = new Date(start); d < end; d.setDate(d.getDate() + 1)) {
console.log('Holiday:', summary, d);
holidays.push({
festival: summary,
date: d.toISOString().split('T')[0], // Format date as YYYY-MM-DD
});
}
});
return holidays;
} catch (error) {
console.error('Error fetching India holidays:', error.message);
throw error;
}
}
// Call the function to get tamil holidays
async function refreshHolidays() {
try {
holidays = await getIndiaTamilHolidays(); // Fetch the holidays
console.log('India Holidays:', holidays);
console.log('Total holidays:', holidays.length);
console.log('Last holiday:', holidays[holidays.length - 1]);
allHolidayDates = holidays.reduce((accumulator, holiday) => {
accumulator.push(holiday.date); // Collect all dates in an array
return accumulator;
}, []);
console.log(allHolidayDates);
// After the function finishes, set the next interval
setTimeout(refreshHolidays, 14 * 24 * 60 * 60 * 1000); // 14 days in ms
} catch (error) {
console.error('Failed to fetch holidays:', error);
// If there's an error, retry after a short delay
setTimeout(refreshHolidays, 10000); // Retry in 10 seconds
}
}
async function isHoliday(date) {
return allHolidayDates.includes(date);
}
module.exports = { getIndiaTamilHolidays, refreshHolidays, isHoliday };