Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
704 lines (578 loc) · 22.1 KB
/
Copy pathserver.js
File metadata and controls
704 lines (578 loc) · 22.1 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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
const express = require('express');
const session = require('express-session');
const axios = require('axios');
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
require('dotenv').config();
const app = express();
const PORT = process.env.PORT || 3000;
// Simple database using JSON file
const DB_FILE = path.join(__dirname, 'database.json');
function readDatabase() {
try {
return JSON.parse(fs.readFileSync(DB_FILE, 'utf8'));
} catch (error) {
return { users: [], calendars: [], events: [], calendar_sync_state: {} };
}
}
function writeDatabase(data) {
fs.writeFileSync(DB_FILE, JSON.stringify(data, null, 2));
}
// Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static('public'));
// Session configuration with auto-generated secret
app.use(session({
secret: crypto.randomBytes(32).toString('hex'),
resave: false,
saveUninitialized: false,
cookie: { secure: false, maxAge: 24 * 60 * 60 * 1000 } // 24 hours
}));
// OAuth configuration
const GOOGLE_CONFIG = {
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
redirectUri: `http://localhost:${PORT}/auth/google/callback`,
scopes: ['https://www.googleapis.com/auth/calendar.readonly', 'https://www.googleapis.com/auth/userinfo.email'],
authUrl: 'https://accounts.google.com/o/oauth2/v2/auth',
tokenUrl: 'https://oauth2.googleapis.com/token',
userInfoUrl: 'https://www.googleapis.com/oauth2/v2/userinfo'
};
const MICROSOFT_CONFIG = {
clientId: process.env.MICROSOFT_CLIENT_ID,
clientSecret: process.env.MICROSOFT_CLIENT_SECRET,
redirectUri: `http://localhost:${PORT}/auth/microsoft/callback`,
scopes: ['https://graph.microsoft.com/calendars.read', 'https://graph.microsoft.com/user.read', 'offline_access'],
authUrl: 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize',
tokenUrl: 'https://login.microsoftonline.com/common/oauth2/v2.0/token',
userInfoUrl: 'https://graph.microsoft.com/v1.0/me'
};
// Attendee API configuration
const ATTENDEE_CONFIG = {
apiKey: process.env.ATTENDEE_API_KEY,
baseUrl: process.env.ATTENDEE_API_URL || 'https://app.attendee.dev',
webhookSecret: process.env.WEBHOOK_SECRET
};
// Helper function to make Attendee API requests
async function makeAttendeeRequest(endpoint, method = 'GET', data = null) {
const config = {
method,
url: `${ATTENDEE_CONFIG.baseUrl}${endpoint}`,
headers: {
'Authorization': `Token ${ATTENDEE_CONFIG.apiKey}`,
'Content-Type': 'application/json'
}
};
if (data) {
config.data = data;
}
console.log('Attendee API Request:', {method: config.method, url: config.url, data: config.data});
try {
const response = await axios(config);
return response.data;
} catch (error) {
console.error('Attendee API Error:', error.response?.data || error.message);
throw error;
}
}
// Helper function to create or update calendar in Attendee
async function createOrUpdateAttendeeCalendar(user) {
const deduplicationKey = `${user.email}-${user.provider}`;
const calendarData = {
client_id: user.provider === 'google' ? GOOGLE_CONFIG.clientId : MICROSOFT_CONFIG.clientId,
client_secret: user.provider === 'google' ? GOOGLE_CONFIG.clientSecret : MICROSOFT_CONFIG.clientSecret,
refresh_token: user.refreshToken,
platform: user.provider === 'microsoft' ? 'microsoft' : 'google',
deduplication_key: deduplicationKey,
metadata: {
user_email: user.email,
updated_at: new Date().toISOString()
}
};
try {
// Try to create new calendar first
return await makeAttendeeRequest('/api/v1/calendars', 'POST', calendarData);
} catch (error) {
// If calendar already exists, find it and update it
if (error.response?.status === 400 &&
Array.isArray(error.response?.data?.deduplication_key) &&
error.response.data.deduplication_key.some(msg => msg.includes('already exists'))) {
console.log('Calendar already exists, finding and updating existing calendar...');
// Get list of calendars to find the existing one
const calendarsResponse = await makeAttendeeRequest(
`/api/v1/calendars?deduplication_key=${encodeURIComponent(deduplicationKey)}`
);
if (calendarsResponse.results && calendarsResponse.results.length > 0) {
const existingCalendar = calendarsResponse.results[0];
// Update the existing calendar with new credentials
const updateData = {
client_secret: calendarData.client_secret,
refresh_token: calendarData.refresh_token,
metadata: calendarData.metadata
};
const updatedCalendar = await makeAttendeeRequest(
`/api/v1/calendars/${existingCalendar.id}`,
'PATCH',
updateData
);
console.log('Updated existing calendar:', updatedCalendar.id);
return updatedCalendar;
} else {
throw new Error('Calendar with deduplication key exists but could not be found');
}
} else {
throw error;
}
}
}
// Helper function to sync calendar events from Attendee
async function syncCalendarEvents(attendeeCalendarId, updatedAfter = null) {
let endpoint = `/api/v1/calendar_events?calendar_id=${attendeeCalendarId}`;
if (updatedAfter) {
endpoint += `&updated_after=${encodeURIComponent(updatedAfter)}`;
}
return await makeAttendeeRequest(endpoint);
}
// Helper function to sort keys in an object
function sortKeys(value) {
if (Array.isArray(value)) return value.map(sortKeys);
if (value && typeof value === "object" && !(value instanceof Date)) {
return Object.keys(value)
.sort()
.reduce((acc, k) => ({ ...acc, [k]: sortKeys(value[k]) }), {});
}
return value;
}
// Helper function to sign a payload with the webhook secret
function signPayload(payload, secretB64) {
const canonical = JSON.stringify(sortKeys(payload));
const secretBuf = Buffer.from(secretB64, "base64");
return crypto
.createHmac("sha256", secretBuf)
.update(canonical, "utf8")
.digest("base64");
}
// Helper function to verify webhook signature
function verifyWebhookSignature(payload, signature) {
if (!ATTENDEE_CONFIG.webhookSecret) {
console.warn('Webhook secret not configured, skipping signature verification');
return true;
}
const payloadJson = sortKeys(payload);
const expectedSignature = signPayload(payloadJson, ATTENDEE_CONFIG.webhookSecret);
return expectedSignature === signature;
}
// Helper function to complete OAuth login (shared by Google and Microsoft)
async function completeOAuthLogin(req, res, userInfo, provider, accessToken, refreshToken) {
// Store user info in session
req.session.user = {
email: userInfo.email || userInfo.mail || userInfo.userPrincipalName,
provider: provider,
accessToken: accessToken,
refreshToken: refreshToken
};
// Store in database
const db = readDatabase();
const existingUserIndex = db.users.findIndex(u => u.email === req.session.user.email);
if (existingUserIndex >= 0) {
db.users[existingUserIndex] = req.session.user;
} else {
db.users.push(req.session.user);
}
// Create calendar in Attendee API - REQUIRED for app functionality
try {
const attendeeCalendar = await createOrUpdateAttendeeCalendar(req.session.user);
console.log('Created Attendee calendar:', attendeeCalendar.id);
// Store calendar info
const deduplicationKey = `${req.session.user.email}-${req.session.user.provider}`;
const existingCalendarIndex = db.calendars.findIndex(c => c.deduplication_key === deduplicationKey);
const calendarData = {
attendee_id: attendeeCalendar.id,
user_email: req.session.user.email,
provider: req.session.user.provider,
deduplication_key: deduplicationKey,
state: 'connected',
connection_failure_data: null,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString()
};
if (existingCalendarIndex >= 0) {
db.calendars[existingCalendarIndex] = calendarData;
} else {
db.calendars.push(calendarData);
}
// Initialize sync state
if (!db.calendar_sync_state) {
db.calendar_sync_state = {};
}
if (!db.calendar_sync_state[attendeeCalendar.id]) {
db.calendar_sync_state[attendeeCalendar.id] = {
updated_after_for_next_sync: null,
last_sync_at: null
};
}
writeDatabase(db);
res.redirect('/dashboard');
} catch (error) {
console.error('Failed to create Attendee calendar:', error.message);
// Calendar creation is required - fail the login
const providerName = provider === 'google' ? 'Google' : 'Microsoft';
// Read error template and replace placeholders
const templatePath = path.join(__dirname, 'views', 'error.html');
let template = fs.readFileSync(templatePath, 'utf8');
template = template.replace('{{PROVIDER_NAME}}', providerName);
template = template.replace('{{ERROR_MESSAGE}}', error.response?.data?.detail || error.message);
return res.status(500).send(template);
}
}
// Routes
app.get('/', (req, res) => {
if (req.session.user) {
res.redirect('/dashboard');
return;
}
// Read and send login template
const templatePath = path.join(__dirname, 'views', 'login.html');
const template = fs.readFileSync(templatePath, 'utf8');
res.send(template);
});
// Google OAuth flow
app.get('/auth/google', (req, res) => {
const state = crypto.randomBytes(32).toString('hex');
req.session.oauthState = state;
const authUrl = `${GOOGLE_CONFIG.authUrl}?` + new URLSearchParams({
client_id: GOOGLE_CONFIG.clientId,
redirect_uri: GOOGLE_CONFIG.redirectUri,
scope: GOOGLE_CONFIG.scopes.join(' '),
response_type: 'code',
state: state,
access_type: 'offline',
prompt: 'consent'
});
res.redirect(authUrl);
});
// Microsoft OAuth flow
app.get('/auth/microsoft', (req, res) => {
const state = crypto.randomBytes(32).toString('hex');
req.session.oauthState = state;
const authUrl = `${MICROSOFT_CONFIG.authUrl}?` + new URLSearchParams({
client_id: MICROSOFT_CONFIG.clientId,
redirect_uri: MICROSOFT_CONFIG.redirectUri,
scope: MICROSOFT_CONFIG.scopes.join(' '),
response_type: 'code',
state: state,
response_mode: 'query'
});
res.redirect(authUrl);
});
// Google OAuth callback
app.get('/auth/google/callback', async (req, res) => {
const { code, state } = req.query;
if (!code || state !== req.session.oauthState) {
return res.status(400).send('Invalid OAuth callback');
}
try {
// Exchange code for tokens
const tokenResponse = await axios.post(GOOGLE_CONFIG.tokenUrl, {
client_id: GOOGLE_CONFIG.clientId,
client_secret: GOOGLE_CONFIG.clientSecret,
code: code,
grant_type: 'authorization_code',
redirect_uri: GOOGLE_CONFIG.redirectUri
});
const { access_token, refresh_token } = tokenResponse.data;
// Get user info
const userResponse = await axios.get(GOOGLE_CONFIG.userInfoUrl, {
headers: { Authorization: `Bearer ${access_token}` }
});
const userInfo = userResponse.data;
// Complete OAuth login using shared function
await completeOAuthLogin(req, res, userInfo, 'google', access_token, refresh_token);
} catch (error) {
console.error('Google OAuth error:', error.response?.data || error.message);
res.status(500).send('Authentication failed');
}
});
// Microsoft OAuth callback
app.get('/auth/microsoft/callback', async (req, res) => {
const { code, state } = req.query;
if (!code || state !== req.session.oauthState) {
return res.status(400).send('Invalid OAuth callback');
}
try {
// Exchange code for tokens
const tokenResponse = await axios.post(MICROSOFT_CONFIG.tokenUrl, new URLSearchParams({
client_id: MICROSOFT_CONFIG.clientId,
client_secret: MICROSOFT_CONFIG.clientSecret,
code: code,
grant_type: 'authorization_code',
redirect_uri: MICROSOFT_CONFIG.redirectUri
}), {
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
const { access_token, refresh_token } = tokenResponse.data;
// Get user info
const userResponse = await axios.get(MICROSOFT_CONFIG.userInfoUrl, {
headers: { Authorization: `Bearer ${access_token}` }
});
const userInfo = userResponse.data;
// Complete OAuth login using shared function
await completeOAuthLogin(req, res, userInfo, 'microsoft', access_token, refresh_token);
} catch (error) {
console.error('Microsoft OAuth error:', error.response?.data || error.message);
res.status(500).send('Authentication failed');
}
});
// Dashboard route
app.get('/dashboard', (req, res) => {
if (!req.session.user) {
res.redirect('/');
return;
}
// Read template file and replace placeholders
const templatePath = path.join(__dirname, 'views', 'dashboard.html');
let template = fs.readFileSync(templatePath, 'utf8');
// Replace template variables
template = template.replace('{{USER_EMAIL}}', req.session.user.email);
template = template.replace('{{USER_PROVIDER}}', req.session.user.provider);
res.send(template);
});
// Webhook endpoint for Attendee callbacks
app.post('/webhook/attendee', async (req, res) => {
try {
const payload = req.body;
const signature = req.headers['x-webhook-signature'];
// Verify webhook signature
if (!verifyWebhookSignature(payload, signature)) {
console.error('Invalid webhook signature payload', payload);
return res.status(400).send('Invalid signature');
}
console.log('Received Attendee webhook:', payload.trigger);
// Handle calendar events update webhook
if (payload.trigger === 'calendar.events_update') {
await handleCalendarEventsUpdate(payload);
}
// Handle calendar state change webhook
if (payload.trigger === 'calendar.state_change') {
await handleCalendarStateChange(payload);
}
res.status(200).send('Webhook processed successfully');
} catch (error) {
console.error('Webhook processing error:', error);
res.status(500).send('Webhook processing failed');
}
});
// Handle calendar state change webhook
async function handleCalendarStateChange(payload) {
const calendarId = payload.calendar_id;
const newState = payload.data.state;
const connectionFailureData = payload.data.connection_failure_data;
console.log(`Calendar ${calendarId} state changed to: ${newState}`);
try {
const db = readDatabase();
// Find and update the calendar in our database
const calendarIndex = db.calendars.findIndex(c => c.attendee_id === calendarId);
if (calendarIndex >= 0) {
db.calendars[calendarIndex].state = newState;
db.calendars[calendarIndex].connection_failure_data = connectionFailureData;
db.calendars[calendarIndex].updated_at = new Date().toISOString();
// If disconnected, clear events for this calendar to avoid showing stale data
if (newState === 'disconnected') {
console.error('Calendar disconnected, clearing events:', connectionFailureData);
db.events = db.events.filter(e => e.calendar_id !== calendarId);
// Clear sync state
if (db.calendar_sync_state[calendarId]) {
delete db.calendar_sync_state[calendarId];
}
}
writeDatabase(db);
console.log(`Updated calendar ${calendarId} state to ${newState}`);
} else {
console.warn(`Calendar ${calendarId} not found in local database`);
}
} catch (error) {
console.error('Failed to handle calendar state change:', error);
}
}
// Handle calendar events update webhook
async function handleCalendarEventsUpdate(payload) {
const calendarId = payload.calendar_id;
try {
const db = readDatabase();
const syncState = db.calendar_sync_state[calendarId] || {};
// Capture sync start time before making the API call
const syncStartTime = new Date().toISOString();
// Sync events from Attendee API
const eventsResponse = await syncCalendarEvents(
calendarId,
syncState.updated_after_for_next_sync
);
if (eventsResponse.results) {
// Process and store events
for (const event of eventsResponse.results) {
const existingEventIndex = db.events.findIndex(e => e.attendee_id === event.id);
const eventData = {
attendee_id: event.id,
calendar_id: calendarId,
platform_uuid: event.platform_uuid,
name: event.name,
meeting_url: event.meeting_url,
start_time: event.start_time,
end_time: event.end_time,
is_deleted: event.is_deleted,
attendees: event.attendees,
created_at: event.created_at,
updated_at: event.updated_at,
bot_join_enabled: false, // Default to false, user can enable later
bot_id: null // Track the Attendee bot ID when created
};
if (existingEventIndex >= 0) {
// Preserve existing bot information when updating
eventData.bot_join_enabled = db.events[existingEventIndex].bot_join_enabled || false;
eventData.bot_id = db.events[existingEventIndex].bot_id || null;
db.events[existingEventIndex] = eventData;
} else {
db.events.push(eventData);
}
}
// Update sync state with the sync start time
db.calendar_sync_state[calendarId] = {
updated_after_for_next_sync: syncStartTime,
last_sync_at: new Date().toISOString()
};
writeDatabase(db);
console.log(`Synced ${eventsResponse.results.length} events for calendar ${calendarId}`);
}
} catch (error) {
console.error('Failed to sync calendar events:', error);
}
}
// API endpoint to get calendar events for the current user
app.get('/api/events', (req, res) => {
if (!req.session.user) {
return res.status(401).json({ error: 'Not authenticated' });
}
const db = readDatabase();
const deduplicationKey = `${req.session.user.email}-${req.session.user.provider}`;
// Find user's calendar
const userCalendar = db.calendars.find(c => c.deduplication_key === deduplicationKey);
if (!userCalendar) {
return res.json({ events: [] });
}
// Get events for this calendar that have meeting URLs
const userEvents = db.events
.filter(e => e.calendar_id === userCalendar.attendee_id && !e.is_deleted && e.meeting_url)
.sort((a, b) => new Date(a.start_time) - new Date(b.start_time));
// Check if calendar is connected
const calendarState = userCalendar.state || 'connected';
const connectionFailureData = userCalendar.connection_failure_data || null;
res.json({
events: userEvents,
calendar_state: calendarState,
connection_failure_data: connectionFailureData
});
});
// API endpoint to add bot to an event
app.post('/api/events/:eventId/add-bot', async (req, res) => {
if (!req.session.user) {
return res.status(401).json({ error: 'Not authenticated' });
}
const eventId = req.params.eventId;
const db = readDatabase();
const eventIndex = db.events.findIndex(e => e.attendee_id === eventId);
if (eventIndex === -1) {
return res.status(404).json({ error: 'Event not found' });
}
const event = db.events[eventIndex];
// Check if bot already exists
if (event.bot_id) {
return res.status(400).json({ error: 'Bot already exists for this event' });
}
// Check if event has a meeting URL
if (!event.meeting_url) {
return res.status(400).json({ error: 'Event has no meeting URL' });
}
try {
// Create bot using Attendee API
const botData = {
calendar_event_id: eventId,
bot_name: `Calendar Bot - ${req.session.user.email}`,
metadata: {
user_email: req.session.user.email,
event_id: eventId,
created_via: 'calendar_integration'
}
};
const bot = await makeAttendeeRequest('/api/v1/bots', 'POST', botData);
// Update event with bot ID
db.events[eventIndex].bot_join_enabled = true;
db.events[eventIndex].bot_id = bot.id;
writeDatabase(db);
res.json({
success: true,
bot_id: bot.id,
message: 'Bot scheduled successfully'
});
} catch (error) {
console.error('Failed to create bot:', error);
res.status(500).json({
error: 'Failed to create bot: ' + (error.response?.data?.detail || error.message)
});
}
});
// API endpoint to remove bot from an event
app.post('/api/events/:eventId/remove-bot', async (req, res) => {
if (!req.session.user) {
return res.status(401).json({ error: 'Not authenticated' });
}
const eventId = req.params.eventId;
const db = readDatabase();
const eventIndex = db.events.findIndex(e => e.attendee_id === eventId);
if (eventIndex === -1) {
return res.status(404).json({ error: 'Event not found' });
}
const event = db.events[eventIndex];
// Check if bot exists
if (!event.bot_id) {
return res.status(400).json({ error: 'No bot exists for this event' });
}
try {
// Delete bot using Attendee API
await makeAttendeeRequest(`/api/v1/bots/${event.bot_id}`, 'DELETE');
// Update event to remove bot
db.events[eventIndex].bot_join_enabled = false;
db.events[eventIndex].bot_id = null;
writeDatabase(db);
res.json({
success: true,
message: 'Bot removed successfully'
});
} catch (error) {
console.error('Failed to delete bot:', error);
// If bot doesn't exist in Attendee anymore, still update our database
if (error.response?.status === 404) {
db.events[eventIndex].bot_join_enabled = false;
db.events[eventIndex].bot_id = null;
writeDatabase(db);
res.json({
success: true,
message: 'Bot removed (was already deleted)'
});
} else {
res.status(500).json({
error: 'Failed to remove bot: ' + (error.response?.data?.detail || error.message)
});
}
}
});
// Logout route
app.get('/logout', (req, res) => {
req.session.destroy();
res.redirect('/');
});
// Start server
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});