forked from ryanmwangi/CalMerger
Compare commits
6 commits
3b590958a0
...
441f4d2fb3
Author | SHA1 | Date | |
---|---|---|---|
441f4d2fb3 | |||
8c0de14d5f | |||
af980956cb | |||
5d7bdb6878 | |||
df37f35ace | |||
2a0fe0812e |
10 changed files with 1106 additions and 187 deletions
886
package-lock.json
generated
886
package-lock.json
generated
File diff suppressed because it is too large
Load diff
|
@ -23,6 +23,7 @@
|
|||
"devDependencies": {
|
||||
"@babel/preset-env": "^7.26.0",
|
||||
"@babel/register": "^7.25.9",
|
||||
"jest": "^29.7.0"
|
||||
"jest": "^29.7.0",
|
||||
"rewire": "^7.0.0"
|
||||
}
|
||||
}
|
||||
|
|
183
server.js
183
server.js
|
@ -1,183 +0,0 @@
|
|||
import express from 'express';
|
||||
import ICAL from 'ical.js';
|
||||
import fs from 'fs';
|
||||
import axios from 'axios';
|
||||
import path from 'path';
|
||||
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
|
||||
const MERGED_CALENDARS_DIR = path.join(process.cwd(), 'calendar');
|
||||
console.log(`Merged calendars directory: ${MERGED_CALENDARS_DIR} under ${process.cwd()}`);
|
||||
|
||||
// Ensure the merged calendars directory exists
|
||||
fs.mkdirSync(MERGED_CALENDARS_DIR, { recursive: true });
|
||||
|
||||
// Serve static files from the 'public' directory
|
||||
app.use(express.static(path.join(process.cwd(), 'public')));
|
||||
|
||||
// Utility to sanitize filenames
|
||||
const sanitizeFilename = (filename) => filename.replace(/[<>:"/\\|?* ]/g, '_');
|
||||
|
||||
// Fetch calendar data from URL or file
|
||||
async function fetchCalendarData(calendar) {
|
||||
const isFilePath = !calendar.url.startsWith('http');
|
||||
try {
|
||||
if (isFilePath) {
|
||||
console.log(`Fetching calendar data from file: ${calendar.url}`);
|
||||
return {
|
||||
data: fs.readFileSync(path.resolve(calendar.url), 'utf-8'),
|
||||
...calendar
|
||||
};
|
||||
} else {
|
||||
console.log(`Fetching calendar data from URL: ${calendar.url}`);
|
||||
const response = await axios.get(calendar.url);
|
||||
return { data: response.data, ...calendar };
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Error retrieving calendar from ${calendar.url}:`, error.message);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Create a top-level VCALENDAR component
|
||||
function 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
|
||||
function addEventsToCalendar(calendarComponent, results) {
|
||||
console.log(`Adding events to calendar component.`);
|
||||
results.forEach((result) => {
|
||||
// console.log(result.data);
|
||||
const parsed = ICAL.parse(result.data);
|
||||
const component = new ICAL.Component(parsed);
|
||||
|
||||
component.getAllSubcomponents('vevent').forEach((event) => {
|
||||
const vevent = new ICAL.Event(event);
|
||||
const newEvent = new ICAL.Component('vevent');
|
||||
|
||||
console.log(`Adding event: ${vevent.summary} to calendar.`);
|
||||
|
||||
// Get start and end dates directly
|
||||
const startDate = vevent.startDate && ICAL.Time.fromJSDate(vevent.startDate.toJSDate());
|
||||
const endDate = vevent.endDate && ICAL.Time.fromJSDate(vevent.endDate.toJSDate());
|
||||
|
||||
// Log the start and end dates
|
||||
console.log(`Start Date: ${startDate}`);
|
||||
console.log(`End Date: ${endDate}`);
|
||||
|
||||
// // 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
|
||||
// }
|
||||
|
||||
newEvent.updatePropertyWithValue('uid', vevent.uid);
|
||||
newEvent.updatePropertyWithValue('summary', result.override ? result.prefix : `${result.prefix} ${vevent.summary}`);
|
||||
newEvent.updatePropertyWithValue('dtstart', startDate);
|
||||
newEvent.updatePropertyWithValue('dtend', endDate);
|
||||
|
||||
calendarComponent.addSubcomponent(newEvent);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Save calendar data to file
|
||||
function saveCalendarFile(filename, content) {
|
||||
const filePath = path.join(MERGED_CALENDARS_DIR, filename);
|
||||
console.log(`Saving calendar data to file: ${filePath}`);
|
||||
fs.writeFileSync(filePath, content);
|
||||
return filePath;
|
||||
}
|
||||
|
||||
// Merge calendars endpoint
|
||||
app.post('/merge', async (req, res) => {
|
||||
const { linkGroupName, calendars } = req.body;
|
||||
|
||||
// Validate the input
|
||||
if (!linkGroupName || !Array.isArray(calendars) || calendars.length === 0) {
|
||||
console.warn('Invalid input provided for merge endpoint.');
|
||||
return res.status(400).json({ error: 'Invalid input. Please provide a linkGroupName and at least one calendar.' });
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
// Sanitize the linkGroupName to create a valid filename
|
||||
console.log(`Merging calendars for group: ${linkGroupName}`);
|
||||
const sanitizedLinkGroupName = sanitizeFilename(linkGroupName);
|
||||
const filename = `${sanitizedLinkGroupName}.ics`;
|
||||
|
||||
// Fetch calendar data
|
||||
const results = await Promise.all(calendars.map(fetchCalendarData));
|
||||
|
||||
// Generate merged calendar using ical.js
|
||||
const calendarComponent = createCalendarComponent(linkGroupName);
|
||||
addEventsToCalendar(calendarComponent, results);
|
||||
|
||||
// Save the calendar to a file
|
||||
saveCalendarFile(filename, calendarComponent.toString());
|
||||
|
||||
// Save the user input and sanitizedLinkGroupName in a separate JSON file
|
||||
saveCalendarFile(`${sanitizedLinkGroupName}.json`, JSON.stringify({ linkGroupName, calendars }, null, 2));
|
||||
|
||||
res.json({ url: `${req.protocol}://${req.get('host')}/calendar/${sanitizedLinkGroupName}` });
|
||||
} catch (error) {
|
||||
console.error('Error merging calendars:', error.message);
|
||||
res.status(500).json({ error: 'Failed to merge calendars' });
|
||||
}
|
||||
});
|
||||
|
||||
// Refresh calendar if outdated
|
||||
async function refreshCalendarData(calendarName) {
|
||||
const jsonFilePath = path.join(MERGED_CALENDARS_DIR, `${calendarName}.json`);
|
||||
console.log(`Refreshing calendar data for: ${calendarName}`);
|
||||
|
||||
// Read the JSON file to get the source URL and other details
|
||||
const { calendars } = JSON.parse(fs.readFileSync(jsonFilePath, 'utf-8'));
|
||||
|
||||
const results = await Promise.all(calendars.map(fetchCalendarData));
|
||||
const calendarComponent = createCalendarComponent(calendarName);
|
||||
addEventsToCalendar(calendarComponent, results);
|
||||
|
||||
saveCalendarFile(`${calendarName}.ics`, calendarComponent.toString());
|
||||
console.log('Calendar data refreshed and saved.');
|
||||
}
|
||||
|
||||
// Serve the merged calendar file and refresh if older than an hour
|
||||
app.get('/calendar/:name', async (req, res) => {
|
||||
const calendarName = req.params.name;
|
||||
const icsFilePath = path.join(MERGED_CALENDARS_DIR, `${calendarName}.ics`);
|
||||
|
||||
try {
|
||||
// Check if the .ics file exists
|
||||
console.log(`Serving calendar for: ${calendarName}`);
|
||||
if (fs.existsSync(icsFilePath)) {
|
||||
const stats = fs.statSync(icsFilePath);
|
||||
const isOutdated = new Date() - new Date(stats.mtime) > 60 * 60 * 1000;
|
||||
|
||||
if (isOutdated){
|
||||
console.log(`Calendar ${calendarName} is outdated. Refreshing...`);
|
||||
await refreshCalendarData(calendarName);
|
||||
|
||||
}
|
||||
|
||||
res.setHeader('Content-Type', 'text/calendar');
|
||||
res.sendFile(icsFilePath);
|
||||
|
||||
} else {
|
||||
res.status(404).json({ error: 'Calendar not found.' });
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error retrieving calendar data:', error.message);
|
||||
res.status(500).json({ error: 'Failed to retrieve calendar data.' });
|
||||
}
|
||||
});
|
||||
|
||||
export default app;
|
67
src/calendarUtil.js
Normal file
67
src/calendarUtil.js
Normal file
|
@ -0,0 +1,67 @@
|
|||
import ICAL from 'ical.js';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import axios from 'axios';
|
||||
|
||||
export const MERGED_CALENDARS_DIR = path.join(process.cwd(), 'calendar');
|
||||
|
||||
// Ensure the merged calendars directory exists
|
||||
fs.mkdirSync(MERGED_CALENDARS_DIR, { recursive: true });
|
||||
|
||||
// Utility to sanitize filenames
|
||||
export const sanitizeFilename = (filename) => filename.replace(/[<>:"/\\|?* ]/g, '_');
|
||||
|
||||
// Fetch calendar data from URL or file
|
||||
export async function fetchCalendarData(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) {
|
||||
throw new Error(`Error retrieving calendar from ${calendar.url}: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Create a top-level VCALENDAR component
|
||||
export function createCalendarComponent(name) {
|
||||
const calendarComponent = new ICAL.Component(['vcalendar', [], []]);
|
||||
calendarComponent.updatePropertyWithValue('prodid', '-//Your Product ID//EN');
|
||||
calendarComponent.updatePropertyWithValue('version', '2.0');
|
||||
calendarComponent.updatePropertyWithValue('name', name);
|
||||
return calendarComponent;
|
||||
}
|
||||
|
||||
// Add events to the calendar component
|
||||
export function addEventsToCalendar(calendarComponent, results) {
|
||||
results.forEach((result) => {
|
||||
const parsed = ICAL.parse(result.data);
|
||||
const component = new ICAL.Component(parsed);
|
||||
|
||||
component.getAllSubcomponents('vevent').forEach((event) => {
|
||||
const vevent = new ICAL.Event(event);
|
||||
const newEvent = new ICAL.Component('vevent');
|
||||
|
||||
const startDate = vevent.startDate && ICAL.Time.fromJSDate(vevent.startDate.toJSDate());
|
||||
const endDate = vevent.endDate && ICAL.Time.fromJSDate(vevent.endDate.toJSDate());
|
||||
|
||||
newEvent.updatePropertyWithValue('uid', vevent.uid);
|
||||
newEvent.updatePropertyWithValue('summary', `${result.prefix} ${vevent.summary}`);
|
||||
newEvent.updatePropertyWithValue('dtstart', startDate);
|
||||
newEvent.updatePropertyWithValue('dtend', endDate);
|
||||
|
||||
calendarComponent.addSubcomponent(newEvent);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Save calendar data to file
|
||||
export function saveCalendarFile(filename, content) {
|
||||
const filePath = path.join(MERGED_CALENDARS_DIR, filename);
|
||||
console.log(`Saving calendar data to file: ${filePath}`);
|
||||
fs.writeFileSync(filePath, content);
|
||||
return filePath;
|
||||
}
|
85
src/routes.js
Normal file
85
src/routes.js
Normal file
|
@ -0,0 +1,85 @@
|
|||
import express from 'express';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
import { fetchCalendarData, sanitizeFilename, createCalendarComponent, addEventsToCalendar, saveCalendarFile, MERGED_CALENDARS_DIR } from './calendarUtil.js';
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// Merge calendars endpoint
|
||||
router.post('/merge', async (req, res) => {
|
||||
const { linkGroupName, calendars } = req.body;
|
||||
|
||||
// Validate the input
|
||||
if (!linkGroupName || !Array.isArray(calendars) || calendars.length === 0) {
|
||||
return res.status(400).json({ error: 'Invalid input. Please provide a linkGroupName and at least one calendar.' });
|
||||
}
|
||||
|
||||
try {
|
||||
// Sanitize the linkGroupName to create a valid filename
|
||||
const sanitizedLinkGroupName = sanitizeFilename(linkGroupName);
|
||||
const filename = `${sanitizedLinkGroupName}.ics`;
|
||||
|
||||
// Fetch calendar data
|
||||
const results = await Promise.all(calendars.map(fetchCalendarData));
|
||||
|
||||
// Generate merged calendar using ical.js
|
||||
const calendarComponent = createCalendarComponent(linkGroupName);
|
||||
addEventsToCalendar(calendarComponent, results);
|
||||
|
||||
// Save the calendar to a file
|
||||
saveCalendarFile(filename, calendarComponent.toString());
|
||||
|
||||
// Save the user input and sanitizedLinkGroupName in a separate JSON file
|
||||
saveCalendarFile(`${sanitizedLinkGroupName}.json`, JSON.stringify({ linkGroupName, calendars }, null, 2));
|
||||
|
||||
res.json({ url: `${req.protocol}://${req.get('host')}/calendar/${sanitizedLinkGroupName}` });
|
||||
} catch (error) {
|
||||
console.error('Error merging calendars:', error.message);
|
||||
res.status(500).json({ error: 'Failed to merge calendars' });
|
||||
}
|
||||
});
|
||||
|
||||
// Refresh calendar if outdated
|
||||
async function refreshCalendarData(calendarName) {
|
||||
const jsonFilePath = path.join(MERGED_CALENDARS_DIR, `${calendarName}.json`);
|
||||
console.log(`Refreshing calendar data for: ${calendarName}`);
|
||||
|
||||
// Read the JSON file to get the source URL and other details
|
||||
const { calendars } = JSON.parse(fs.readFileSync(jsonFilePath, 'utf-8'));
|
||||
|
||||
const results = await Promise.all(calendars.map(fetchCalendarData));
|
||||
const calendarComponent = createCalendarComponent(calendarName);
|
||||
addEventsToCalendar(calendarComponent, results);
|
||||
|
||||
saveCalendarFile(`${calendarName}.ics`, calendarComponent.toString());
|
||||
console.log('Calendar data refreshed and saved.');
|
||||
}
|
||||
|
||||
// Serve the merged calendar file and refresh if older than an hour
|
||||
router.get('/calendar/:name', async (req, res) => {
|
||||
const calendarName = req.params.name;
|
||||
const icsFilePath = path.join(MERGED_CALENDARS_DIR, `${calendarName}.ics`);
|
||||
|
||||
try {
|
||||
// Check if the .ics file exists
|
||||
console.log(`Serving calendar for: ${calendarName}`);
|
||||
if (fs.existsSync(icsFilePath)) {
|
||||
const stats = fs.statSync(icsFilePath);
|
||||
const isOutdated = new Date() - new Date(stats.mtime) > 60 * 60 * 1000;
|
||||
|
||||
if (isOutdated){
|
||||
console.log(`Calendar ${calendarName} is outdated. Refreshing...`);
|
||||
await refreshCalendarData(calendarName);
|
||||
}
|
||||
res.setHeader('Content-Type', 'text/calendar');
|
||||
res.sendFile(icsFilePath);
|
||||
} else {
|
||||
res.status(404).json({ error: 'Calendar not found.' });
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error retrieving calendar data:', error.message);
|
||||
res.status(500).json({ error: 'Failed to retrieve calendar data.' });
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
14
src/server.js
Normal file
14
src/server.js
Normal file
|
@ -0,0 +1,14 @@
|
|||
import express from 'express';
|
||||
import path from 'path';
|
||||
import routes from './routes.js';
|
||||
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
|
||||
|
||||
// Serve static files from the 'public' directory
|
||||
app.use(express.static(path.join(process.cwd(), 'public')));
|
||||
app.use('/', routes);
|
||||
|
||||
|
||||
export default app;
|
|
@ -10,7 +10,7 @@ const EXPECTED_OUTPUTS_DIR = path.join(__dirname, 'expected_outputs');
|
|||
let server;
|
||||
process.chdir(__dirname)
|
||||
console.log(process.cwd());
|
||||
const app = require('../server').default;
|
||||
const app = require('../src/server').default;
|
||||
|
||||
describe('Calendar Merging API', () => {
|
||||
beforeAll(async () => {
|
||||
|
|
51
test/calendarUtil.test.js
Normal file
51
test/calendarUtil.test.js
Normal file
|
@ -0,0 +1,51 @@
|
|||
import fs from 'fs';
|
||||
import axios from 'axios';
|
||||
|
||||
// Describe the test suite for Calendar Utility Functions
|
||||
describe('Calendar Utility Functions', () => {
|
||||
// Declare variable to hold the functions we will be testing
|
||||
let fetchCalendarData;
|
||||
|
||||
beforeAll(async () => {
|
||||
const calendarUtilModule = await import('../src/calendarUtil.js');
|
||||
fetchCalendarData = calendarUtilModule.fetchCalendarData;
|
||||
});
|
||||
|
||||
// Describe a nested test suite for the 'fetchCalendarData' function
|
||||
describe('fetchCalendarData', () => {
|
||||
|
||||
// Test case: fetching data from a URL
|
||||
it('fetches data from a URL', async () => {
|
||||
const testCalendar = { url: 'https://calendar.google.com/calendar/ical/b4c66eb4bb2cc15257d071bab3f935385778b042112ea1aaedada47f3f1a6e3a%40group.calendar.google.com/public/basic.ics' };
|
||||
|
||||
// Mock the axios.get method to resolve with specific test data
|
||||
jest.spyOn(axios, 'get').mockResolvedValue({ data: 'test data' });
|
||||
|
||||
// Call the fetchCalendarData function with the test calendar object
|
||||
const result = await fetchCalendarData(testCalendar);
|
||||
|
||||
// Assert that the fetched result's data matches the expected test data
|
||||
expect(result.data).toBe('test data');
|
||||
|
||||
// Restore the original axios.get method after the test
|
||||
axios.get.mockRestore();
|
||||
});
|
||||
|
||||
// Test case: reading data from a file
|
||||
it('reads data from a file', async () => {
|
||||
const testCalendar = { url: './test_calendars/work_task_calendar.ics' };
|
||||
|
||||
// Mock the fs.readFileSync method to return specific test data
|
||||
jest.spyOn(fs, 'readFileSync').mockReturnValue('file data');
|
||||
|
||||
// Call the fetchCalendarData function with the test calendar object
|
||||
const result = await fetchCalendarData(testCalendar);
|
||||
|
||||
// Assert that the fetched result's data matches the expected file data
|
||||
expect(result.data).toBe('file data');
|
||||
|
||||
// Restore the original fs.readFileSync method after the test
|
||||
fs.readFileSync.mockRestore();
|
||||
});
|
||||
});
|
||||
});
|
|
@ -4,7 +4,7 @@ VERSION:2.0
|
|||
NAME:Override Calendar
|
||||
BEGIN:VEVENT
|
||||
UID:20231225T000000-001@example.com
|
||||
SUMMARY:Override Event
|
||||
SUMMARY:Override Event Christmas Day
|
||||
DTSTART:20231225T000000
|
||||
DTEND:20231226T000000
|
||||
END:VEVENT
|
||||
|
|
Loading…
Add table
Reference in a new issue