-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinjected.js
More file actions
566 lines (503 loc) · 25.4 KB
/
Copy pathinjected.js
File metadata and controls
566 lines (503 loc) · 25.4 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
// Our actual code that will run in the page's context
(async () => {
console.log('Injected script waiting for WhatsApp require...');
while (typeof window.require !== 'function') {
await new Promise(resolve => setTimeout(resolve, 100));
}
// Wait for WhatsApp's main UI to render before calling require(). Calling
// require() on a not-yet-registered module throws synchronously, and
// WhatsApp's ErrorUtils reports it as a red error + crashlog POST before
// our try/catch can intervene. Once the chat-list pane exists, the
// webpack registry is guaranteed to be populated.
const isWhatsAppReady = () =>
document.querySelector('#pane-side') ||
document.querySelector('[aria-label*="Chat list" i]') ||
document.querySelector('[data-testid="chat-list"]');
while (!isWhatsAppReady()) {
await new Promise(resolve => setTimeout(resolve, 300));
}
const loadWhatsAppModules = async (retryCount = 0, maxRetries = 3) => {
try {
window.Store = Object.assign({}, window.require('WAWebCollections'));
window.Store.DownloadManager = window.require('WAWebDownloadManager').downloadManager;
window.Store.Validators = window.require('WALinkify');
console.log('WhatsApp modules loaded successfully');
return true;
} catch (error) {
console.warn(`Failed to load WhatsApp modules (attempt ${retryCount + 1}/${maxRetries}):`, error);
if (retryCount < maxRetries) {
await new Promise(resolve => setTimeout(resolve, 2000));
return loadWhatsAppModules(retryCount + 1, maxRetries);
}
console.error('Failed to load WhatsApp modules after maximum retries');
return false;
}
};
// Initial load attempt
await loadWhatsAppModules();
// Resolve a message from the DOM's data-id. WhatsApp's current DOM emits
// only the bare message hash (e.g. "AC386A5F..."), so Store.Msg.get(id) —
// which keys by full _serialized — always misses. Scan chats' msgs
// collections and match by msg.id.id, prioritizing the active chat.
const findMsg = (id) => {
const Chat = window.Store && window.Store.Chat;
if (!Chat) return null;
const chats = Chat.getModelsArray ? Chat.getModelsArray() : (Chat.models || []);
const active = chats.find(c => c && c.active);
const ordered = active ? [active, ...chats.filter(c => c !== active)] : chats;
for (const chat of ordered) {
const models = chat && chat.msgs && (chat.msgs.getModelsArray
? chat.msgs.getModelsArray()
: chat.msgs.models);
if (!models) continue;
const found = models.find(m => m && m.id && m.id.id === id);
if (found) return found;
}
return null;
};
window.WWebJS = {};
window.WWebJS.getMessageModel = message => {
const msg = message.serialize();
msg.isEphemeral = message.isEphemeral;
msg.isStatusV3 = message.isStatusV3;
msg.links = (window.Store.Validators.findLinks(message.mediaObject ? message.caption : message.body)).map((link) => ({
link: link.href,
isSuspicious: Boolean(link.suspiciousCharacters && link.suspiciousCharacters.size)
}));
if (msg.buttons) {
msg.buttons = msg.buttons.serialize();
}
if (msg.dynamicReplyButtons) {
msg.dynamicReplyButtons = JSON.parse(JSON.stringify(msg.dynamicReplyButtons));
}
if (msg.replyButtons) {
msg.replyButtons = JSON.parse(JSON.stringify(msg.replyButtons));
}
if (typeof msg.id.remote === 'object') {
msg.id = Object.assign({}, msg.id, { remote: msg.id.remote._serialized });
}
delete msg.pendingAckUpdate;
return msg;
};
// Cache of transcriptions pulled from extension storage
let cachedTranscriptions = {};
const pendingRequests = new Map();
const isOutgoingId = (id) => typeof id === 'string' && id.startsWith('true_');
const INBOUND_BUTTON_X = 470;
const OUTBOUND_BUTTON_X = 470;
const buttonAnchors = new WeakMap();
const positionButton = (button, id) => {
if (!button) return;
const anchor = buttonAnchors.get(button);
const host = (anchor && anchor.host) || button.offsetParent || button.parentElement;
if (!host) return;
const hostRect = host.getBoundingClientRect();
const topPx = hostRect.height / 2;
if (isOutgoingId(id)) {
button.style.right = `${Math.round(OUTBOUND_BUTTON_X)}px`;
button.style.left = 'auto';
} else {
button.style.left = `${Math.round(INBOUND_BUTTON_X)}px`;
button.style.right = 'auto';
}
button.style.top = `${Math.round(topPx)}px`;
};
const requestSavedTranscriptions = () => {
window.postMessage({ type: 'GET_SAVED_TRANSCRIPTIONS' }, '*');
};
requestSavedTranscriptions(); // initial load
// Update the event listener for transcription responses
window.addEventListener('message', function (event) {
if (event.data.type === 'TRANSCRIBE_RESPONSE') {
const messageId = event.data.messageId;
const button = document.querySelector(`button[data-message-id="${messageId}"]`);
const transcriptionContainer = document.querySelector(`div.transcription-container[data-message-id="${messageId}"]`);
const textContentDiv = transcriptionContainer ? transcriptionContainer.querySelector('.transcription-text') : null;
if (button && transcriptionContainer && textContentDiv) {
const pending = pendingRequests.get(messageId);
if (pending && pending.timeoutId) {
clearTimeout(pending.timeoutId);
}
pendingRequests.delete(messageId);
const existingError = transcriptionContainer.querySelector('.error-message');
if (existingError) existingError.remove();
if (event.data.success) {
button.textContent = 'Transcribe again';
button.style.background = 'rgb(0 92 75)';
positionButton(button, messageId);
button.disabled = false;
transcriptionContainer.style.display = 'block';
textContentDiv.textContent = event.data.data.text;
// Content script persists it; update cache locally too
cachedTranscriptions[messageId] = { text: event.data.data.text, timestamp: Date.now() };
} else {
console.error('Transcription Error:', event.data.error);
button.textContent = 'Error - Try again';
button.style.background = '#f44336';
positionButton(button, messageId);
button.disabled = false;
// Show error message
const errorMessage = document.createElement('div');
errorMessage.className = 'error-message';
errorMessage.style.cssText = `
font-size: 12px;
color: #f44336;
margin-top: 4px;
padding: 4px 8px;
border-radius: 4px;
background: #f44336;
color: white;
`;
if (event.data.options && /API MISSING OR INVALID/i.test(event.data.error || '')) {
errorMessage.innerHTML = event.data.error + ' <a href="#" id="open-settings" style="color:#0084ff;text-decoration:underline;">Open settings</a>';
errorMessage.querySelector('a').addEventListener('click', () => {
window.postMessage({ type: 'OPEN_SETTINGS' }, '*');
});
} else {
errorMessage.textContent = event.data.error;
}
transcriptionContainer.appendChild(errorMessage);
}
}
}
});
// Listen for saved transcription payload
window.addEventListener('message', function (event) {
if (event.data.type === 'SAVED_TRANSCRIPTIONS') {
cachedTranscriptions = event.data.payload || {};
injectTranscribeButtons(document);
}
});
function injectTranscribeButtons(root = document) {
// WhatsApp dropped the <canvas> waveform from voice messages; the
// slider is now the reliable anchor for both voice messages (ptt)
// and audio-file attachments, and it's language-agnostic.
const audioAnchors = root.querySelectorAll('[role="slider"][aria-valuetext]:not([data-watr-processed])');
const savedTranscriptions = cachedTranscriptions;
// Define SVG icons as constants to avoid repetition
const SVG_ICONS = {
COPY: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="18" height="18" fill="gray"><path d="M16 1H4C2.9 1 2 1.9 2 3V17H4V3H16V1ZM19 5H8C6.9 5 6 5.9 6 7V21C6 22.1 6.9 23 8 23H19C20.1 23 21 22.1 21 21V7C21 5.9 20.1 5 19 5ZM19 21H8V7H19V21Z"/></svg>',
SUCCESS: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="18" height="18" fill="gray"><path d="M9 16.2L4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4L9 16.2z"/></svg>',
ERROR: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="18" height="18" fill="gray"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12 19 6.41z"/></svg>'
};
audioAnchors.forEach(audioAnchor => {
const messageElement = audioAnchor.closest('[data-id]');
const id = messageElement ? messageElement.getAttribute('data-id') : null;
if (!id || audioAnchor.dataset.watrProcessed) return;
if (document.querySelector(`button.transcribe-btn[data-message-id="${id}"]`)) {
audioAnchor.dataset.watrProcessed = 'true';
return;
}
const storeMsg = window.Store && window.Store.Msg && window.Store.Msg.get ? window.Store.Msg.get(id) : null;
const msgType = storeMsg && (storeMsg.type || (storeMsg.mediaData && storeMsg.mediaData.type));
if (msgType && !(msgType === 'audio' || msgType === 'ptt')) {
audioAnchor.dataset.watrProcessed = 'true';
return;
}
if (!msgType) {
const hasAudioPlay = messageElement && messageElement.querySelector('[data-icon="audio-play"], [data-icon="audio-pause"]');
const ariaAudio = messageElement && messageElement.querySelector('[aria-label*="mensagem de voz" i], [aria-label*="voice message" i]');
if (!hasAudioPlay && !ariaAudio) {
audioAnchor.dataset.watrProcessed = 'true';
return;
}
}
// Find the parent row element
const rowElement = messageElement.closest('[role="row"]');
// Create transcribe button
const button = document.createElement('button');
button.className = 'transcribe-btn';
button.textContent = 'Transcribe';
button.dataset.messageId = id; // Add message ID as data attribute
button.style.cssText = `
position: absolute;
top: 0;
transform: translateY(-50%);
font-size: 12px;
padding: 6px 10px;
z-index: 1000;
cursor: pointer;
background: #00a884;
color: white;
border: none;
border-radius: 4px;
`;
button.style.visibility = 'hidden';
// Create transcription container (hidden initially)
audioAnchor.style.position = 'relative';
const transcriptionContainer = document.createElement('div');
transcriptionContainer.className = 'transcription-container';
transcriptionContainer.dataset.messageId = id; // Add message ID as data attribute
transcriptionContainer.style.cssText = `
display: none;
padding: 6px 8px 8px;
margin: 0px 60px 4px;
background: rgb(240, 242, 245);
border-radius: 7.5px;
margin-top: 2px;
color: rgb(17, 27, 33);
user-select: text;
cursor: text;
position: relative;
overflow: hidden;
`;
// Create header div for copy button
const headerDiv = document.createElement('div');
headerDiv.style.cssText = `
position: absolute;
right: 6px;
background: radial-gradient(circle at top right,rgb(240, 242, 245) 40%,rgba(var(--outgoing-background-rgb),0) 80%);
`;
// Add copy button to header
const copyButton = document.createElement('button');
copyButton.innerHTML = SVG_ICONS.COPY;
copyButton.title = "Copy transcription";
copyButton.style.cssText = `
padding: 2px;
cursor: pointer;
background: transparent;
border: none;
display: flex;
align-items: center;
justify-content: center;
`;
headerDiv.appendChild(copyButton);
transcriptionContainer.appendChild(headerDiv);
// Create a wrapper for the text content
const textContentDiv = document.createElement('div');
textContentDiv.className = 'transcription-text selectable-text';
textContentDiv.style.cssText = `
font-size: 14.2px;
line-height: 19px;
user-select: text;
-webkit-user-select: text;
-moz-user-select: text;
-ms-user-select: text;
margin-top: 0;
padding: 0;
`;
transcriptionContainer.appendChild(textContentDiv);
// Small text at the bottom of the transcription container
const smallText = document.createElement('p');
smallText.innerHTML = 'This transcription is only visible to you through the WhatsApp Transcriber extension';
smallText.style.cssText = `
font-size: 11px;
color: rgb(79 168 54);
font-style: italic;
margin: 8px 0 0;
padding: 0;
`;
transcriptionContainer.appendChild(smallText);
// Insert after the row element
if ((rowElement && rowElement.nextSibling && !rowElement.nextSibling.classList.contains('transcription-container')) || (rowElement && rowElement === rowElement.parentNode.lastElementChild)) {
rowElement.parentNode.insertBefore(transcriptionContainer, rowElement.nextSibling);
}
// Check if we have a saved transcription and change state
if (savedTranscriptions[id]) {
transcriptionContainer.style.display = 'block';
textContentDiv.textContent = savedTranscriptions[id].text;
button.textContent = 'Transcribe again';
button.style.background = 'rgb(0 92 75)';
positionButton(button, id);
}
// Add copy button click handler
copyButton.addEventListener('click', async function () {
// Get the text from the textContentDiv
const textToCopy = textContentDiv.textContent;
try {
// Use the Async Clipboard API
await navigator.clipboard.writeText(textToCopy);
// Visual feedback
const originalHTML = copyButton.innerHTML;
copyButton.innerHTML = SVG_ICONS.SUCCESS;
setTimeout(() => {
copyButton.innerHTML = originalHTML;
}, 2000);
} catch (err) {
console.error('Failed to copy using Clipboard API:', err);
// Fallback only if the browser doesn't support the API or if we're not in a secure context
if (!navigator.clipboard || !window.isSecureContext) {
const textarea = document.createElement('textarea');
textarea.value = textToCopy;
textarea.style.position = 'fixed';
textarea.style.opacity = '0';
document.body.appendChild(textarea);
textarea.select();
try {
document.execCommand('copy');
copyButton.innerHTML = SVG_ICONS.SUCCESS;
} catch (e) {
console.error('Fallback copy failed:', e);
copyButton.innerHTML = SVG_ICONS.ERROR;
}
document.body.removeChild(textarea);
setTimeout(() => {
copyButton.innerHTML = SVG_ICONS.COPY;
}, 2000);
} else {
// Show error indicator if Clipboard API fails in a secure context
copyButton.innerHTML = SVG_ICONS.ERROR;
setTimeout(() => {
copyButton.innerHTML = SVG_ICONS.COPY;
}, 2000);
}
}
});
// Add transcribe button click handler
button.addEventListener('click', async () => {
try {
const existingError = transcriptionContainer.querySelector('.error-message');
if (existingError) existingError.remove();
button.textContent = 'Transcribing...';
positionButton(button, id);
button.disabled = true;
button.style.background = '#999999';
const timeoutId = setTimeout(() => {
button.textContent = 'Timed out';
positionButton(button, id);
button.style.background = '#f44336';
button.disabled = false;
}, 60000);
pendingRequests.set(id, { timeoutId });
const storeMsg = findMsg(id);
if (!storeMsg) {
throw new Error('Message not found (scroll to the message in the chat and try again)');
}
let mediaData = storeMsg.mediaData;
const msgType = storeMsg.type || (mediaData && mediaData.type);
if (!(msgType === 'audio' || msgType === 'ptt')) {
button.textContent = 'Not an audio message';
positionButton(button, id);
button.style.background = '#f44336';
button.disabled = false;
return;
}
const dlMgr = window.Store.DownloadManager;
const signal = new AbortController().signal;
if (!mediaData && typeof storeMsg.downloadMedia === 'function') {
await storeMsg.downloadMedia({
downloadEvenIfExpensive: true,
rmrReason: 1
});
mediaData = storeMsg.mediaData;
}
if (mediaData) {
const stage = mediaData.mediaStage;
if (stage === 'REUPLOADING') {
throw new Error('Media expired (WhatsApp is reuploading)');
}
if (stage !== 'RESOLVED' && typeof storeMsg.downloadMedia === 'function') {
await storeMsg.downloadMedia({
downloadEvenIfExpensive: true,
rmrReason: 1
});
mediaData = storeMsg.mediaData || mediaData;
}
const refreshedStage = mediaData && mediaData.mediaStage;
if (refreshedStage === 'FETCHING' || (typeof refreshedStage === 'string' && refreshedStage.includes('ERROR'))) {
throw new Error('Media not ready for download');
}
}
let blobData;
if (dlMgr.downloadAndMaybeDecrypt && mediaData) {
const mockQpl = {
addAnnotations: function () { return this; },
addPoint: function () { return this; }
};
blobData = await dlMgr.downloadAndMaybeDecrypt({
directPath: mediaData.directPath || storeMsg.directPath,
encFilehash: mediaData.encFilehash || storeMsg.encFilehash,
filehash: mediaData.filehash || storeMsg.filehash,
mediaKey: mediaData.mediaKey || storeMsg.mediaKey,
mediaKeyTimestamp: mediaData.mediaKeyTimestamp || storeMsg.mediaKeyTimestamp,
type: msgType,
signal,
downloadQpl: mockQpl
});
} else if (dlMgr.downloadAndDecrypt) {
const mediaInfo = mediaData || storeMsg;
if (!mediaInfo || !mediaInfo.directPath) {
throw new Error('Missing media info for downloadAndDecrypt');
}
blobData = await dlMgr.downloadAndDecrypt({
directPath: mediaInfo.directPath,
encFilehash: mediaInfo.encFilehash,
filehash: mediaInfo.filehash,
mediaKey: mediaInfo.mediaKey,
mediaKeyTimestamp: mediaInfo.mediaKeyTimestamp,
type: msgType,
signal,
});
} else {
throw new Error('Download manager unavailable');
}
const mimeType = (mediaData && mediaData.mimetype) || 'audio/webm';
const blob = new Blob([blobData], { type: mimeType });
const reader = new FileReader();
reader.onload = async function () {
if (!reader.result || typeof reader.result !== 'string') return;
const audioData = reader.result.split(',')[1];
// Send message to content script
window.postMessage({
type: 'TRANSCRIBE_AUDIO',
audioData: audioData,
messageId: id,
mimeType
}, '*');
};
reader.readAsDataURL(blob);
} catch (error) {
console.error('Processing Error:', error);
button.textContent = 'Error - Try again';
positionButton(button, id);
button.style.background = '#f44336';
button.disabled = false;
const pending = pendingRequests.get(id);
if (pending && pending.timeoutId) clearTimeout(pending.timeoutId);
pendingRequests.delete(id);
}
});
const buttonHost = rowElement || messageElement || audioAnchor.parentElement || audioAnchor;
if (buttonHost) {
buttonHost.style.position = buttonHost.style.position || 'relative';
buttonHost.style.overflow = 'visible';
buttonHost.appendChild(button);
buttonAnchors.set(button, { host: buttonHost });
requestAnimationFrame(() => {
positionButton(button, id);
button.style.visibility = 'visible';
});
}
audioAnchor.dataset.watrProcessed = 'true';
});
}
async function setupMutationObserver(retries = 0) {
const MAX_RETRIES = 5;
const container = document.body;
if (!container && retries < MAX_RETRIES) {
console.log(`Message container not found - retry ${retries + 1}/${MAX_RETRIES}`);
await new Promise(resolve => setTimeout(resolve, 2000));
return setupMutationObserver(retries + 1);
}
if (!container) {
throw new Error('Failed to find message container after multiple attempts');
}
let scheduled = false;
const scheduleInject = () => {
if (scheduled) return;
scheduled = true;
requestAnimationFrame(() => {
scheduled = false;
injectTranscribeButtons(document);
});
};
new MutationObserver(scheduleInject).observe(container, {
childList: true,
subtree: true
});
console.log("Mutation observer active on:", container);
return container;
}
injectTranscribeButtons(document);
setupMutationObserver();
})();