-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathutils.js
More file actions
228 lines (198 loc) · 7.22 KB
/
utils.js
File metadata and controls
228 lines (198 loc) · 7.22 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
if (typeof window.utilsLoaded === "undefined") {
console.log("utils.js loaded");
window.utilsLoaded = true;
// Common utility functions
const CommonUtils = {
// Delay utility
delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
},
// Generate timestamp
generateTimestamp() {
return new Date().toISOString().replace("T", " ").substr(0, 19);
},
// Safe element query with timeout
async waitForElement(selector, parent = document, timeout = UI_CONFIG.TIMEOUTS.ELEMENT_WAIT) {
const startedAt = Date.now();
while (Date.now() - startedAt < timeout) {
const element = parent.querySelector(selector);
if (element) return element;
await this.delay(UI_CONFIG.DELAYS.SHORT);
}
throw new Error(`Element ${selector} not found within ${timeout}ms`);
},
// Wait for element to disappear
async waitForElementToDisappear(selector, timeout = UI_CONFIG.TIMEOUTS.ELEMENT_WAIT) {
const startedAt = Date.now();
while (Date.now() - startedAt < timeout) {
const element = document.querySelector(selector);
if (!element) return;
await this.delay(UI_CONFIG.DELAYS.SHORT);
}
throw new Error(`Element ${selector} did not disappear within ${timeout}ms`);
},
// Find element by text content (legacy method)
async waitForElementByText(selector, textOptions, parent = document, timeout = UI_CONFIG.TIMEOUTS.ELEMENT_WAIT) {
const startedAt = Date.now();
const texts = Array.isArray(textOptions) ? textOptions : [textOptions];
while (Date.now() - startedAt < timeout) {
const elements = parent.querySelectorAll(selector);
const element = Array.from(elements).find(el => {
const textContent = el.textContent.trim();
return texts.some(text =>
textContent === text ||
textContent.includes(text) ||
(text === UI_CONFIG.STRINGS.DELETE && el.querySelector(".text-token-text-error"))
);
});
if (element) return element;
await this.delay(UI_CONFIG.DELAYS.SHORT);
}
return null;
},
// Find element using multiple strategies (language-independent)
async waitForElementByStrategy(operation, parent = document, timeout = UI_CONFIG.TIMEOUTS.ELEMENT_WAIT) {
const strategies = UI_CONFIG.BUTTON_STRATEGIES[operation.toUpperCase()];
if (!strategies) {
throw new Error(`No strategies defined for operation: ${operation}`);
}
const startedAt = Date.now();
while (Date.now() - startedAt < timeout) {
for (const strategy of strategies) {
if (strategy === 'text-fallback') {
// Fallback to text matching with multiple languages
// Dynamically get all strings for the operation
const prefix = operation === 'DELETE' ? 'DELETE' : 'ARCHIVE';
const textOptions = Object.entries(UI_CONFIG.STRINGS)
.filter(([key]) => key === prefix || key.startsWith(prefix + '_'))
.map(([, value]) => value);
const elements = parent.querySelectorAll('div[role="menuitem"]');
const element = Array.from(elements).find(el => {
const textContent = el.textContent.trim();
return textOptions.some(text =>
textContent === text || textContent.includes(text)
);
});
if (element) {
console.log(`Found ${operation} button using text fallback strategy, text: "${element.textContent.trim()}"`);
return element;
}
} else {
// Try CSS selector strategy
const element = parent.querySelector(strategy);
if (element) {
console.log(`Found ${operation} button using strategy: ${strategy}`);
return element;
}
}
}
await this.delay(UI_CONFIG.DELAYS.SHORT);
}
return null;
},
// Get selected conversations
getSelectedConversations() {
return [...document.querySelectorAll(UI_CONFIG.SELECTORS.conversationsCheckbox)];
},
// Remove all checkboxes
removeAllCheckboxes() {
const checkboxes = document.querySelectorAll(`.${CSS_CLASSES.CHECKBOX}`);
checkboxes.forEach(checkbox => checkbox.remove());
},
// Show notification
showNotification(message, type = 'info') {
console.log(`[${type.toUpperCase()}] ${message}`);
if (type === 'error') {
alert(message);
}
}
};
// Chrome API utilities
const ChromeUtils = {
// Get user info with error handling
getUserInfo() {
return new Promise((resolve, reject) => {
chrome.runtime.sendMessage({ action: "getUserInfo" }, (response) => {
if (chrome.runtime.lastError) {
reject(chrome.runtime.lastError);
} else if (response.error) {
reject(new Error(response.error));
} else {
resolve(response.userInfo);
}
});
});
},
// Send progress update
sendProgress(buttonId, progress) {
chrome.runtime.sendMessage({
action: "updateProgress",
buttonId: buttonId,
progress: progress
});
},
// Send operation complete
sendComplete(buttonId) {
chrome.runtime.sendMessage({
action: "operationComplete",
buttonId: buttonId
});
}
};
// API utilities
const APIUtils = {
// Generic API call with error handling
async makeRequest(endpoint, options = {}) {
try {
const url = `${API_CONFIG.BASE_URL}${endpoint}`;
const response = await fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
...options
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error(`API request failed for ${endpoint}:`, error);
throw error;
}
},
// Send analytics event
async sendEvent(action, count) {
try {
const userInfo = await ChromeUtils.getUserInfo();
const data = {
user_id: userInfo.id || "unknown",
timestamp: CommonUtils.generateTimestamp(),
action: action,
count: count
};
await this.makeRequest(API_CONFIG.ENDPOINTS.SEND_EVENT, {
method: 'POST',
body: JSON.stringify(data)
});
console.log(`Event '${action}' sent successfully`);
} catch (error) {
console.error(`Error sending '${action}' event:`, error);
}
},
// Check payment status
async checkPaymentStatus(userId) {
const endpoint = `${API_CONFIG.ENDPOINTS.CHECK_PAYMENT}?user_id=${encodeURIComponent(userId)}`;
return await this.makeRequest(endpoint);
}
};
// Export to global scope
window.CommonUtils = CommonUtils;
window.ChromeUtils = ChromeUtils;
window.APIUtils = APIUtils;
// For backward compatibility
window.getUserInfo = ChromeUtils.getUserInfo;
window.sendEventAsync = APIUtils.sendEvent;
} else {
console.log("utils.js already loaded, skipping re-initialization");
}