-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
executable file
Β·194 lines (158 loc) Β· 6.48 KB
/
server.js
File metadata and controls
executable file
Β·194 lines (158 loc) Β· 6.48 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
const express = require('express');
const cors = require('cors');
const { config, validateConfig } = require('./config');
const { logMessage } = require('./src/utils/logger');
const { requestLogger, errorHandler } = require('./src/middleware/logging');
const subscriptionManager = require('./src/managers/subscription-manager');
const graphAuth = require('./src/auth/graph-auth');
const { getGraphClient } = require('./src/services/graph-client');
const eventCache = require('./src/services/event-cache-db');
// Import routes
const homeRoutes = require('./src/routes/home');
const webhookRoutes = require('./src/routes/webhook');
const subscriptionRoutes = require('./src/routes/subscriptions');
const statusRoutes = require('./src/routes/status');
const calendarRoutes = require('./src/routes/calendar');
const healthRoutes = require('./src/routes/health');
const app = express();
// Middleware
app.use(cors());
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ extended: true }));
app.use(requestLogger);
// Routes
app.use('/', homeRoutes);
app.use('/webhook', webhookRoutes);
app.use('/subscriptions', subscriptionRoutes);
app.use('/status', statusRoutes);
app.use('/calendar', calendarRoutes);
app.use('/health', healthRoutes);
// Error handling
app.use(errorHandler);
async function cleanupOldSubscriptions() {
try {
logMessage('π§Ή Cleaning up old webhook subscriptions...');
const graphClient = await getGraphClient();
// Get all current subscriptions
const result = await graphClient.api('/subscriptions').get();
const subscriptions = result.value || [];
if (subscriptions.length === 0) {
logMessage('No existing subscriptions found');
// Still clear cache since we want a fresh start
subscriptionManager.clearCachedSubscription();
return;
}
logMessage(`Found ${subscriptions.length} existing subscriptions to clean up`);
// Delete all existing subscriptions
for (const sub of subscriptions) {
try {
logMessage(`Deleting subscription: ${sub.id.slice(-8)}`);
await graphClient.api(`/subscriptions/${sub.id}`).delete();
} catch (deleteError) {
logMessage(`Failed to delete subscription ${sub.id.slice(-8)}: ${deleteError.message}`, 'WARNING');
}
}
// Clear cached subscription since we deleted all
subscriptionManager.clearCachedSubscription();
logMessage('β
Old subscriptions cleaned up successfully');
} catch (error) {
logMessage(`Subscription cleanup failed: ${error.message}`, 'WARNING');
// Clear cache anyway to force fresh start
subscriptionManager.clearCachedSubscription();
}
}
async function syncExistingEvents() {
try {
logMessage('π Syncing existing events from Outlook calendar...');
const graphClient = await getGraphClient();
// Fetch events from 1 week ago to 1 year forward
const now = new Date();
const oneWeekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
const oneYearForward = new Date(now.getTime() + 365 * 24 * 60 * 60 * 1000);
const response = await graphClient
.api('/me/events')
.filter(`start/dateTime ge '${oneWeekAgo.toISOString()}' and start/dateTime le '${oneYearForward.toISOString()}'`)
.select('id,subject,start,end,location,body,bodyPreview,isAllDay,lastModifiedDateTime,createdDateTime,isCancelled')
.top(500)
.get();
const events = response.value || [];
logMessage(`Found ${events.length} events to cache`);
let cachedCount = 0;
for (const event of events) {
try {
eventCache.upsertEvent(event);
cachedCount++;
} catch (error) {
logMessage(`Failed to cache event ${event.id}: ${error.message}`, 'WARNING');
}
}
logMessage(`β
Successfully cached ${cachedCount} events`);
} catch (error) {
logMessage(`β οΈ Initial sync failed: ${error.message}`, 'WARNING');
logMessage('Service will continue with empty cache - webhooks will populate as events change', 'WARNING');
}
}
async function initializeServices() {
try {
// Validate configuration
validateConfig();
// Initialize event cache database
logMessage('Initializing event cache database...');
eventCache.initialize();
// Clean up old events (older than 1 year)
eventCache.cleanupOldEvents();
// Initialize auth
logMessage('Refreshing Microsoft Graph token...');
await graphAuth.getToken();
// Sync existing events to populate cache
await syncExistingEvents();
// Clean up old subscriptions first (this will clear cache)
await cleanupOldSubscriptions();
// Initialize subscription manager AFTER cleanup
subscriptionManager.initSubscription();
// Create new subscription (will create since we cleared cache)
const subscriptionResult = await subscriptionManager.manageSubscription();
if (!subscriptionResult) {
logMessage('β Failed to create webhook subscription', 'ERROR');
logMessage('Service will continue without webhooks - manual subscription creation may be needed', 'WARNING');
}
// Scan and move existing events that match criteria
const { scanAndMoveExistingEvents } = require('./src/services/event-processor');
await scanAndMoveExistingEvents();
logMessage('β
Services initialized successfully');
logMessage(`π
ICS feed available at: /calendar/{secret-token}.ics`);
// Start periodic health checks
logMessage('π Periodic health check scheduler started');
setInterval(async () => {
try {
await subscriptionManager.manageSubscription();
} catch (error) {
logMessage(`Health check error: ${error.message}`, 'ERROR');
}
}, 30 * 60 * 1000); // Every 30 minutes
} catch (error) {
logMessage(`Initialization failed: ${error.message}`, 'ERROR');
throw error;
}
}
// Graceful shutdown
process.on('SIGINT', () => {
logMessage('Shutting down...');
process.exit(0);
});
process.on('SIGTERM', () => {
logMessage('Shutting down...');
process.exit(0);
});
// Start server
app.listen(config.port, async () => {
logMessage(`Server running on port ${config.port}`);
try {
await initializeServices();
logMessage('β
Initialization completed successfully');
} catch (error) {
logMessage(`β Initialization failed: ${error.message}`, 'ERROR');
process.exit(1);
}
});
module.exports = app;