2024-09-30 12:55:03 +00:00
|
|
|
import express from 'express';
|
2024-11-04 12:21:13 +00:00
|
|
|
import ICAL from 'ical.js';
|
2024-09-30 12:55:03 +00:00
|
|
|
import fs from 'fs';
|
|
|
|
import axios from 'axios';
|
2024-10-24 12:02:01 +00:00
|
|
|
import path from 'path';
|
2024-09-30 12:55:03 +00:00
|
|
|
|
|
|
|
const app = express();
|
|
|
|
app.use(express.json());
|
|
|
|
|
2024-11-07 09:12:05 +00:00
|
|
|
const MERGED_CALENDARS_DIR = path.join(process.cwd(), 'calendar');
|
2024-11-06 19:58:29 +00:00
|
|
|
console.log(`Merged calendars directory: ${MERGED_CALENDARS_DIR} under ${process.cwd()}`);
|
2024-10-18 12:30:53 +00:00
|
|
|
|
|
|
|
// Ensure the merged calendars directory exists
|
2024-11-06 19:58:29 +00:00
|
|
|
fs.mkdirSync(MERGED_CALENDARS_DIR, { recursive: true });
|
2024-09-30 12:55:03 +00:00
|
|
|
|
2024-11-07 11:11:09 +00:00
|
|
|
// Serve static files
|
|
|
|
app.get('/script.js', (req, res) => res.sendFile('script.js', { root: '.' }));
|
|
|
|
app.get('/', (req, res) => res.sendFile('index.html', { root: '.' }));
|
2024-09-30 12:55:03 +00:00
|
|
|
|
2024-11-07 11:18:18 +00:00
|
|
|
// Utility to sanitize filenames
|
|
|
|
const sanitizeFilename = (filename) => filename.replace(/[<>:"/\\|?* ]/g, '_');
|
2024-10-28 12:02:13 +00:00
|
|
|
|
2024-11-07 11:20:56 +00:00
|
|
|
// Fetch calendar data from URL or file
|
|
|
|
const fetchCalendarData = async (calendar) => {
|
|
|
|
const isFilePath = !calendar.url.startsWith('http');
|
|
|
|
try {
|
|
|
|
if (isFilePath) {
|
2024-11-07 17:11:48 +00:00
|
|
|
console.log(`Fetching calendar data from file: ${calendar.url}`);
|
2024-11-07 11:20:56 +00:00
|
|
|
return {
|
|
|
|
data: fs.readFileSync(path.resolve(calendar.url), 'utf-8'),
|
|
|
|
...calendar
|
|
|
|
};
|
|
|
|
} else {
|
2024-11-07 17:11:48 +00:00
|
|
|
console.log(`Fetching calendar data from URL: ${calendar.url}`);
|
2024-11-07 11:20:56 +00:00
|
|
|
const response = await axios.get(calendar.url);
|
|
|
|
return { data: response.data, ...calendar };
|
|
|
|
}
|
|
|
|
} catch (error) {
|
2024-11-07 17:11:48 +00:00
|
|
|
console.error(`Error retrieving calendar from ${calendar.url}:`, error.message);
|
2024-11-07 11:20:56 +00:00
|
|
|
throw error;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2024-11-07 17:11:48 +00:00
|
|
|
// Create a top-level VCALENDAR component
|
|
|
|
const createCalendarComponent = (name) => {
|
|
|
|
console.log(`Creating calendar component for: ${name}`);
|
|
|
|
const calendarComponent = new ICAL.Component(['vcalendar', [], []]);
|
|
|
|
calendarComponent.updatePropertyWithValue('prodid', '-//Your Product ID//EN');
|
|
|
|
calendarComponent.updatePropertyWithValue('version', '2.0');
|
|
|
|
calendarComponent.updatePropertyWithValue('name', name); // calendar name
|
|
|
|
return calendarComponent;
|
|
|
|
};
|
|
|
|
|
|
|
|
// Add events to the calendar component
|
|
|
|
const addEventsToCalendar = (calendarComponent, results) => {
|
|
|
|
console.log(`Adding events to calendar component.`);
|
2024-11-07 11:23:24 +00:00
|
|
|
results.forEach((result) => {
|
2024-11-07 17:37:23 +00:00
|
|
|
console.log(result.data);
|
2024-11-07 11:23:24 +00:00
|
|
|
const parsed = ICAL.parse(result.data);
|
|
|
|
const component = new ICAL.Component(parsed);
|
2024-11-07 17:11:48 +00:00
|
|
|
|
2024-11-07 11:23:24 +00:00
|
|
|
component.getAllSubcomponents('vevent').forEach((event) => {
|
|
|
|
const vevent = new ICAL.Event(event);
|
2024-11-07 17:11:48 +00:00
|
|
|
const newEvent = new ICAL.Component('vevent');
|
2024-11-07 11:23:24 +00:00
|
|
|
|
2024-11-07 17:11:48 +00:00
|
|
|
console.log(`Adding event: ${vevent.summary} to calendar.`);
|
2024-11-07 23:21:22 +00:00
|
|
|
|
|
|
|
// Get start and end dates directly
|
2024-11-08 11:23:30 +00:00
|
|
|
const startDate = vevent.startDate && ICAL.Time.fromJSDate(vevent.startDate.toJSDate());
|
|
|
|
const endDate = vevent.endDate && ICAL.Time.fromJSDate(vevent.endDate.toJSDate());
|
2024-11-07 23:21:22 +00:00
|
|
|
|
|
|
|
// Log the start and end dates
|
|
|
|
console.log(`Start Date: ${startDate}`);
|
|
|
|
console.log(`End Date: ${endDate}`);
|
|
|
|
|
2024-11-08 11:23:30 +00:00
|
|
|
// // Check if the dates are valid
|
|
|
|
// if (!startDate || !endDate || !startDate.isValid() || !endDate.isValid()) {
|
|
|
|
// console.warn(`Invalid date for event: ${vevent.summary}`);
|
|
|
|
// return; // Skip or handle accordingly
|
|
|
|
// }
|
2024-11-07 23:21:22 +00:00
|
|
|
|
2024-11-07 17:11:48 +00:00
|
|
|
newEvent.updatePropertyWithValue('uid', vevent.uid);
|
|
|
|
newEvent.updatePropertyWithValue('summary', result.override ? result.prefix : `${result.prefix} ${vevent.summary}`);
|
2024-11-08 11:23:30 +00:00
|
|
|
newEvent.updatePropertyWithValue('dtstart', startDate);
|
|
|
|
newEvent.updatePropertyWithValue('dtend', endDate);
|
2024-11-07 17:11:48 +00:00
|
|
|
|
|
|
|
calendarComponent.addSubcomponent(newEvent);
|
2024-11-07 11:23:24 +00:00
|
|
|
});
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
2024-11-07 11:25:02 +00:00
|
|
|
// Save calendar data to file
|
|
|
|
const saveCalendarFile = (filename, content) => {
|
|
|
|
const filePath = path.join(MERGED_CALENDARS_DIR, filename);
|
2024-11-07 17:27:43 +00:00
|
|
|
console.log(`Saving calendar data to file: ${filePath}`);
|
2024-11-07 11:25:02 +00:00
|
|
|
fs.writeFileSync(filePath, content);
|
|
|
|
return filePath;
|
|
|
|
};
|
|
|
|
|
2024-10-28 11:54:33 +00:00
|
|
|
// Merge calendars endpoint
|
2024-09-30 12:55:03 +00:00
|
|
|
app.post('/merge', async (req, res) => {
|
2024-10-20 23:25:40 +00:00
|
|
|
const { linkGroupName, calendars } = req.body;
|
2024-09-30 12:55:03 +00:00
|
|
|
|
2024-11-07 11:33:24 +00:00
|
|
|
// Validate the input
|
|
|
|
if (!linkGroupName || !Array.isArray(calendars) || calendars.length === 0) {
|
2024-11-07 17:27:43 +00:00
|
|
|
console.warn('Invalid input provided for merge endpoint.');
|
2024-11-07 11:33:24 +00:00
|
|
|
return res.status(400).json({ error: 'Invalid input. Please provide a linkGroupName and at least one calendar.' });
|
|
|
|
}
|
2024-10-28 12:08:25 +00:00
|
|
|
|
2024-11-07 11:33:24 +00:00
|
|
|
try {
|
|
|
|
|
2024-10-28 12:05:49 +00:00
|
|
|
// Sanitize the linkGroupName to create a valid filename
|
2024-11-07 17:27:43 +00:00
|
|
|
console.log(`Merging calendars for group: ${linkGroupName}`);
|
2024-10-28 12:05:49 +00:00
|
|
|
const sanitizedLinkGroupName = sanitizeFilename(linkGroupName);
|
|
|
|
const filename = `${sanitizedLinkGroupName}.ics`;
|
|
|
|
|
2024-11-07 11:33:24 +00:00
|
|
|
// Fetch calendar data
|
|
|
|
const results = await Promise.all(calendars.map(fetchCalendarData));
|
|
|
|
|
2024-11-07 17:27:43 +00:00
|
|
|
// Generate merged calendar using ical.js
|
|
|
|
const calendarComponent = createCalendarComponent(linkGroupName);
|
|
|
|
addEventsToCalendar(calendarComponent, results);
|
2024-10-28 17:56:36 +00:00
|
|
|
|
2024-10-28 17:57:34 +00:00
|
|
|
// Save the calendar to a file
|
2024-11-07 17:27:43 +00:00
|
|
|
saveCalendarFile(filename, calendarComponent.toString());
|
2024-10-28 23:29:29 +00:00
|
|
|
|
2024-10-28 12:12:57 +00:00
|
|
|
// Save the user input and sanitizedLinkGroupName in a separate JSON file
|
2024-11-07 11:33:24 +00:00
|
|
|
saveCalendarFile(`${sanitizedLinkGroupName}.json`, JSON.stringify({ linkGroupName, calendars }, null, 2));
|
2024-10-18 13:43:13 +00:00
|
|
|
|
2024-10-28 12:12:57 +00:00
|
|
|
res.json({ url: `${req.protocol}://${req.get('host')}/calendar/${sanitizedLinkGroupName}` });
|
2024-09-30 12:55:03 +00:00
|
|
|
} catch (error) {
|
2024-11-07 17:37:23 +00:00
|
|
|
console.error('Error merging calendars:', error.message);
|
2024-09-30 12:55:03 +00:00
|
|
|
res.status(500).json({ error: 'Failed to merge calendars' });
|
|
|
|
}
|
|
|
|
});
|
2024-10-18 13:43:13 +00:00
|
|
|
|
2024-11-07 11:35:25 +00:00
|
|
|
// Refresh calendar if outdated
|
|
|
|
const refreshCalendarData = async (calendarName) => {
|
|
|
|
const jsonFilePath = path.join(MERGED_CALENDARS_DIR, `${calendarName}.json`);
|
2024-11-07 17:27:43 +00:00
|
|
|
console.log(`Refreshing calendar data for: ${calendarName}`);
|
|
|
|
|
2024-11-07 11:43:41 +00:00
|
|
|
// Read the JSON file to get the source URL and other details
|
2024-11-07 11:35:25 +00:00
|
|
|
const { calendars } = JSON.parse(fs.readFileSync(jsonFilePath, 'utf-8'));
|
|
|
|
|
|
|
|
const results = await Promise.all(calendars.map(fetchCalendarData));
|
2024-11-07 17:27:43 +00:00
|
|
|
const calendarComponent = createCalendarComponent(calendarName);
|
|
|
|
addEventsToCalendar(calendarComponent, results);
|
2024-11-07 11:35:25 +00:00
|
|
|
|
2024-11-07 17:27:43 +00:00
|
|
|
saveCalendarFile(`${calendarName}.ics`, calendarComponent.toString());
|
|
|
|
console.log('Calendar data refreshed and saved.');
|
2024-11-07 11:35:25 +00:00
|
|
|
};
|
|
|
|
|
2024-10-24 12:16:44 +00:00
|
|
|
// Serve the merged calendar file and refresh if older than an hour
|
|
|
|
app.get('/calendar/:name', async (req, res) => {
|
2024-10-24 12:18:02 +00:00
|
|
|
const calendarName = req.params.name;
|
2024-11-07 11:43:41 +00:00
|
|
|
const icsFilePath = path.join(MERGED_CALENDARS_DIR, `${calendarName}.ics`);
|
2024-10-24 12:16:44 +00:00
|
|
|
|
2024-10-24 12:20:52 +00:00
|
|
|
try {
|
|
|
|
// Check if the .ics file exists
|
2024-11-07 17:27:43 +00:00
|
|
|
console.log(`Serving calendar for: ${calendarName}`);
|
2024-10-24 12:20:52 +00:00
|
|
|
if (fs.existsSync(icsFilePath)) {
|
|
|
|
const stats = fs.statSync(icsFilePath);
|
2024-11-07 11:43:41 +00:00
|
|
|
const isOutdated = new Date() - new Date(stats.mtime) > 60 * 60 * 1000;
|
|
|
|
|
2024-11-07 17:27:43 +00:00
|
|
|
if (isOutdated){
|
|
|
|
console.log(`Calendar ${calendarName} is outdated. Refreshing...`);
|
|
|
|
await refreshCalendarData(calendarName);
|
|
|
|
|
|
|
|
}
|
2024-11-07 11:43:41 +00:00
|
|
|
|
|
|
|
res.setHeader('Content-Type', 'text/calendar');
|
|
|
|
res.sendFile(icsFilePath);
|
|
|
|
|
2024-10-24 12:33:58 +00:00
|
|
|
} else {
|
2024-11-07 11:43:41 +00:00
|
|
|
res.status(404).json({ error: 'Calendar not found.' });
|
2024-10-24 12:20:52 +00:00
|
|
|
}
|
2024-10-24 12:33:58 +00:00
|
|
|
|
2024-10-24 12:26:50 +00:00
|
|
|
} catch (error) {
|
2024-11-07 17:27:43 +00:00
|
|
|
console.error('Error retrieving calendar data:', error.message);
|
2024-10-24 12:26:50 +00:00
|
|
|
res.status(500).json({ error: 'Failed to retrieve calendar data.' });
|
2024-10-24 12:20:52 +00:00
|
|
|
}
|
2024-10-24 12:16:44 +00:00
|
|
|
});
|
|
|
|
|
2024-11-06 19:58:29 +00:00
|
|
|
export default app;
|