-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWhatsApp-Web-Transcriber.user.js
More file actions
410 lines (355 loc) · 16.2 KB
/
Copy pathWhatsApp-Web-Transcriber.user.js
File metadata and controls
410 lines (355 loc) · 16.2 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
// ==UserScript==
// @name WhatsApp Web Transcriber
// @namespace http://tampermonkey.net/
// @version 1.6
// @description Transcribes WhatsApp voice messages with one click (Fixed Emoji Rendering)
// @author DevEmperor
// @match https://web.whatsapp.com/*
// @grant GM_xmlhttpRequest
// @grant unsafeWindow
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_registerMenuCommand
// @connect api.groq.com
// @updateURL https://raw.githubusercontent.com/DevEmperor/WhatsApp-Web-Transcriber/main/WhatsApp-Web-Transcriber.user.js
// @downloadURL https://raw.githubusercontent.com/DevEmperor/WhatsApp-Web-Transcriber/main/WhatsApp-Web-Transcriber.user.js
// ==/UserScript==
(function() {
'use strict';
// === SETTINGS MANAGEMENT ===
const API_KEY_NAME = 'GROQ_API_KEY';
const LANGUAGE_NAME = 'GROQ_LANGUAGE';
let apiKey = GM_getValue(API_KEY_NAME, '');
let targetLanguage = GM_getValue(LANGUAGE_NAME, ''); // Empty means auto-detect
function checkAndGetApiKey() {
if (!apiKey || apiKey.trim() === '') {
apiKey = prompt("🤖 WhatsApp Voice Transcriber\n\nPlease enter your Groq API Key (gsk_...):\n(You can get one for free at console.groq.com/keys)");
if (apiKey && apiKey.trim() !== '') {
GM_setValue(API_KEY_NAME, apiKey.trim());
alert("✅ API Key saved successfully!");
}
}
return apiKey;
}
// Menu: Change API Key
GM_registerMenuCommand("🔑 Change API Key", () => {
const newKey = prompt("Enter new Groq API Key (leave blank to cancel):", apiKey);
if (newKey && newKey.trim() !== '') {
apiKey = newKey.trim();
GM_setValue(API_KEY_NAME, apiKey);
alert("✅ API Key updated successfully!");
}
});
// Menu: Change Language
GM_registerMenuCommand("🌐 Change Language (Auto/Manual)", () => {
const promptText = "Enter a 2-letter language code (e.g., 'en' for English, 'de' for German, 'es' for Spanish).\n\nLeave the field completely blank to use Auto-Detect:";
const newLang = prompt(promptText, targetLanguage);
if (newLang !== null) {
targetLanguage = newLang.trim().toLowerCase();
GM_setValue(LANGUAGE_NAME, targetLanguage);
if (targetLanguage === '') {
alert("✅ Language set to Auto-Detect!");
} else {
alert(`✅ Language explicitly set to: '${targetLanguage}'`);
}
}
});
// --- 1. CSP BYPASS VIA UNSAFEWINDOW ---
const originalClick = unsafeWindow.HTMLAnchorElement.prototype.click;
unsafeWindow.HTMLAnchorElement.prototype.click = function() {
if (unsafeWindow.__transcriberTrapArmed === true && this.download) {
unsafeWindow.__transcriberTrapArmed = false;
document.dispatchEvent(new CustomEvent('AudioCaught', { detail: this.href }));
return;
}
return originalClick.apply(this, arguments);
};
// --- 2. TAMPERMONKEY LOGIC ---
let currentSession = null;
document.addEventListener('AudioCaught', async (e) => {
if (!currentSession) return;
const blobUrl = e.detail;
const { btnWrapper, btn, isOut } = currentSession;
currentSession = null;
setBtnState(btn, 'upload', isOut);
try {
const response = await fetch(blobUrl);
const blob = await response.blob();
sendToAPI(blob, btnWrapper, btn, isOut);
} catch (err) {
console.error("Fetch error:", err);
showError(btn, btnWrapper, "File error", isOut);
}
});
// Manages dynamic button states and colors
function setBtnState(btn, state, isOut) {
btn.dataset.state = state;
const defaultColor = isOut ? '#144d37' : '#242626';
if (state === 'idle') {
btn.innerHTML = '📄 Transcribe';
btn.style.backgroundColor = defaultColor;
} else if (state === 'menu') {
btn.innerHTML = '🔍 Finding menu...';
btn.style.backgroundColor = '#8696a0';
} else if (state === 'download') {
btn.innerHTML = '⏳ Extracting...';
btn.style.backgroundColor = '#8696a0';
} else if (state === 'upload') {
btn.innerHTML = '🚀 Transcribing...';
btn.style.backgroundColor = '#8696a0';
} else if (state === 'close') {
btn.innerHTML = '✖ Close';
btn.style.backgroundColor = '#d14553'; // Red
} else if (state === 'error') {
btn.innerHTML = '🔄 Try again';
btn.style.backgroundColor = '#d14553'; // Red
}
}
function findAndInjectButtons() {
const voiceMessageLabels = document.querySelectorAll('span[aria-label="Voice message"]');
voiceMessageLabels.forEach(label => {
const messageContainer = label.closest('[role="row"]');
if (!messageContainer) return;
const coloredBubble = label.closest('._ak4a, ._ak49') || label.closest('[data-testid="msg-container"] > div > div');
if (!coloredBubble || coloredBubble.querySelector('.wa-transcribe-wrapper')) return;
let isOut = false;
if (coloredBubble.classList.contains('_ak4a') || messageContainer.classList.contains('message-out')) {
isOut = true;
} else if (messageContainer.querySelector('[data-testid*="msg-dblcheck"], [data-testid*="msg-check"], [data-testid*="msg-time"], [data-icon*="msg-dblcheck"], [data-icon*="msg-check"], [data-icon*="msg-time"]')) {
isOut = true;
} else {
const rowRect = messageContainer.getBoundingClientRect();
const bubbleRect = coloredBubble.getBoundingClientRect();
if (rowRect.width > 0 && bubbleRect.width > 0) {
const isRightAligned = (bubbleRect.left + bubbleRect.width / 2) > (rowRect.left + rowRect.width / 2);
isOut = document.dir === 'rtl' ? !isRightAligned : isRightAligned;
}
}
const timeStampContainer = coloredBubble.querySelector('._ak4s');
if (timeStampContainer && !timeStampContainer.dataset.anchored) {
if (window.getComputedStyle(coloredBubble).position === 'static') {
coloredBubble.style.position = 'relative';
}
const tsRect = timeStampContainer.getBoundingClientRect();
const bubbleRect = coloredBubble.getBoundingClientRect();
const topOffset = tsRect.top - bubbleRect.top;
const rightOffset = bubbleRect.right - tsRect.right;
timeStampContainer.style.position = 'absolute';
timeStampContainer.style.top = topOffset + 'px';
timeStampContainer.style.right = rightOffset + 'px';
timeStampContainer.style.bottom = 'auto';
timeStampContainer.style.left = 'auto';
timeStampContainer.style.margin = '0';
timeStampContainer.dataset.anchored = "true";
}
const btnWrapper = document.createElement('div');
btnWrapper.className = 'wa-transcribe-wrapper';
Object.assign(btnWrapper.style, {
display: 'block',
width: '100%',
boxSizing: 'border-box',
marginTop: '26px',
paddingTop: '8px',
borderTop: isOut ? '1px solid rgba(255, 255, 255, 0.15)' : '1px solid rgba(255, 255, 255, 0.05)',
clear: 'both'
});
const buttonGroup = document.createElement('div');
Object.assign(buttonGroup.style, {
display: 'flex',
gap: '8px',
width: '100%'
});
const copyBtn = document.createElement('button');
copyBtn.className = 'wa-copy-btn';
copyBtn.innerHTML = '📋 Copy';
Object.assign(copyBtn.style, {
padding: '6px 12px',
color: 'white',
backgroundColor: '#404a4e',
border: 'none',
borderRadius: '8px',
cursor: 'pointer',
fontSize: '13px',
fontWeight: 'bold',
flex: '1',
display: 'none',
textAlign: 'center',
transition: 'background-color 0.2s'
});
const btn = document.createElement('button');
btn.className = 'wa-transcribe-btn';
Object.assign(btn.style, {
padding: '6px 12px',
color: 'white',
border: 'none',
borderRadius: '8px',
cursor: 'pointer',
fontSize: '13px',
fontWeight: 'bold',
flex: '2',
boxSizing: 'border-box',
textAlign: 'center',
transition: 'background-color 0.2s'
});
setBtnState(btn, 'idle', isOut);
btn.onclick = () => {
if (btn.dataset.state === 'close' || btn.dataset.state === 'error') {
const textDiv = btnWrapper.querySelector('.wa-transcript-text');
if (textDiv) textDiv.remove();
setBtnState(btn, 'idle', isOut);
copyBtn.style.display = 'none';
} else if (btn.dataset.state === 'idle') {
const currentKey = checkAndGetApiKey();
if (currentKey && currentKey.trim() !== '') {
startDownloadTrick(messageContainer, coloredBubble, btnWrapper, btn, isOut);
} else {
showError(btn, btnWrapper, "Missing API Key", isOut);
}
}
};
buttonGroup.appendChild(copyBtn);
buttonGroup.appendChild(btn);
btnWrapper.appendChild(buttonGroup);
coloredBubble.appendChild(btnWrapper);
});
}
function startDownloadTrick(messageContainer, coloredBubble, btnWrapper, btn, isOut) {
setBtnState(btn, 'menu', isOut);
currentSession = { btnWrapper: btnWrapper, btn: btn, isOut: isOut };
unsafeWindow.__transcriberTrapArmed = true;
const playBtn = messageContainer.querySelector('button[aria-label="Play voice message"], button[aria-label="Pause voice message"]');
const targetElement = playBtn || coloredBubble;
const rect = targetElement.getBoundingClientRect();
const rightClickEvent = new MouseEvent('contextmenu', {
bubbles: true, cancelable: true, view: unsafeWindow,
button: 2, buttons: 2,
clientX: rect.left + (rect.width / 2),
clientY: rect.top + (rect.height / 2)
});
targetElement.dispatchEvent(rightClickEvent);
let attempts = 0;
const findMenuInterval = setInterval(() => {
attempts++;
const downloadBtn = document.querySelector('[aria-label="Download"], [aria-label="Herunterladen"]');
if (downloadBtn) {
clearInterval(findMenuInterval);
setBtnState(btn, 'download', isOut);
downloadBtn.click();
} else if (attempts > 40) {
clearInterval(findMenuInterval);
showError(btn, btnWrapper, "Menu error", isOut);
document.body.click();
unsafeWindow.__transcriberTrapArmed = false;
}
}, 50);
setTimeout(() => {
if (unsafeWindow.__transcriberTrapArmed === true) {
unsafeWindow.__transcriberTrapArmed = false;
if (currentSession && currentSession.btn === btn) {
showError(btn, btnWrapper, "Timeout", isOut);
document.body.click();
currentSession = null;
}
}
}, 4000);
}
function sendToAPI(blob, btnWrapper, btn, isOut) {
let textDiv = btnWrapper.querySelector('.wa-transcript-text');
if (!textDiv) {
textDiv = createTextContainer(isOut);
updateTextContent(textDiv, "...", false);
btnWrapper.insertBefore(textDiv, btnWrapper.firstChild);
}
const formData = new FormData();
formData.append('file', blob, 'voice_message.ogg');
formData.append('model', 'whisper-large-v3');
if (targetLanguage && targetLanguage !== '') {
formData.append('language', targetLanguage);
}
GM_xmlhttpRequest({
method: "POST",
url: "https://api.groq.com/openai/v1/audio/transcriptions",
headers: { "Authorization": `Bearer ${apiKey}` },
data: formData,
onload: function(res) {
if (res.status === 200) {
const resultText = JSON.parse(res.responseText).text;
updateTextContent(textDiv, resultText, false);
setBtnState(btn, 'close', isOut);
const copyBtn = btnWrapper.querySelector('.wa-copy-btn');
if (copyBtn) {
copyBtn.style.display = 'block';
copyBtn.onclick = () => {
navigator.clipboard.writeText(resultText).then(() => {
copyBtn.innerHTML = '✅ Copied!';
copyBtn.style.backgroundColor = '#144d37';
setTimeout(() => {
copyBtn.innerHTML = '📋 Copy';
copyBtn.style.backgroundColor = '#404a4e';
}, 2000);
});
};
}
} else {
showError(btn, btnWrapper, `API Error ${res.status}`, isOut);
}
},
onerror: function() {
showError(btn, btnWrapper, "Offline", isOut);
}
});
}
// --- NEW: Helper Function for safe and robust formatting ---
function updateTextContent(container, text, isError) {
container.innerHTML = ''; // Clear previous content
const iconSpan = document.createElement('span');
iconSpan.innerText = isError ? '🤖 ❌ ' : '🤖 ';
iconSpan.style.fontStyle = 'normal'; // Fix for Emoji Rendering!
iconSpan.style.marginRight = '4px';
const textSpan = document.createElement('span');
textSpan.innerText = text;
textSpan.style.fontStyle = 'italic'; // Text remains italic
container.appendChild(iconSpan);
container.appendChild(textSpan);
}
function showError(btn, btnWrapper, msg, isOut) {
setBtnState(btn, 'error', isOut);
let textDiv = btnWrapper.querySelector('.wa-transcript-text');
if (textDiv) updateTextContent(textDiv, msg, true);
}
function createTextContainer(isOut) {
const div = document.createElement('div');
div.className = 'wa-transcript-text';
const bgColor = isOut ? 'rgba(0, 0, 0, 0.15)' : 'rgba(255, 255, 255, 0.05)';
Object.assign(div.style, {
padding: '8px 12px',
marginBottom: '8px',
backgroundColor: bgColor,
borderRadius: '8px',
fontSize: '14px',
lineHeight: '1.4',
color: 'var(--primary-text)',
wordWrap: 'break-word',
width: '100%',
boxSizing: 'border-box'
});
// fontStyle: 'italic' was removed here and moved to updateTextContent
return div;
}
let isThrottled = false;
const observer = new MutationObserver(() => {
if (!isThrottled) {
isThrottled = true;
requestAnimationFrame(() => {
findAndInjectButtons();
setTimeout(() => { isThrottled = false; }, 100);
});
}
});
setTimeout(() => {
console.log("🚀 Voice Transcriber started.");
setTimeout(checkAndGetApiKey, 1000);
findAndInjectButtons();
observer.observe(document.body, { childList: true, subtree: true });
}, 1500);
})();