-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathpopup.js
More file actions
388 lines (331 loc) · 14 KB
/
popup.js
File metadata and controls
388 lines (331 loc) · 14 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
const authBtn = document.getElementById("authBtn");
const status = document.getElementById("status");
const keywordInput = document.getElementById("keywordInput");
const logoutBtn = document.getElementById("logoutBtn")
const countKeywordBtn = document.getElementById("countKeywordBtn");
const deleteKeywordBtn = document.getElementById("deleteKeywordBtn");
const subjectOnlyCheckbox = document.getElementById("subjectOnlyCheckbox");
const previewModal = document.getElementById("previewModal");
const previewList = document.getElementById("previewList");
const previewDeleteBtn = document.getElementById("previewDeleteBtn");
const previewCancelBtn = document.getElementById("previewCancelBtn");
const labelNameInput = document.getElementById("labelNameInput");
const generateKeywordsBtn = document.getElementById("generateKeywordsBtn");
const applyAutoLabelBtn = document.getElementById("applyAutoLabelBtn");
const generatedKeywords = document.getElementById("generatedKeywords");
let authToken = null;
function updateUIState(isAuthenticated) {
const isEnabled = isAuthenticated;
status.textContent = isEnabled ? "Connected to Gmail" : "Click Connect Gmail to start";
keywordInput.disabled = !isEnabled;
countKeywordBtn.disabled = !isEnabled;
deleteKeywordBtn.disabled = !isEnabled;
if (labelNameInput) labelNameInput.disabled = !isEnabled;
if (generateKeywordsBtn) generateKeywordsBtn.disabled = !isEnabled;
if (applyAutoLabelBtn) applyAutoLabelBtn.disabled = !isEnabled;
if(isAuthenticated){
document.getElementById("logoutBtn").style.display = 'block'
}
authBtn.textContent = isEnabled ? "Connected " : "Connect Gmail";
authBtn.disabled = isEnabled;
authBtn.style.backgroundColor = isEnabled ? "#34a853" : "#4285F4";
logoutBtn.disabled = !isEnabled;
}
logoutBtn.addEventListener("click", async () => {
status.textContent = "Logging out...";
try {
await sendMessageToBackground("clearToken");
authToken = null;
document.getElementById("logoutBtn").style.display = 'none'
updateUIState(false);
status.textContent = "Logged out successfully ";
} catch (err) {
console.error(err);
status.textContent = `Logout failed `;
}
});
function sendMessageToBackground(action, data = {}) {
return new Promise((resolve, reject) => {
browser.runtime.sendMessage({ action, ...data }, (response) => {
if (browser.runtime.lastError) return reject(browser.runtime.lastError);
if (!response) return reject(new Error(`No response for ${action}`));
if (response.success) return resolve(response);
reject(new Error(response.error || `${action} failed`));
});
});
}
async function validateAndRefreshToken() {
if (!authToken) throw new Error("No token available. Connect to Gmail first.");
const testRes = await fetch("https://gmail.googleapis.com/gmail/v1/users/me/profile", {
headers: { Authorization: `Bearer ${authToken}` }
});
if (testRes.status === 401) {
authToken = null;
await sendMessageToBackground("clearToken");
updateUIState(false);
throw new Error("Token expired. Please reconnect Gmail.");
}
if (!testRes.ok) throw new Error(`Token validation failed: ${testRes.status}`);
return true;
}
async function getAllMessageIds(query) {
await validateAndRefreshToken();
let allIds = [];
let nextPageToken = null;
const searchUrlBase = `https://gmail.googleapis.com/gmail/v1/users/me/messages?q=${encodeURIComponent(query)}&maxResults=500`;
status.textContent = "Finding all matching emails (this may take a moment)...";
do {
const searchUrl = nextPageToken ? `${searchUrlBase}&pageToken=${nextPageToken}` : searchUrlBase;
const response = await fetch(searchUrl, {
headers: { Authorization: `Bearer ${authToken}` }
});
if (!response.ok) throw new Error(`API Error: ${response.status}`);
const data = await response.json();
if (data.messages) {
allIds.push(...data.messages.map(msg => msg.id));
}
nextPageToken = data.nextPageToken;
status.textContent = `Found ${allIds.length} emails so far...`;
} while (nextPageToken);
return allIds;
}
async function deleteEmailsByQuery(query, description) {
const ids = await getAllMessageIds(query);
if (ids.length === 0) {
status.textContent = `No ${description} found to delete `;
return;
}
status.textContent = `Deleting ${ids.length} ${description}... `;
const batchSize = 1000;
let deletedCount = 0;
for (let i = 0; i < ids.length; i += batchSize) {
const batch = ids.slice(i, i + batchSize);
const deleteRes = await fetch("https://gmail.googleapis.com/gmail/v1/users/me/messages/batchDelete", {
method: "POST",
headers: { Authorization: `Bearer ${authToken}`, "Content-Type": "application/json" },
body: JSON.stringify({ ids: batch })
});
if (!deleteRes.ok) throw new Error(`Failed to delete batch: ${deleteRes.status}`);
deletedCount += batch.length;
status.textContent = `Deleted ${deletedCount} of ${ids.length} ${description}... `;
}
status.textContent = `Deleted ${deletedCount} ${description} `;
}
async function countEmailsByQuery(query, description) {
const ids = await getAllMessageIds(query);
const count = ids.length;
status.textContent = count ? `Found ${count} ${description} ` : `No ${description} found `;
return count;
}
async function showSubjectPreview(query, description) {
await validateAndRefreshToken();
const res = await fetch(`https://gmail.googleapis.com/gmail/v1/users/me/messages?q=${encodeURIComponent(query)}&maxResults=50`, {
headers: { Authorization: `Bearer ${authToken}` }
});
const data = await res.json();
if (!data.messages || data.messages.length === 0) {
status.textContent = `No ${description} found 🎉`;
return false;
}
previewList.innerHTML = "<li><em>Loading subjects...</em></li>";
previewModal.style.display = "flex";
const subjectPromises = data.messages.map(msg =>
fetch(`https://gmail.googleapis.com/gmail/v1/users/me/messages/${msg.id}?format=metadata&metadataHeaders=Subject`, {
headers: { Authorization: `Bearer ${authToken}` }
}).then(res => res.json())
);
const messages = await Promise.all(subjectPromises);
previewList.innerHTML = "";
messages.forEach(msgData => {
const header = msgData.payload.headers.find(h => h.name === "Subject");
const li = document.createElement("li");
li.textContent = header ? header.value : "(no subject)";
previewList.appendChild(li);
});
return new Promise(resolve => {
previewDeleteBtn.onclick = () => { previewModal.style.display = "none"; resolve(true); status.scrollIntoView();};
previewCancelBtn.onclick = () => { previewModal.style.display = "none"; resolve(false);};
});
}
countKeywordBtn.addEventListener("click", async () => {
const keyword = keywordInput.value.trim();
if (!keyword) {
status.textContent = "Please enter a keyword.";
return;
}
const isSubjectOnly = subjectOnlyCheckbox.checked;
const query = isSubjectOnly ? `subject:("${keyword}")` : `"${keyword}"`;
const description = `emails with keyword "${keyword}"` + (isSubjectOnly ? " in subject" : "");
await countEmailsByQuery(query, description);
});
deleteKeywordBtn.addEventListener("click", async () => {
const keyword = keywordInput.value.trim();
if (!keyword) {
status.textContent = "Please enter a keyword.";
return;
}
const isSubjectOnly = subjectOnlyCheckbox.checked;
const query = isSubjectOnly ? `subject:("${keyword}")` : `"${keyword}"`;
const description = `emails with keyword "${keyword}"` + (isSubjectOnly ? " in subject" : "");
const userConfirmed = await showSubjectPreview(query, description);
if (userConfirmed) {
await deleteEmailsByQuery(query, description);
}
});
async function aiSuggestKeywords(labelName) {
status.textContent = "Asking Groq LLaMA for keywords...";
if (previewDeleteBtn) previewDeleteBtn.textContent = "Apply";
try {
const res = await fetch("https://api.groq.com/openai/v1/chat/completions", {
method: "POST",
headers: {
"Authorization": `Bearer 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`,
"Content-Type": "application/json"
},
body: JSON.stringify({
model: "llama-3.1-8b-instant",
messages: [
{ role: "system", content: "You are an assistant that generates concise Gmail keyword filters." },
{ role: "user", content: `Suggest up to 10 short keywords to filter emails for label: "${labelName}". Return them as a comma-separated list only.` }
],
temperature: 0.4,
max_tokens: 100
})
});
if (!res.ok) throw new Error(`Groq API error: ${res.status}`);
const data = await res.json();
const text = data.choices?.[0]?.message?.content?.trim() || "";
const kws = text
.split(/[,;\n]+/)
.map(s => s.trim().toLowerCase())
.filter(Boolean);
if (kws.length) return kws;
} catch (e) {
console.warn("Groq AI unavailable, using fallback.", e);
}
const base = (labelName || "").toLowerCase().trim();
const words = Array.from(new Set(base.split(/[\s\-_/]+/).filter(Boolean)));
const synonyms = {
};
let out = [...words];
words.forEach(w => { if (synonyms[w]) out.push(...synonyms[w]); });
if (base && !out.includes(base)) out.push(base);
out = Array.from(new Set(out)).slice(0, 20);
return out;
}
function buildGmailQueryFromKeywords(keywords) {
if (!keywords || keywords.length === 0) return "";
const esc = s => `"${s.replace(/"/g, '\\"')}"`;
const any = keywords.map(k => esc(k)).join(" OR ");
const subj = keywords.map(k => `subject:${esc(k)}`).join(" OR ");
return `( ${any} OR ${subj} ) -in:trash`;
}
async function ensureLabelExists(name) {
await validateAndRefreshToken();
const listRes = await fetch("https://gmail.googleapis.com/gmail/v1/users/me/labels", {
headers: { Authorization: `Bearer ${authToken}` }
});
if (!listRes.ok) throw new Error(`Failed to list labels: ${listRes.status}`);
const { labels = [] } = await listRes.json();
const existing = labels.find(l => l.name.toLowerCase() === name.toLowerCase());
if (existing) return existing.id;
const createRes = await fetch("https://gmail.googleapis.com/gmail/v1/users/me/labels", {
method: "POST",
headers: { Authorization: `Bearer ${authToken}`, "Content-Type": "application/json" },
body: JSON.stringify({
name,
labelListVisibility: "labelShow",
messageListVisibility: "show"
})
});
if (!createRes.ok) throw new Error(`Failed to create label: ${createRes.status}`);
const created = await createRes.json();
return created.id;
}
async function labelEmailsByQuery(query, labelId, description) {
const ids = await getAllMessageIds(query);
if (ids.length === 0) {
status.textContent = `No ${description} found to label `;
return;
}
status.textContent = `Labeling ${ids.length} ${description}... `;
const batchSize = 1000;
let labeled = 0;
for (let i = 0; i < ids.length; i += batchSize) {
const batch = ids.slice(i, i + batchSize);
const modRes = await fetch("https://gmail.googleapis.com/gmail/v1/users/me/messages/batchModify", {
method: "POST",
headers: { Authorization: `Bearer ${authToken}`, "Content-Type": "application/json" },
body: JSON.stringify({ ids: batch, addLabelIds: [labelId] })
});
if (!modRes.ok) throw new Error(`Failed to label batch: ${modRes.status}`);
labeled += batch.length;
status.textContent = `Labeled ${labeled} of ${ids.length} ${description}... `;
}
status.textContent = `Applied label to ${labeled} ${description} `;
}
if (generateKeywordsBtn) {
generateKeywordsBtn.addEventListener("click", async () => {
const label = labelNameInput ? labelNameInput.value.trim() : "";
if (!label) { status.textContent = "Enter a label name first."; return; }
try {
const kws = await aiSuggestKeywords(label);
if (generatedKeywords) generatedKeywords.value = kws.join(", ");
status.textContent = `Got ${kws.length} keyword(s) for "${label}". You can edit before applying.`;
if (generatedKeywords) generatedKeywords.readOnly = false;
} catch (err) {
status.textContent = `AI keyword error: ${err.message}`;
}
status.scrollIntoView();
});
}
if (applyAutoLabelBtn) {
applyAutoLabelBtn.addEventListener("click", async () => {
const label = labelNameInput ? labelNameInput.value.trim() : "";
if (!label) { status.textContent = "Enter a label name first."; return; }
let keywords = generatedKeywords && generatedKeywords.value
? generatedKeywords.value.split(",").map(s => s.trim()).filter(Boolean)
: [];
if (keywords.length === 0) {
try {
keywords = await aiSuggestKeywords(label);
if (generatedKeywords) generatedKeywords.value = keywords.join(", ");
if (generatedKeywords) generatedKeywords.readOnly = false;
} catch (e) {
status.textContent = `AI keyword error: ${e.message}`;
return;
}
}
const query = buildGmailQueryFromKeywords(keywords);
if (!query) { status.textContent = "No usable keywords."; return; }
try {
const ok = await showSubjectPreview(query, `emails for label "${label}"`);
if (!ok) { status.textContent = "Canceled."; return; }
const labelId = await ensureLabelExists(label);
await labelEmailsByQuery(query, labelId, `emails for label "${label}"`);
} catch (err) {
status.textContent = `Error: ${err.message}`;
}
});
}
authBtn.addEventListener("click", async () => {
status.textContent = "Authenticating...";
authBtn.disabled = true;
authBtn.textContent = "Connecting...";
try {
const response = await sendMessageToBackground("getToken");
authToken = response.token;
updateUIState(true);
} catch (err) {
console.error(err);
status.textContent = `Auth failed `;
updateUIState(false);
}
});
document.addEventListener('DOMContentLoaded', async () => {
try {
const resp = await sendMessageToBackground('checkToken');
if (resp.hasValidToken) { authToken = resp.token; updateUIState(true); }
else updateUIState(false);
} catch { updateUIState(false); }
});