-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
2774 lines (2351 loc) · 102 KB
/
server.js
File metadata and controls
2774 lines (2351 loc) · 102 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
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
require('dotenv').config();
const express = require('express');
const session = require('express-session');
const bodyParser = require('body-parser');
const cors = require('cors');
const RingCentral = require('@ringcentral/sdk').SDK;
const path = require('path');
const MessageDetector = require('./message_detector');
const { SimpleUserStorage, SimpleSessionStorage } = require('./simple_storage');
const app = express();
const PORT = process.env.PORT || 3000;
// Initialize RingCentral SDK
console.log('🔧 REDIRECT_URI configured as:', process.env.REDIRECT_URI);
const rcsdk = new RingCentral({
server: process.env.RINGCENTRAL_SERVER_URL,
clientId: process.env.RINGCENTRAL_CLIENT_ID,
clientSecret: process.env.RINGCENTRAL_CLIENT_SECRET,
redirectUri: process.env.REDIRECT_URI
});
// Initialize Message Detector
const messageDetector = new MessageDetector(process.env.OPENAI_API_KEY);
// Helper function to send OMI notification to user's mobile app
async function sendOmiNotification(userId, message) {
const appId = process.env.OMI_APP_ID;
const appSecret = process.env.OMI_APP_SECRET;
if (!appId || !appSecret) {
console.log('⚠️ OMI credentials not configured, skipping notification');
return null;
}
const https = require('https');
const options = {
hostname: 'api.omi.me',
path: `/v2/integrations/${appId}/notification?uid=${encodeURIComponent(userId)}&message=${encodeURIComponent(message)}`,
method: 'POST',
headers: {
'Authorization': `Bearer ${appSecret}`,
'Content-Type': 'application/json',
'Content-Length': 0
}
};
return new Promise((resolve, reject) => {
const req = https.request(options, (res) => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => {
if (res.statusCode >= 200 && res.statusCode < 300) {
console.log(`📲 OMI notification sent to user ${userId.substring(0, 10)}...`);
try {
resolve(data ? JSON.parse(data) : {});
} catch (e) {
resolve({ raw: data });
}
} else {
console.error(`❌ OMI notification failed (${res.statusCode}): ${data}`);
reject(new Error(`API Error (${res.statusCode}): ${data}`));
}
});
});
req.on('error', (error) => {
console.error(`❌ OMI notification error: ${error.message}`);
reject(error);
});
req.end();
});
}
// CORS Configuration
const corsOptions = {
origin: function (origin, callback) {
// Allow requests with no origin (like mobile apps or curl requests)
if (!origin) return callback(null, true);
// Allow all origins for API endpoints
callback(null, true);
},
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'Accept'],
exposedHeaders: ['Content-Length', 'X-Request-Id'],
maxAge: 86400 // 24 hours
};
// Apply CORS middleware
app.use(cors(corsOptions));
// Handle preflight requests
app.options('*', cors(corsOptions));
// Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: true,
cookie: { secure: false }
}));
app.use(express.static('public'));
// Store OAuth states temporarily
const oauthStates = {};
// Background task for timeout monitoring
let timeoutMonitorInterval = null;
// Helper function to enrich chats with member names for DMs
async function enrichChatsWithMemberNames(platform, chats) {
const enrichedChats = [];
// Get current user's ID first
let currentUserId = null;
try {
const authData = await platform.auth().data();
currentUserId = authData.owner_id ? authData.owner_id.toString() : null;
console.log(`👤 Current user ID: ${currentUserId}`);
} catch (err) {
console.error(`❌ Could not get current user ID: ${err.message}`);
}
for (const chat of chats) {
const enrichedChat = { ...chat };
// For Direct messages, fetch member details to get names
if (chat.type === 'Direct' && chat.members && chat.members.length > 0) {
try {
// For DMs, fetch both members and find the OTHER person (not me)
const memberData = [];
for (const member of chat.members) {
// Skip bot/system accounts (glip- prefix)
const memberId = member.id.toString();
if (memberId.startsWith('glip-')) {
console.log(`⏭️ Skipping bot/system account: ${memberId}`);
continue;
}
try {
console.log(`🔍 Fetching details for member ${memberId}...`);
const userResponse = await platform.get(`/team-messaging/v1/persons/${memberId}`);
const userData = await userResponse.json();
const name = `${userData.firstName || ''} ${userData.lastName || ''}`.trim() || userData.email || null;
if (name) {
memberData.push({
id: memberId,
name: name
});
}
} catch (err) {
// Silently skip members we can't fetch (likely bots or deleted users)
if (!err.message.includes('404')) {
console.log(`⚠️ Could not fetch member ${memberId}: ${err.message}`);
}
}
}
// Find the member that is NOT the current user
if (currentUserId && memberData.length > 0) {
const otherPerson = memberData.find(m => m.id !== currentUserId);
if (otherPerson) {
enrichedChat.displayName = otherPerson.name;
enrichedChat.dmPersonName = otherPerson.name;
console.log(`✅ DM enriched: ${otherPerson.name}`);
} else if (memberData.length === 1) {
// Fallback to the only name we found
enrichedChat.displayName = memberData[0].name;
enrichedChat.dmPersonName = memberData[0].name;
console.log(`✅ DM enriched: ${memberData[0].name}`);
}
} else if (memberData.length > 0) {
// If we don't know current user, pick the first one
enrichedChat.displayName = memberData[0].name;
enrichedChat.dmPersonName = memberData[0].name;
console.log(`✅ DM enriched: ${memberData[0].name}`);
}
// If no displayName set, use a generic fallback
if (!enrichedChat.displayName) {
const realMembers = chat.members.filter(m => !m.id.toString().startsWith('glip-'));
if (realMembers.length > 0) {
enrichedChat.displayName = `DM ${chat.id}`;
} else {
enrichedChat.displayName = `Bot/System Chat ${chat.id}`;
}
}
} catch (err) {
console.log(`⚠️ Could not enrich DM chat ${chat.id}: ${err.message}`);
enrichedChat.displayName = `DM ${chat.id}`;
}
} else if (chat.type === 'Team') {
enrichedChat.displayName = chat.name || chat.description || `Team Chat ${chat.id}`;
} else if (chat.type === 'Personal') {
enrichedChat.displayName = 'Personal Notes';
} else {
enrichedChat.displayName = chat.name || chat.description || `Chat ${chat.id}`;
}
enrichedChats.push(enrichedChat);
}
return enrichedChats;
}
function startTimeoutMonitor() {
if (timeoutMonitorInterval) return;
console.log('🕐 Timeout monitor started');
timeoutMonitorInterval = setInterval(async () => {
try {
const allSessions = SimpleSessionStorage.getAllSessions();
for (const [sessionId, session] of Object.entries(allSessions)) {
if (session.message_mode !== "recording") continue;
const idleTime = SimpleSessionStorage.getSessionIdleTime(sessionId);
if (idleTime && idleTime > 7) {
const segmentsCount = session.segments_count || 0;
const accumulated = session.accumulated_text || "";
const triggerType = session.trigger_type || 'message';
console.log(`⏰ TIMEOUT MONITOR: Processing ${triggerType} for session ${sessionId} after ${idleTime.toFixed(1)}s idle (${segmentsCount} segment(s))`);
const uid = session.uid;
const user = SimpleUserStorage.getUser(uid);
if (user && user.tokens) {
SimpleSessionStorage.updateSession(sessionId, {
message_mode: "processing"
});
try {
// Get user's platform
const platform = rcsdk.platform();
await platform.auth().setData(user.tokens);
if (triggerType === 'event') {
// Handle event creation
console.log(`⏰ Creating event (timeout)...`);
// AI extracts event details
const { name, startDate, startTime, duration, notes } = await messageDetector.aiExtractEventDetails(accumulated);
if (name && name.trim().length >= 3) {
console.log(`⏰ Creating event: "${name}" on ${startDate || 'TBD'} at ${startTime || 'TBD'}`);
try {
const userSettings = SimpleUserStorage.getUserSettings(uid);
await createRingCentralEvent(platform, name, startDate, startTime, duration, notes, userSettings.timezone);
console.log(`⏰ SUCCESS! Event created via timeout: ${name}`);
// Send OMI notification to user's mobile app
const eventInfo = startDate ? ` on ${startDate}${startTime ? ` at ${startTime}` : ''}` : '';
const notificationMsg = `✅ Event created: ${name}${eventInfo}`;
try {
await sendOmiNotification(uid, notificationMsg);
} catch (notifError) {
console.log(`⚠️ Notification failed but event was created: ${notifError.message}`);
}
} catch (error) {
console.error(`⏰ Failed to create event: ${error.message}`);
}
} else {
console.log(`⏰ Insufficient content for event (name: '${name ? name.substring(0, 50) : 'None'}...')`);
}
} else if (triggerType === 'task') {
// Handle task creation
console.log(`⏰ Creating task (timeout)...`);
// Fetch team members (using same method as message matching for consistency)
const enrichedMembers = await getEnrichedTeamMembers(platform);
// AI extracts task details
const { title, assigneeId, assigneeName, dueDate, dueTime } = await messageDetector.aiExtractTaskDetails(
accumulated,
enrichedMembers
);
if (title && title.trim().length >= 3) {
console.log(`⏰ Creating task: "${title}" ${assigneeName ? `for ${assigneeName}` : ''}`);
try {
const userSettings = SimpleUserStorage.getUserSettings(uid);
await createRingCentralTask(platform, title, assigneeId, assigneeName, dueDate, dueTime, userSettings.timezone);
console.log(`⏰ SUCCESS! Task created via timeout: ${title}`);
// Send OMI notification to user's mobile app
const dueInfo = dueDate ? ` (due ${dueDate}${dueTime ? ` at ${dueTime}` : ''})` : '';
const notificationMsg = `✅ Task created: ${title}${assigneeName ? ` for ${assigneeName}` : ''}${dueInfo}`;
try {
await sendOmiNotification(uid, notificationMsg);
} catch (notifError) {
console.log(`⚠️ Notification failed but task was created: ${notifError.message}`);
}
} catch (error) {
console.error(`⏰ Failed to create task: ${error.message}`);
}
} else {
console.log(`⏰ Insufficient content for task (title: '${title ? title.substring(0, 50) : 'None'}...')`);
}
} else {
// Handle message sending
console.log(`⏰ Sending message (timeout)...`);
// Fetch fresh chats
const chatsResponse = await platform.get('/team-messaging/v1/chats');
const chatsData = await chatsResponse.json();
let chats = chatsData.records || chatsData || [];
// Enrich chats with member names for DMs (only for message sending)
console.log(`🔄 Enriching chats for message sending (timeout)...`);
chats = await enrichChatsWithMemberNames(platform, chats);
// AI extracts chat and message
const { chatId, chatName, message } = await messageDetector.aiExtractMessageAndChannel(
accumulated,
chats
);
if (chatId && message && message.trim().length >= 3) {
console.log(`⏰ Sending timeout message to ${chatName}`);
await platform.post(
`/team-messaging/v1/chats/${chatId}/posts`,
{ text: message }
);
console.log(`⏰ SUCCESS! Timeout message sent to ${chatName}`);
// Send OMI notification to user's mobile app
const notificationMsg = `✅ Message sent to ${chatName}: ${message}`;
try {
await sendOmiNotification(uid, notificationMsg);
} catch (notifError) {
console.log(`⚠️ Notification failed but message was sent: ${notifError.message}`);
}
} else {
console.log(`⏰ Insufficient content to send (message: '${message ? message.substring(0, 50) : 'None'}...')`);
}
}
SimpleSessionStorage.resetSession(sessionId);
} catch (error) {
console.error(`⏰ Error processing timeout: ${error}`);
SimpleSessionStorage.resetSession(sessionId);
}
}
}
}
} catch (error) {
console.error(`❌ Timeout monitor error: ${error}`);
}
}, 1000); // Check every second
}
// Helper function to fetch and enrich team members (same as chat enrichment for consistency)
async function getEnrichedTeamMembers(platform) {
const chatsResponse = await platform.get('/team-messaging/v1/chats');
const chatsData = await chatsResponse.json();
const chats = chatsData.records || [];
// Extract unique members from all chats and enrich with names
const memberIds = new Set();
const enrichedMembers = [];
for (const chat of chats) {
if (chat.members) {
for (const member of chat.members) {
const memberId = member.id.toString();
// Skip bot/system accounts and already processed members
if (memberId.startsWith('glip-') || memberIds.has(memberId)) {
continue;
}
try {
// Fetch member details
const userResponse = await platform.get(`/team-messaging/v1/persons/${memberId}`);
const userData = await userResponse.json();
const displayName = `${userData.firstName || ''} ${userData.lastName || ''}`.trim() || userData.email || null;
if (displayName) {
enrichedMembers.push({
id: memberId,
name: displayName,
displayName: displayName,
email: userData.email,
firstName: userData.firstName,
lastName: userData.lastName
});
memberIds.add(memberId);
}
} catch (err) {
// Skip members we can't fetch
if (!err.message.includes('404')) {
console.log(`⚠️ Could not fetch member ${memberId}: ${err.message}`);
}
}
}
}
}
console.log(`✓ Found ${enrichedMembers.length} team members`);
return enrichedMembers;
}
// Helper function to convert date/time to user's timezone and then to UTC
function convertToUserTimezone(dueDate, dueTime, userTimezone) {
// Create a date string in the user's timezone
let dateTimeStr = dueDate;
if (dueTime) {
dateTimeStr = `${dueDate}T${dueTime}:00`;
} else {
dateTimeStr = `${dueDate}T23:59:59`;
}
// Parse as if it's in the user's timezone
// Since we don't have a timezone library, we'll use a simple offset approach
// This is a simplified version - for production, use a library like moment-timezone
const date = new Date(dateTimeStr);
// Get timezone offset in hours from a lookup table
const timezoneOffsets = {
'America/Los_Angeles': -7, // PDT (summer)
'America/Denver': -6, // MDT
'America/Chicago': -5, // CDT
'America/New_York': -4, // EDT
'America/Phoenix': -7, // MST (no DST)
'UTC': 0,
'Europe/London': 1, // BST
'Europe/Paris': 2, // CEST
'Asia/Tokyo': 9,
'Australia/Sydney': 10 // AEST
};
const offsetHours = timezoneOffsets[userTimezone] || -7; // Default to PT
// Adjust the date by the offset to convert to UTC
const utcDate = new Date(date.getTime() - (offsetHours * 60 * 60 * 1000));
// Return in ISO format with Z
return utcDate.toISOString();
}
// Helper function to create calendar event in RingCentral
async function createRingCentralEvent(platform, eventName, startDate, startTime, duration, notes, userTimezone = 'America/Los_Angeles') {
// Build event start time in UTC
let startDateTime = null;
if (startDate && startTime) {
// Convert to user's timezone then to UTC
const dateTimeStr = `${startDate}T${startTime}:00`;
startDateTime = convertToUserTimezone(startDate, startTime, userTimezone);
} else if (startDate) {
// No time specified, default to 9 AM
startDateTime = convertToUserTimezone(startDate, '09:00', userTimezone);
} else {
// No date or time, default to tomorrow at 9 AM
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
const tomorrowStr = tomorrow.toISOString().split('T')[0];
startDateTime = convertToUserTimezone(tomorrowStr, '09:00', userTimezone);
}
// Calculate end time based on duration (in minutes)
const startDateObj = new Date(startDateTime);
const endDateObj = new Date(startDateObj.getTime() + (duration * 60 * 1000));
const endDateTime = endDateObj.toISOString();
console.log(`✓ Creating calendar event: ${eventName}`);
console.log(`✓ Start: ${startDateTime} (${duration} minutes)`);
// Build event body for Calendar Events API
// Reference: https://developers.ringcentral.com/api-reference/Calendar-Events/createEventNew
const eventBody = {
title: eventName,
startTime: startDateTime,
endTime: endDateTime,
allDay: false,
color: 'Blue'
};
if (notes) {
eventBody.description = notes;
}
// Create calendar event using Team Messaging Calendar Events API
const response = await platform.post('/team-messaging/v1/events', eventBody);
return await response.json();
}
// Helper function to create task in RingCentral
async function createRingCentralTask(platform, title, assigneeId, assigneeName, dueDate, dueTime, userTimezone = 'America/Los_Angeles') {
// Get or create a chat for the task
// If there's an assignee, find/create DM with them, otherwise use personal chat
let taskChatId = null;
if (assigneeId) {
// Try to find existing DM with assignee
const chatsResponse = await platform.get('/team-messaging/v1/chats?type=Direct');
const chatsData = await chatsResponse.json();
const chats = chatsData.records || [];
// Find DM with this person
for (const chat of chats) {
if (chat.members && chat.members.some(m => m.id === assigneeId)) {
taskChatId = chat.id;
console.log(`✓ Found existing DM chat ${taskChatId} with ${assigneeName}`);
break;
}
}
// If no DM exists, create one
if (!taskChatId) {
const createChatResponse = await platform.post('/team-messaging/v1/chats', {
type: 'Direct',
members: [{ id: assigneeId }]
});
const newChat = await createChatResponse.json();
taskChatId = newChat.id;
console.log(`✓ Created new DM chat ${taskChatId} with ${assigneeName}`);
}
} else {
// No assignee - use personal chat (create if needed)
const chatsResponse = await platform.get('/team-messaging/v1/chats?type=Personal');
const chatsData = await chatsResponse.json();
const personalChats = chatsData.records || [];
if (personalChats.length > 0) {
taskChatId = personalChats[0].id;
console.log(`✓ Using personal chat ${taskChatId} for unassigned task`);
} else {
// Create personal chat
const createChatResponse = await platform.post('/team-messaging/v1/chats', {
type: 'Personal'
});
const newChat = await createChatResponse.json();
taskChatId = newChat.id;
console.log(`✓ Created personal chat ${taskChatId}`);
}
}
// Build task body
const taskBody = {
subject: title
};
if (assigneeId) {
taskBody.assignees = [{ id: assigneeId }];
}
if (dueDate) {
// Convert to user's timezone then to UTC
const dueDateTimeUTC = convertToUserTimezone(dueDate, dueTime, userTimezone);
taskBody.dueDate = dueDateTimeUTC;
console.log(`✓ Due date in ${userTimezone}: ${dueDate}${dueTime ? ` ${dueTime}` : ' 23:59:59'} → UTC: ${dueDateTimeUTC}`);
}
// Create task in the chat
console.log(`✓ Creating task in chat ${taskChatId}:`, taskBody);
const response = await platform.post(`/restapi/v1.0/glip/chats/${taskChatId}/tasks`, taskBody);
return await response.json();
}
// Start timeout monitor
startTimeoutMonitor();
// Root endpoint - Settings page
app.get('/', async (req, res) => {
const { uid } = req.query;
if (!uid) {
// Show a simple landing page with instructions
return res.send(getLandingPageHTML());
}
const user = SimpleUserStorage.getUser(uid);
if (!user || !user.tokens) {
// Not authenticated - show auth page
const authUrl = `/auth?uid=${uid}`;
return res.send(getNotAuthenticatedHTML(authUrl, uid));
}
// Authenticated - show settings page
const chats = user.available_chats || [];
return res.send(getAuthenticatedHTML(uid, chats));
});
// Settings endpoint (same as root for now)
app.get('/settings', async (req, res) => {
const { uid } = req.query;
if (!uid) {
return res.send(getLandingPageHTML());
}
const user = SimpleUserStorage.getUser(uid);
if (!user || !user.tokens) {
const authUrl = `/auth?uid=${uid}`;
return res.send(getNotAuthenticatedHTML(authUrl, uid));
}
const chats = user.available_chats || [];
return res.send(getAuthenticatedHTML(uid, chats));
});
// OAuth start
app.get('/auth', (req, res) => {
const { uid } = req.query;
if (!uid) {
return res.status(400).send('Missing uid parameter');
}
try {
const state = Math.random().toString(36).substring(7);
oauthStates[state] = uid;
const platform = rcsdk.platform();
const loginUrl = platform.loginUrl({
redirectUri: process.env.REDIRECT_URI,
state: state,
brandId: '',
display: '',
prompt: ''
});
res.redirect(loginUrl);
} catch (error) {
console.error('OAuth start error:', error);
res.status(500).send('OAuth initialization failed: ' + error.message);
}
});
// OAuth callback
app.get('/oauth/callback', async (req, res) => {
const { code, state } = req.query;
if (!code || !state) {
return res.status(400).send('Missing code or state parameter');
}
const uid = oauthStates[state];
if (!uid) {
return res.status(400).send('Invalid state parameter');
}
try {
const platform = rcsdk.platform();
await platform.login({
code: code,
redirectUri: process.env.REDIRECT_URI
});
const authData = await platform.auth().data();
// Get chats
const chatsResponse = await platform.get('/team-messaging/v1/chats');
const chatsData = await chatsResponse.json();
const chats = chatsData.records || chatsData || [];
// Save user data (without enrichment - we'll enrich on-demand when sending)
SimpleUserStorage.saveUser(uid, authData, chats);
// Clean up state
delete oauthStates[state];
res.send(getSuccessHTML(uid, chats.length));
} catch (error) {
console.error('OAuth callback error:', error);
res.status(500).send('Authentication failed: ' + error.message);
}
});
// Setup completed check
app.get('/setup-completed', (req, res) => {
const { uid } = req.query;
if (!uid) {
return res.status(400).json({ error: 'Missing uid parameter' });
}
const isAuthenticated = SimpleUserStorage.isAuthenticated(uid);
res.json({
is_setup_completed: isAuthenticated
});
});
// Refresh chats
app.post('/refresh-chats', async (req, res) => {
const { uid } = req.query;
try {
const user = SimpleUserStorage.getUser(uid);
if (!user || !user.tokens) {
return res.json({ success: false, error: 'User not authenticated' });
}
const platform = rcsdk.platform();
await platform.auth().setData(user.tokens);
const chatsResponse = await platform.get('/team-messaging/v1/chats');
const chatsData = await chatsResponse.json();
const chats = chatsData.records || chatsData || [];
SimpleUserStorage.saveUser(uid, user.tokens, chats);
res.json({ success: true, chats_count: chats.length });
} catch (error) {
console.error('Error refreshing chats:', error);
res.json({ success: false, error: error.message });
}
});
// Update settings
app.post('/update-settings', async (req, res) => {
const { uid } = req.query;
const { timezone } = req.body;
try {
if (!uid) {
return res.json({ success: false, error: 'Missing uid' });
}
const success = SimpleUserStorage.updateUserSettings(uid, { timezone });
if (success) {
res.json({ success: true, message: 'Settings updated' });
} else {
res.json({ success: false, error: 'User not found' });
}
} catch (error) {
console.error('Settings update error:', error);
res.json({ success: false, error: error.message });
}
});
// Logout
app.post('/logout', async (req, res) => {
const { uid } = req.query;
try {
const user = SimpleUserStorage.getUser(uid);
if (user && user.tokens) {
const platform = rcsdk.platform();
await platform.auth().setData(user.tokens);
await platform.logout();
}
SimpleUserStorage.deleteUser(uid);
console.log(`🚪 Logged out user ${uid.substring(0, 10)}...`);
res.json({ success: true, message: 'Logged out successfully' });
} catch (error) {
console.error('Logout error:', error);
res.json({ success: true, message: 'Logged out' });
}
});
// Webhook endpoint - receives OMI transcripts (v2 - detailed logging)
app.post('/webhook', async (req, res) => {
console.log('📥 WEBHOOK RECEIVED:', {
query: req.query,
body: req.body ? (Array.isArray(req.body) ? `Array[${req.body.length}]` : Object.keys(req.body)) : 'empty',
headers: { 'content-type': req.headers['content-type'] }
});
const { uid, session_id } = req.query;
if (!uid) {
console.log('❌ WEBHOOK ERROR: No uid provided');
return res.status(401).json({
message: "User ID required",
setup_required: true
});
}
const sessionId = session_id || `omi_session_${uid}`;
const user = SimpleUserStorage.getUser(uid);
if (!user || !user.tokens) {
return res.status(401).json({
message: "User not authenticated. Please complete setup first.",
setup_required: true
});
}
try {
const payload = req.body;
console.log('📦 FULL PAYLOAD:', JSON.stringify(payload, null, 2));
let segments = [];
if (Array.isArray(payload)) {
segments = payload;
} else if (payload.segments) {
segments = payload.segments;
}
console.log(`📥 Received ${segments.length} segment(s) from OMI`);
if (segments.length > 0) {
segments.slice(0, 3).forEach((seg, i) => {
const text = seg.text || seg;
console.log(` Segment ${i}: ${typeof text === 'string' ? text.substring(0, 100) : JSON.stringify(text)}`);
});
}
if (!segments || segments.length === 0) {
return res.json({ status: "ok" });
}
const session = SimpleSessionStorage.getOrCreateSession(sessionId, uid);
console.log(`📊 Session state: mode=${session.message_mode}, count=${session.segments_count || 0}`);
const responseMessage = await processSegments(session, segments, user);
if (responseMessage && (responseMessage.includes('✅') || responseMessage.includes('❌'))) {
console.log(`✉️ USER NOTIFICATION: ${responseMessage}`);
return res.json({
message: responseMessage,
session_id: sessionId,
processed_segments: segments.length
});
}
console.log(`🔇 Silent response: ${responseMessage}`);
res.json({ status: "ok" });
} catch (error) {
console.error('Webhook error:', error);
res.status(500).json({ error: error.message });
}
});
async function processSegments(session, segments, user) {
const segmentTexts = segments.map(seg => seg.text || seg);
const fullText = segmentTexts.join(' ');
const sessionId = session.session_id;
const isTestSession = sessionId.startsWith('test_session');
console.log(`🔍 Received: '${fullText}'`);
console.log(`📊 Session mode: ${session.message_mode}, Count: ${session.segments_count || 0}/5`);
// Check for trigger phrase
if (messageDetector.detectTrigger(fullText) && session.message_mode === "idle") {
const triggerType = messageDetector.detectTriggerType(fullText);
const content = messageDetector.extractMessageContent(fullText);
console.log(`🎤 TRIGGER! Type: ${triggerType} ${isTestSession ? '[TEST MODE] Processing immediately...' : 'Starting segment collection...'}`);
console.log(` Content: '${content}'`);
// TEST MODE: Process immediately
if (isTestSession && content && content.length > 10) {
console.log(`🧪 Test mode: Processing full text immediately...`);
const platform = rcsdk.platform();
await platform.auth().setData(user.tokens);
if (triggerType === 'event') {
// Handle event creation
console.log(`📅 Creating event...`);
// AI extracts event details
const { name, startDate, startTime, duration, notes } = await messageDetector.aiExtractEventDetails(content);
if (!name || name.trim().length < 3) {
SimpleSessionStorage.resetSession(sessionId);
return "❌ No valid event name found";
}
console.log(`📤 Creating event: "${name}" on ${startDate || 'TBD'} at ${startTime || 'TBD'}`);
try {
const uid = session.uid;
const userSettings = SimpleUserStorage.getUserSettings(uid);
await createRingCentralEvent(platform, name, startDate, startTime, duration, notes, userSettings.timezone);
SimpleSessionStorage.resetSession(sessionId);
console.log(`🎉 SUCCESS! Event created: ${name}`);
const eventInfo = startDate ? ` on ${startDate}${startTime ? ` at ${startTime}` : ''}` : '';
const notificationMsg = `✅ Event created: ${name}${eventInfo}`;
// Send OMI notification to user's mobile app
try {
await sendOmiNotification(uid, notificationMsg);
} catch (notifError) {
console.log(`⚠️ Notification failed but event was created: ${notifError.message}`);
}
return notificationMsg;
} catch (error) {
SimpleSessionStorage.resetSession(sessionId);
console.error(`❌ FAILED: ${error.message}`);
return `❌ Failed to create event: ${error.message}`;
}
} else if (triggerType === 'task') {
// Handle task creation
console.log(`📋 Creating task...`);
// Fetch team members (using same method as message matching for consistency)
const enrichedMembers = await getEnrichedTeamMembers(platform);
// AI extracts task details
const { title, assigneeId, assigneeName, dueDate, dueTime } = await messageDetector.aiExtractTaskDetails(
content,
enrichedMembers
);
if (!title || title.trim().length < 3) {
SimpleSessionStorage.resetSession(sessionId);
return "❌ No valid task title found";
}
console.log(`📤 Creating task: "${title}" ${assigneeName ? `for ${assigneeName}` : ''}`);
try {
const uid = session.uid;
const userSettings = SimpleUserStorage.getUserSettings(uid);
await createRingCentralTask(platform, title, assigneeId, assigneeName, dueDate, dueTime, userSettings.timezone);
SimpleSessionStorage.resetSession(sessionId);
console.log(`🎉 SUCCESS! Task created: ${title}`);
const dueInfo = dueDate ? ` (due ${dueDate}${dueTime ? ` at ${dueTime}` : ''})` : '';
const notificationMsg = `✅ Task created: ${title}${assigneeName ? ` for ${assigneeName}` : ''}${dueInfo}`;
// Send OMI notification to user's mobile app
try {
await sendOmiNotification(uid, notificationMsg);
} catch (notifError) {
console.log(`⚠️ Notification failed but task was created: ${notifError.message}`);
}
return notificationMsg;
} catch (error) {
SimpleSessionStorage.resetSession(sessionId);
console.error(`❌ FAILED: ${error.message}`);
return `❌ Failed to create task: ${error.message}`;
}
} else {
// Handle message sending (original logic)
console.log(`🔄 Fetching fresh chat list...`);
const chatsResponse = await platform.get('/team-messaging/v1/chats');
const chatsData = await chatsResponse.json();
let chats = chatsData.records || chatsData || [];
// Enrich chats with member names for DMs (only for message sending)
console.log(`🔄 Enriching chats for message sending (test mode)...`);
chats = await enrichChatsWithMemberNames(platform, chats);
// AI extracts chat and message
const { chatId, chatName, message } = await messageDetector.aiExtractMessageAndChannel(
content,
chats
);
if (!chatId) {
SimpleSessionStorage.resetSession(sessionId);
return "❌ No chat specified and no default chat set";
}
if (!message) {
SimpleSessionStorage.resetSession(sessionId);
return "❌ No message content found";
}
console.log(`📤 Sending to ${chatName}: '${message}'`);
try {
await platform.post(
`/team-messaging/v1/chats/${chatId}/posts`,
{ text: message }
);
SimpleSessionStorage.resetSession(sessionId);
console.log(`🎉 SUCCESS! Message sent to ${chatName}`);
const notificationMsg = `✅ Message sent to ${chatName}: ${message}`;
// Send OMI notification to user's mobile app
const uid = session.uid;
try {
await sendOmiNotification(uid, notificationMsg);
} catch (notifError) {
console.log(`⚠️ Notification failed but message was sent: ${notifError.message}`);