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-10-28 17:52:07 +00:00
|
|
|
import icalGenerator from 'ical-generator';
|
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) {
|
|
|
|
return {
|
|
|
|
data: fs.readFileSync(path.resolve(calendar.url), 'utf-8'),
|
|
|
|
...calendar
|
|
|
|
};
|
|
|
|
} else {
|
|
|
|
const response = await axios.get(calendar.url);
|
|
|
|
return { data: response.data, ...calendar };
|
|
|
|
}
|
|
|
|
} catch (error) {
|
|
|
|
console.error(`Error retrieving calendar from ${calendar.url}:`, error);
|
|
|
|
throw error;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
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
|
|
|
|
|
|
|
try {
|
2024-10-20 23:25:40 +00:00
|
|
|
// Validate the input
|
2024-10-21 12:33:57 +00:00
|
|
|
if (!linkGroupName || !calendars || !Array.isArray(calendars) || calendars.length === 0) {
|
|
|
|
return res.status(400).json({ error: 'Invalid input. Please provide a linkGroupName and at least one calendar.' });
|
2024-10-01 23:06:52 +00:00
|
|
|
}
|
2024-10-28 12:08:25 +00:00
|
|
|
|
2024-10-28 12:05:49 +00:00
|
|
|
// Sanitize the linkGroupName to create a valid filename
|
|
|
|
const sanitizedLinkGroupName = sanitizeFilename(linkGroupName);
|
|
|
|
const filename = `${sanitizedLinkGroupName}.ics`;
|
|
|
|
|
2024-11-04 10:46:44 +00:00
|
|
|
// Fetch calendar data from URLs or load from local files
|
2024-10-01 23:08:49 +00:00
|
|
|
const promises = calendars.map((calendar) => {
|
2024-11-04 10:46:44 +00:00
|
|
|
// Check if calendar URL is a file path or a URL
|
|
|
|
const isFilePath = !calendar.url.startsWith('http');
|
2024-11-04 10:51:00 +00:00
|
|
|
if (isFilePath) {
|
|
|
|
try{
|
|
|
|
// Read calendar data from local file
|
|
|
|
const data = fs.readFileSync(path.resolve(calendar.url), 'utf-8');
|
|
|
|
return Promise.resolve({
|
2024-11-04 10:56:48 +00:00
|
|
|
data: data,
|
2024-11-04 10:51:00 +00:00
|
|
|
prefix: calendar.prefix,
|
|
|
|
override: calendar.override,
|
|
|
|
});
|
2024-11-07 09:12:05 +00:00
|
|
|
} catch (error) {
|
|
|
|
console.error(`Error reading calendar file ${calendar.url}: ${error}`);
|
|
|
|
return Promise.reject(error)
|
2024-11-04 10:51:00 +00:00
|
|
|
}
|
|
|
|
} else {
|
2024-11-04 10:56:48 +00:00
|
|
|
// Fetch calendar data from URL
|
|
|
|
return axios.get(calendar.url)
|
|
|
|
.then((response) => {
|
|
|
|
return {
|
|
|
|
data: response.data,
|
|
|
|
prefix: calendar.prefix,
|
|
|
|
override: calendar.override,
|
|
|
|
};
|
|
|
|
})
|
|
|
|
.catch((error) => {
|
|
|
|
console.error(`Error fetching calendar from ${calendar.url}:`, error);
|
|
|
|
return null;
|
|
|
|
});
|
2024-11-04 10:51:00 +00:00
|
|
|
}
|
2024-10-01 23:08:49 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
const results = await Promise.all(promises);
|
2024-10-28 17:53:46 +00:00
|
|
|
// Create a new iCalendar instance
|
|
|
|
const calendar = icalGenerator({ name: linkGroupName });
|
|
|
|
|
2024-09-30 12:55:03 +00:00
|
|
|
// Parse calendar data
|
2024-11-07 09:12:05 +00:00
|
|
|
results.forEach((result) => {
|
2024-11-04 12:21:13 +00:00
|
|
|
const parsed = ICAL.parse(result.data);
|
2024-11-04 12:15:47 +00:00
|
|
|
const component = new ICAL.Component(parsed);
|
|
|
|
const events = component.getAllSubcomponents('vevent');
|
|
|
|
|
|
|
|
events.forEach((event) => {
|
|
|
|
const vevent = new ICAL.Event(event);
|
|
|
|
const start = vevent.startDate.toJSDate();
|
|
|
|
const end = vevent.endDate.toJSDate();
|
|
|
|
const summary = result.override ? result.prefix : `${result.prefix} ${vevent.summary}`;
|
|
|
|
|
|
|
|
if (vevent.startDate.isDate) {
|
|
|
|
calendar.createEvent({
|
|
|
|
start: start.toISOString().split('T')[0],
|
|
|
|
end: end.toISOString().split('T')[0],
|
|
|
|
summary: summary,
|
|
|
|
allDay: true,
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
calendar.createEvent({
|
|
|
|
start: start,
|
|
|
|
end: end,
|
|
|
|
summary: summary,
|
|
|
|
});
|
|
|
|
}
|
2024-10-01 23:10:37 +00:00
|
|
|
});
|
|
|
|
});
|
2024-09-30 12:55:03 +00:00
|
|
|
|
2024-10-28 17:56:36 +00:00
|
|
|
|
2024-10-28 17:57:34 +00:00
|
|
|
// Save the calendar to a file
|
2024-10-31 12:26:36 +00:00
|
|
|
const filePath = `${MERGED_CALENDARS_DIR}/${filename}`;
|
|
|
|
fs.writeFileSync(filePath, calendar.toString());
|
|
|
|
console.log(`Calendar saved to ${filePath}`);
|
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-10-28 12:10:34 +00:00
|
|
|
saveCalendarData(sanitizedLinkGroupName, linkGroupName, calendars);
|
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-10-31 12:27:46 +00:00
|
|
|
console.error('Error merging calendars:', error);
|
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-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-10-25 11:44:43 +00:00
|
|
|
const icsFilePath = path.resolve(MERGED_CALENDARS_DIR, `${calendarName}.ics`);
|
2024-10-25 11:45:34 +00:00
|
|
|
const jsonFilePath = path.resolve(MERGED_CALENDARS_DIR, `${calendarName}.json`);
|
2024-10-24 12:16:44 +00:00
|
|
|
|
2024-10-24 12:20:52 +00:00
|
|
|
try {
|
|
|
|
// Check if the .ics file exists
|
|
|
|
if (fs.existsSync(icsFilePath)) {
|
|
|
|
const stats = fs.statSync(icsFilePath);
|
|
|
|
const lastModified = new Date(stats.mtime);
|
|
|
|
const now = new Date();
|
2024-10-24 12:21:56 +00:00
|
|
|
// Check if the file is older than one hour
|
|
|
|
if (now - lastModified > 60 * 60 * 1000) {
|
|
|
|
console .log('Refreshing calendar data...');
|
2024-10-24 12:22:50 +00:00
|
|
|
|
|
|
|
// Read the JSON file to get the source URL and other details
|
|
|
|
const jsonData = JSON.parse(fs.readFileSync(jsonFilePath, 'utf8'));
|
2024-10-28 11:54:33 +00:00
|
|
|
const { calendars } = jsonData;
|
2024-10-24 12:25:02 +00:00
|
|
|
|
|
|
|
// Fetch calendar data for each merged calendar
|
|
|
|
const promises = calendars.map((calendar) => {
|
|
|
|
return axios.get(calendar.url)
|
|
|
|
.then((response) => {
|
|
|
|
return {
|
|
|
|
data: response.data,
|
|
|
|
prefix: calendar.prefix,
|
|
|
|
override: calendar.override,
|
|
|
|
};
|
|
|
|
})
|
|
|
|
.catch((error) => {
|
|
|
|
console.error(error);
|
|
|
|
return null;
|
|
|
|
});
|
|
|
|
});
|
2024-10-24 12:28:13 +00:00
|
|
|
|
|
|
|
const results = await Promise.all(promises);
|
|
|
|
// Filter out any failed requests
|
|
|
|
const validResults = results.filter((result) => result !== null);
|
2024-10-24 12:30:01 +00:00
|
|
|
|
2024-10-28 23:29:29 +00:00
|
|
|
// Create a new iCalendar instance
|
|
|
|
const calendar = icalGenerator({ name: calendarName });
|
|
|
|
|
2024-10-24 12:30:01 +00:00
|
|
|
// Parse calendar data
|
|
|
|
validResults.forEach((result) => {
|
2024-11-04 12:23:21 +00:00
|
|
|
const parsed = ICAL.parse(result.data);
|
|
|
|
const component = new ICAL.Component(parsed);
|
|
|
|
const events = component.getAllSubcomponents('vevent');
|
|
|
|
|
|
|
|
events.forEach((event) => {
|
|
|
|
const vevent = new ICAL.Event(event);
|
|
|
|
const start = vevent.startDate.toJSDate();
|
|
|
|
const end = vevent.endDate.toJSDate();
|
|
|
|
const summary = result.override ? result.prefix : `${result.prefix} ${vevent.summary}`;
|
2024-11-04 12:24:33 +00:00
|
|
|
|
|
|
|
if (vevent.startDate.isDate) {
|
|
|
|
calendar.createEvent({
|
|
|
|
start: start.toISOString().split('T')[0],
|
|
|
|
end: end.toISOString().split('T')[0],
|
|
|
|
summary: summary,
|
|
|
|
allDay: true,
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
calendar.createEvent({
|
|
|
|
start: start,
|
|
|
|
end: end,
|
|
|
|
summary: summary,
|
|
|
|
});
|
|
|
|
}
|
2024-11-04 12:23:21 +00:00
|
|
|
});
|
2024-10-24 12:30:01 +00:00
|
|
|
});
|
|
|
|
|
2024-10-28 23:31:58 +00:00
|
|
|
// Save the calendar to a file
|
|
|
|
fs.writeFileSync(icsFilePath, calendar.toString());
|
2024-10-24 12:33:58 +00:00
|
|
|
|
2024-10-28 23:35:10 +00:00
|
|
|
console.log('Calendar data refreshed.');
|
2024-10-24 12:21:56 +00:00
|
|
|
}
|
2024-10-24 12:33:58 +00:00
|
|
|
} else {
|
|
|
|
return 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:35:03 +00:00
|
|
|
// Return the contents of the .ics file
|
|
|
|
res.setHeader('Content-Type', 'text/calendar');
|
|
|
|
res.sendFile(icsFilePath);
|
|
|
|
|
2024-10-24 12:26:50 +00:00
|
|
|
} catch (error) {
|
|
|
|
console.error(error);
|
|
|
|
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-10-18 13:43:13 +00:00
|
|
|
|
2024-10-23 12:22:01 +00:00
|
|
|
//function to save calendar data to seperate .json files
|
|
|
|
function saveCalendarData(calendarId, linkGroupName, calendars) {
|
|
|
|
const calendarFile = `${MERGED_CALENDARS_DIR}/${calendarId}.json`;
|
|
|
|
const calendarData = {
|
|
|
|
id: calendarId,
|
|
|
|
linkGroupName: linkGroupName,
|
|
|
|
calendars: calendars
|
|
|
|
};
|
|
|
|
|
|
|
|
try {
|
|
|
|
fs.writeFileSync(calendarFile, JSON.stringify(calendarData, null, 2));
|
|
|
|
} catch (error) {
|
|
|
|
console.error('Error writing to calendar file:', error);
|
|
|
|
}
|
|
|
|
}
|
2024-10-19 14:41:06 +00:00
|
|
|
|
2024-11-06 19:58:29 +00:00
|
|
|
export default app;
|