-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
409 lines (355 loc) · 13.5 KB
/
content.js
File metadata and controls
409 lines (355 loc) · 13.5 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
// TeamSync AI - Content Script
let geminiApiKey = null;
let groqApiKey = null;
// Load API Key on startup
chrome.storage.local.get(['geminiApiKey', 'groqApiKey'], (result) => {
// Always inject the panel so the user sees the extension is active
injectGlobalControlPanel();
if (result.geminiApiKey && result.geminiApiKey.trim() !== "") {
geminiApiKey = result.geminiApiKey;
console.log('TeamSync AI: Gemini API Key loaded.');
}
if (result.groqApiKey && result.groqApiKey.trim() !== "") {
groqApiKey = result.groqApiKey;
console.log('TeamSync AI: Groq API Key loaded.');
}
if (result.geminiApiKey || result.groqApiKey) {
startObserver();
updateStatus('Ready to scan');
} else {
console.log('TeamSync AI: No API Key found. Please set it in the extension settings.');
updateStatus('Missing API Key', true);
}
});
// Listen for changes in storage (in case user updates key while tab is open)
chrome.storage.onChanged.addListener((changes, namespace) => {
if (namespace === 'local') {
if (changes.geminiApiKey) {
geminiApiKey = changes.geminiApiKey.newValue;
console.log('TeamSync AI: Gemini API Key updated.');
}
if (changes.groqApiKey) {
groqApiKey = changes.groqApiKey.newValue;
console.log('TeamSync AI: Groq API Key updated.');
}
startObserver();
injectGlobalControlPanel();
}
});
function startObserver() {
const observer = new MutationObserver(debounce(handleMutations, 1000));
observer.observe(document.body, {
childList: true,
subtree: true
});
console.log('TeamSync AI: Observer started.');
}
// Debounce utility
function debounce(func, wait) {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), wait);
};
}
function handleMutations(mutations) {
if (!geminiApiKey && !groqApiKey) {
updateStatus('Missing API Key', true);
return;
}
// Teams message bodies often have data-tid="message-body" or similar classes
// We'll look for elements that look like message content and haven't been processed
const messages = document.querySelectorAll('[data-tid="message-body"]:not([data-teamsync-processed])');
messages.forEach(message => {
// Mark as processed immediately to avoid duplicate calls
message.setAttribute('data-teamsync-processed', 'true');
const text = message.innerText;
if (text && text.length > 10) { // Basic filter
processMessage(message, text);
}
});
}
async function processMessage(messageElement, text) {
try {
updateStatus('Analyzing...', false);
// Attempt to find a timestamp context
// We look for a parent container that might have the timestamp
// In Teams, the timestamp is often in a 'title' attribute of a nearby element or a 'time' element
let timestampContext = '';
try {
// Look up to 5 levels up
let parent = messageElement.parentElement;
for (let i = 0; i < 5; i++) {
if (!parent) break;
// Check for any element with a title attribute that looks like a date
const timeElement = parent.querySelector('[title*="202"], [title*="AM"], [title*="PM"]');
if (timeElement) {
timestampContext = timeElement.getAttribute('title');
break;
}
// Also check innerText of the container for date-like strings if it's short
if (parent.innerText.length < 200 && (parent.innerText.includes('Yesterday') || parent.innerText.includes('Today') || parent.innerText.match(/\d{1,2}:\d{2}/))) {
// This might include the name and time, which is good context
timestampContext = parent.innerText.split('\n')[0]; // Usually the first line is header
}
parent = parent.parentElement;
}
} catch (e) {
console.log('Timestamp extraction failed', e);
}
let eventData = null;
try {
eventData = await callGeminiAPI(text, timestampContext);
} catch (geminiError) {
console.warn('TeamSync AI: Gemini API failed', geminiError);
}
let finalEventData = eventData;
// Fallback to Groq if Gemini failed (threw error) or returned null/no-event
// Note: If Gemini returned {is_event: false}, we might accept that or try Groq.
// For now, if Gemini works but says "no", we trust it.
// We only fallback if eventData is null (error/parse fail).
if (!finalEventData && groqApiKey) {
console.log('TeamSync AI: Gemini returned no event or failed, trying Groq...');
updateStatus('Gemini failed, trying Groq...', false);
finalEventData = await callGroqAPI(text, timestampContext);
}
if (finalEventData) {
// Save to storage for Dashboard
await saveEventToStorage(finalEventData, text);
// Inject UI button
injectButton(messageElement, finalEventData);
updateStatus('Event Found!', false);
} else {
updateStatus('No event detected', false);
}
} catch (error) {
console.error('TeamSync AI: Error processing message', error);
updateStatus('API Error: ' + error.message, true);
}
}
async function saveEventToStorage(geminiResult, originalText) {
// Generate ID
let id;
if (window.crypto && window.crypto.subtle) {
const msgBuffer = new TextEncoder().encode(originalText + geminiResult.start_time);
const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
const hashArray = Array.from(new Uint8Array(hashBuffer));
id = hashArray.map(b => b.toString(16).padStart(2, '0')).join('').substring(0, 12);
} else {
// Fallback for non-secure contexts (e.g. local testing)
id = 'id-' + Math.random().toString(36).substring(2, 15);
}
const newEvent = {
id: id,
title: geminiResult.event_title,
startDateTime: geminiResult.start_time,
type: geminiResult.type || 'other',
originalMessage: originalText,
detectedAt: new Date().toISOString(),
status: 'pending'
};
chrome.storage.local.get(['events', 'stats'], (data) => {
const currentEvents = data.events || [];
const stats = data.stats || { totalEventsFound: 0, totalScanned: 0, lastSyncTime: new Date().toISOString(), tokensUsed: 0 };
// Check duplicate
if (!currentEvents.some(e => e.id === id)) {
const updatedEvents = [newEvent, ...currentEvents];
// Update stats
stats.totalEventsFound += 1;
stats.lastSyncTime = new Date().toISOString();
chrome.storage.local.set({
events: updatedEvents,
stats: stats
}, () => {
console.log('TeamSync AI: Event saved to storage', newEvent);
});
}
});
}
async function callGeminiAPI(text, timestampContext = '') {
const currentDate = new Date().toISOString();
let prompt = `You are an assistant that extracts calendar events from student chat messages.
Today's date is ${currentDate}.`;
if (timestampContext) {
prompt += `\nThe message was sent near this timestamp context: "${timestampContext}". Use this to help determine the correct date.`;
}
prompt += `\nExtract the event title, start date (ISO format), and type (exam, assignment, lecture, meeting, other) from this text: '${text}'.
Return strictly JSON in this format: { "is_event": true, "event_title": "Title", "start_time": "ISO_DATE_STRING", "type": "exam" }.
If no event is present, return { "is_event": false }.`;
// SEND MESSAGE TO BACKGROUND SCRIPT
return new Promise((resolve, reject) => {
chrome.runtime.sendMessage({
action: 'analyze_gemini',
apiKey: geminiApiKey,
prompt: prompt
}, (response) => {
if (chrome.runtime.lastError) {
console.error("Runtime Error:", chrome.runtime.lastError);
return resolve(null);
}
if (response && response.success) {
try {
const responseText = response.data.candidates[0].content.parts[0].text;
const jsonString = responseText.replace(/```json/g, '').replace(/```/g, '').trim();
const result = JSON.parse(jsonString);
if (result.is_event && result.event_title && result.start_time) {
resolve(result);
} else {
resolve(null);
}
} catch (e) {
console.error('Parse Error:', e);
resolve(null);
}
} else {
console.error('Background Script Error:', response?.error);
resolve(null);
}
});
});
}
async function callGroqAPI(text, timestampContext = '') {
if (!groqApiKey) return null;
const dateObj = new Date();
// Format the date so the AI understands "today" vs "tomorrow"
const dateString = dateObj.toLocaleDateString('en-US', {
weekday: 'long', year: 'numeric', month: 'long', day: 'numeric'
});
const isoString = dateObj.toISOString();
let systemPrompt = `Current Date: ${dateString} (${isoString}).
Context from UI: "${timestampContext}"
TASK: Extract calendar events from the student message below.
RULES:
1. "Tonight" implies the deadline is ON the Current Date.
2. "Tomorrow" is Current Date + 1 day.
3. Return ONLY valid JSON. No markdown. No comments.
Format:
{
"is_event": true,
"event_title": "Short Title",
"start_time": "ISO_DATE_STRING (e.g. 2025-12-12T18:00:00)",
"type": "assignment"
}
If no event, return: { "is_event": false }
4. If unsure, lean towards "is_event": true.`;
if (timestampContext) {
systemPrompt += `\nContext: "${timestampContext}"`;
}
const payload = {
model: "llama-3.1-8b-instant",
messages: [
{ role: "system", content: systemPrompt },
{ role: "user", content: text }
],
response_format: { type: "json_object" }
};
// SEND MESSAGE TO BACKGROUND SCRIPT
return new Promise((resolve) => {
chrome.runtime.sendMessage({
action: 'analyze_groq',
apiKey: groqApiKey,
payload: payload
}, (response) => {
if (response && response.success) {
try {
let rawContent = response.data.choices[0].message.content;
// --- DEBUGGING LOG ---
// Open Console (F12) to see exactly what Groq returned
console.log("🔍 Groq Raw Response:", rawContent);
// --- THE FIX: Clean Markdown Fences ---
// Removes ```json and ``` if they exist
rawContent = rawContent.replace(/```json/g, '').replace(/```/g, '').trim();
const result = JSON.parse(rawContent);
if (result.is_event) {
resolve(result);
} else {
console.log("AI decided it was NOT an event.");
resolve(null);
}
} catch (e) {
console.error("JSON Parse Error:", e);
resolve(null);
}
} else {
console.error("Groq Network Error:", response?.error);
resolve(null);
}
});
});
}
function injectButton(messageElement, eventData) {
const button = document.createElement('a');
button.className = 'teamsync-calendar-btn';
button.innerHTML = '<span class="icon">📅</span> Add to Calendar';
button.title = `Detected: ${eventData.event_title} on ${new Date(eventData.start_time).toLocaleString()}`;
// Outlook Deep Link
// Format: https://outlook.office.com/calendar/0/deeplink/compose?subject={TITLE}&startdt={DATE}
const subject = encodeURIComponent(eventData.event_title);
const startDt = encodeURIComponent(eventData.start_time);
button.href = `https://outlook.office.com/calendar/0/deeplink/compose?subject=${subject}&startdt=${startDt}`;
button.target = '_blank';
// Append to the message element or its parent container
// In Teams, appending directly to message-body might be overwritten by React
// So we try to append to the parent or a safe container if possible.
// For now, we append to the message element itself as a simple approach.
messageElement.appendChild(button);
}
function injectGlobalControlPanel() {
if (document.getElementById('teamsync-control-panel')) return;
const panel = document.createElement('div');
panel.id = 'teamsync-control-panel';
panel.style.cssText = `
position: fixed;
bottom: 20px;
right: 20px;
z-index: 9999;
background: white;
padding: 10px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.2);
display: flex;
flex-direction: column;
gap: 5px;
font-family: 'Segoe UI', sans-serif;
font-size: 12px;
`;
const title = document.createElement('div');
title.textContent = 'TeamSync AI';
title.style.fontWeight = 'bold';
title.style.color = '#444791';
title.style.marginBottom = '5px';
panel.appendChild(title);
const scanBtn = document.createElement('button');
scanBtn.textContent = 'Scan Chat Now';
scanBtn.style.cssText = `
background: #444791;
color: white;
border: none;
padding: 8px 12px;
border-radius: 4px;
cursor: pointer;
`;
scanBtn.onclick = () => {
scanBtn.textContent = 'Scanning...';
// Reset processed flags to force re-scan
document.querySelectorAll('[data-teamsync-processed]').forEach(el => {
el.removeAttribute('data-teamsync-processed');
});
handleMutations([]);
setTimeout(() => { scanBtn.textContent = 'Scan Chat Now'; }, 2000);
};
panel.appendChild(scanBtn);
const status = document.createElement('div');
status.id = 'teamsync-status-text';
status.textContent = 'Ready';
status.style.color = '#666';
panel.appendChild(status);
document.body.appendChild(panel);
}
function updateStatus(msg, isError = false) {
const el = document.getElementById('teamsync-status-text');
if (el) {
el.textContent = msg;
el.style.color = isError ? 'red' : '#666';
}
}