-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
79 lines (70 loc) · 2.38 KB
/
Copy pathindex.js
File metadata and controls
79 lines (70 loc) · 2.38 KB
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
const http = require('http');
const fs = require('fs');
const path = require('path');
const url = require('url');
// Calendar Data File
const DATA_DIR = path.join(__dirname, 'data');
const CALENDAR_FILE = path.join(DATA_DIR, 'calendar.ics');
// Ensure data folder and calendar file exist
function initializeCalendarFile() {
if (!fs.existsSync(DATA_DIR)) {
fs.mkdirSync(DATA_DIR, { recursive: true });
}
if (!fs.existsSync(CALENDAR_FILE)) {
const defaultCalendar = 'BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:-//CalDAV-NodeJS//EN\nCALSCALE:GREGORIAN\nEND:VCALENDAR';
fs.writeFileSync(CALENDAR_FILE, defaultCalendar, 'utf8');
}
}
// Initialize on startup
initializeCalendarFile();
// Helper Functions
function readCalendar() {
return fs.readFileSync(CALENDAR_FILE, 'utf8');
}
function writeCalendar(data) {
fs.writeFileSync(CALENDAR_FILE, data, 'utf8');
}
// Handle different HTTP methods and paths
function handleRequest(req, res) {
const method = req.method;
const pathname = url.parse(req.url).pathname;
if (pathname === '/.well-known/caldav') {
// CalDAV discovery
res.writeHead(301, { 'Location': '/caldav' });
res.end();
} else if (pathname === '/caldav') {
if (method === 'GET') {
// Get calendar data
const calendarData = readCalendar();
res.writeHead(200, { 'Content-Type': 'text/calendar' });
res.end(calendarData);
} else if (method === 'PUT') {
// Update an event or add a new one
let body = '';
req.on('data', chunk => { body += chunk; });
req.on('end', () => {
writeCalendar(body);
res.writeHead(204);
res.end();
});
} else if (method === 'DELETE') {
// Delete the calendar data (to simplify, we'll clear the file)
writeCalendar('BEGIN:VCALENDAR\nVERSION:2.0\nEND:VCALENDAR');
res.writeHead(204);
res.end();
} else {
res.writeHead(405);
res.end('Method Not Allowed');
}
} else {
res.writeHead(404);
res.end('Not Found');
}
}
// Create HTTP Server
const server = http.createServer(handleRequest);
// Start the server
const PORT = 8008;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/caldav`);
});