-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
563 lines (482 loc) · 15.1 KB
/
background.js
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
import detectLang from "./lang-detector";
import { encode } from "./base64";
import moment from "moment-timezone";
let ray_so_tabId;
let facebook_tabId;
let data = {};
const facebookAutoPostScript = (query, data, imageBase64) => {
const imageBlob = base64ToBlob(imageBase64);
console.log(query, data, imageBlob);
function clickOnDiv(div) {
const clickEvent = new MouseEvent("click", {
view: window,
bubbles: true,
cancelable: true,
});
div.dispatchEvent(clickEvent);
}
function base64ToBlob(base64String) {
const [dataType, base64Data] = base64String.split(";base64,");
const contentType = dataType.split(":")[1];
const byteCharacters = atob(base64Data);
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
return new Blob([byteArray], { type: contentType });
}
function getPopupOpenerDiv() {
const spans = document.querySelectorAll("span");
for (const span of spans) {
const text = span.textContent.trim();
if (text.includes("Photo/video")) {
// Check if the text starts with "Photo/video"
if (text.indexOf("Photo/video") === 0) {
// Get the parent div of the parent div of this span
const parentDiv = span.closest("div");
if (parentDiv && parentDiv.parentElement) {
return parentDiv.parentElement;
}
}
}
}
return null; // If not found
}
function getLexicalEditorCaptionDiv() {
const elements = document.querySelectorAll(
'div[contenteditable="true"][role="textbox"][data-lexical-editor="true"]'
);
for (const element of elements) {
const ariaLabel = element.getAttribute("aria-label");
if (ariaLabel && ariaLabel.includes("What's on your mind")) {
return element;
}
}
return null; // If not found
}
function handleCaptionEditor(lexicalEditor) {
waitForElm("p", lexicalEditor).then((pTag) => {
// ensuring the editor is loaded
const inputEvent = new InputEvent("input", {
data: data.caption,
inputType: "insertText",
dataTransfer: null,
isComposing: false,
bubbles: true,
});
lexicalEditor.dispatchEvent(inputEvent);
handleInsertPostImage(imageBlob);
});
}
function handleInsertPostImage(blobImg) {
// Ensure that blobImg contains valid data
if (!blobImg) {
console.error("Invalid blob data");
return;
}
console.log(blobImg);
// Get the input element
var inputElement = document.querySelector(
'input[type="file"][accept="image/*,image/heif,image/heic,video/*,video/mp4,video/x-m4v,video/x-matroska,.mkv"]'
);
// Ensure that the input element is found
if (!inputElement) {
console.error("Input element not found");
return;
}
console.log("Input element:", inputElement);
// Create a File object from the Blob
var file = new File([blobImg], "image.jpg", { type: "image/png" });
console.log("File:", file);
// Get the div element that acts as the drop target
var dropTargetDiv = inputElement.parentElement.querySelector(
'div[role="button"][tabindex="0"]'
);
if (!dropTargetDiv) {
console.error("Drop target div not found");
return;
}
// Create a new DataTransfer object
var dataTransfer = new DataTransfer();
// Add the file to the DataTransfer object
dataTransfer.items.add(file);
// Create a drop event
var dropEvent = new DragEvent("drop", {
bubbles: true,
cancelable: true,
dataTransfer: dataTransfer,
});
// Dispatch the drop event on the drop target div
dropTargetDiv.dispatchEvent(dropEvent);
handleClickPostButton();
}
function handleClickPostButton() {
let postButton = document.querySelector(
'div[aria-label="Post"][role="button"]'
);
waitForClickable(postButton, function () {
clickOnDiv(postButton);
});
}
function waitForClickable(element, callback) {
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (
mutation.type === "attributes" &&
mutation.attributeName === "tabindex"
) {
callback();
observer.disconnect();
}
});
});
observer.observe(element, { attributes: true });
}
const waitForElm = (selector, parentNode = null, timeout = null) =>
new Promise((resolve, reject) => {
if (!selector) reject("no selector");
if (!parentNode) parentNode = globalThis.document.body;
const checkNode = (node) => {
if (node.matches(selector)) {
resolve(node);
observer.disconnect();
}
};
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
const addedNodes = Array.from(mutation.addedNodes);
addedNodes.forEach((node) => {
checkNode(node);
if (node.querySelectorAll) {
const descendants = Array.from(node.querySelectorAll(selector));
descendants.forEach((descendant) => {
checkNode(descendant);
});
}
});
});
});
observer.observe(parentNode, {
childList: true,
subtree: true,
});
if (timeout) {
setTimeout(() => {
observer.disconnect();
reject("timeout");
}, timeout);
}
});
// Function to create a MutationObserver
const observeDOMChanges = (findDesiredElement, callback) => {
const targetNode = document.body;
const config = { childList: true, subtree: true };
const mutationCallback = (mutationsList, observer) => {
for (const mutation of mutationsList) {
if (mutation.type === "childList") {
const desiredElement = findDesiredElement();
if (desiredElement) {
observer.disconnect();
callback(desiredElement);
break;
}
}
}
};
const observer = new MutationObserver(mutationCallback);
observer.observe(targetNode, config);
return observer; // Return the observer in case it needs to be disconnected externally
};
// Begins here
const popupOpenerDiv = getPopupOpenerDiv();
if (popupOpenerDiv) {
clickOnDiv(popupOpenerDiv);
observeDOMChanges(getLexicalEditorCaptionDiv, handleCaptionEditor);
} else {
console.error(`"Create Post" Popup opener div not found`);
}
};
const prepareCodeBlockImageScript = (query, data) => {
const titleSpan = document.querySelector(query.title);
if (titleSpan) {
titleSpan.innerHTML = "";
} else {
console.error(`Target not found: ${query.title}`);
}
const backgroundContainer = document.querySelector(query.background);
if (backgroundContainer) {
backgroundContainer.style.backgroundImage = `linear-gradient(140deg, rgb(165, 176, 188), rgb(169, 181, 193))`;
} else {
console.error(`Target not found: ${query.background}`);
}
const headerButtons = document.querySelectorAll(query.headerButtons);
if (headerButtons.length) {
const colors = ["#ff644e", "#ffbf29", "#27ca36"];
headerButtons.forEach((child, index) => {
child.style.backgroundColor = colors[index % colors.length];
});
} else {
console.error(`Target not found: ${query.background}`);
}
const exportButton = document.querySelector(query.exportButton);
if (exportButton) {
exportButton.click();
} else {
console.error(`Target not found: ${query.exportButton}`);
}
};
async function executeScriptOnTabLoad(tabId, script, ...args) {
return new Promise((resolve, reject) => {
const tabUpdated = new Promise((innerResolve) => {
chrome.tabs.onUpdated.addListener(function listener(
updatedTabId,
changeInfo
) {
if (updatedTabId === tabId && changeInfo.status === "complete") {
chrome.tabs.onUpdated.removeListener(listener);
innerResolve();
}
});
});
tabUpdated.then(async () => {
try {
// Convert blob to data URL using FileReader
const argsWithBlobConverted = await Promise.all(
args.map(async (arg) => {
if (arg instanceof Blob) {
return new Promise((resolveReader, rejectReader) => {
const reader = new FileReader();
reader.onload = function () {
resolveReader(reader.result);
};
reader.onerror = function (error) {
rejectReader(error);
};
reader.readAsDataURL(arg);
});
}
return arg;
})
);
console.log("Args", argsWithBlobConverted);
await chrome.scripting.executeScript({
target: { tabId: tabId },
func: script,
args: argsWithBlobConverted,
});
resolve();
} catch (error) {
reject(error);
}
});
});
}
function openRaySoTab(data, encodedCode) {
return new Promise((resolve, reject) => {
let openTabUrl = "https://ray.so/#code=" + encodedCode;
chrome.tabs.create({ url: openTabUrl, active: false }, (tab) => {
if (tab) {
ray_so_tabId = tab.id;
resolve(tab.id);
} else {
reject(new Error("Failed to create a new tab for ray.so"));
}
});
});
}
function downloadCodeImage(data, encodedCode) {
return new Promise(async (resolve, reject) => {
try {
if (ray_so_tabId) {
chrome.tabs.remove(ray_so_tabId);
ray_so_tabId = undefined;
}
let newTabId = await openRaySoTab(data, encodedCode);
let selectors = {
title: 'div.Frame_fileName__zfOJA span[data-ignore-in-export="true"]',
background: "div.Frame_frame__CAiHj",
headerButtons: "div.Frame_controls__xPHKk div.Frame_control__WM3BS",
exportButton: "button.ExportButton_button__MA4PI",
};
await executeScriptOnTabLoad(
newTabId,
prepareCodeBlockImageScript,
selectors,
data
);
resolve(newTabId);
} catch (error) {
console.log(error);
reject(error);
}
});
}
function getTodaysDate() {
const today = moment();
const day = today.format("Do");
const month = today.format("MMM");
const year = today.format("YY");
return `${day} ${month}'${year}`;
}
const handleSelectedText = (message) => {
// let info = message.info;
let tab = message.tab;
let parsed_code = message.selectedText;
let problem_name = message.problemName;
let detected_language = detectLang(parsed_code);
chrome.tabs.sendMessage(tab.id, {
action: "openCustomPopup",
data: {
language: detected_language,
problem_name,
code: parsed_code,
date: getTodaysDate(),
},
});
console.log("Sent the message to open the popup");
};
const handleProcessedData = async (message) => {
data = message.data;
await downloadCodeImage(data, encode(data.code));
};
chrome.contextMenus.removeAll(() => {
chrome.contextMenus.create({
title: "Share to social media",
contexts: ["selection"],
id: "share_menu_item",
});
});
chrome.contextMenus.onClicked.addListener(async (info, tab) => {
if (info.menuItemId === "share_menu_item") {
chrome.tabs.sendMessage(tab.id, {
action: "getSelectedText",
info,
tab,
});
}
});
// Message listener function
chrome.runtime.onMessage.addListener(async function onMessage(message, _, __) {
if (message.action === "selectedText") {
handleSelectedText(message);
} else if (message.action === "processedData") {
await handleProcessedData(message);
}
});
function getLatestDownloadedFile() {
return new Promise((resolve, reject) => {
chrome.downloads.search(
{
filenameRegex: "ray-so-export(?:\\s*\\(\\d+\\))?\\.png",
orderBy: ["-startTime"],
limit: 1,
},
function (downloadItems) {
if (downloadItems && downloadItems.length > 0) {
const latestDownload = downloadItems[0];
resolve(latestDownload);
} else {
reject(new Error("No matching files found"));
}
}
);
});
}
async function readLatestDownloadedFile() {
try {
const latestDownload = await getLatestDownloadedFile();
const fileURL = "file://" + latestDownload.filename;
// Fetch the file content using the Fetch API
const response = await fetch(fileURL);
if (response.ok) {
const blobData = await response.blob();
console.log(blobData);
return blobData;
} else {
// console.log("Fetch Error:", response.statusText);
return null;
}
} catch (error) {
// console.log("Error reading latest downloaded file:", error);
return null;
}
}
chrome.downloads.onChanged.addListener(async function onDownloadChanged(
downloadDelta
) {
if (downloadDelta.state && downloadDelta.state.current === "complete") {
if (ray_so_tabId) {
chrome.tabs.remove(ray_so_tabId);
ray_so_tabId = undefined;
}
let imageBlob = await readLatestDownloadedFile();
console.log("Image Blob:", imageBlob);
console.log("Code Data:", data);
if(!imageBlob) {
return;
}
await uploadToFacebook(data, imageBlob);
// Handle the image blob as needed
}
});
async function uploadToFacebook(data, imageBlob) {
return new Promise(async (resolve, reject) => {
try {
let tabId = await openFacebookTab();
console.log("Facebook Tab ID: ", tabId);
let selectors = {
postBar: 'div[role="button"][tabindex="0"] > div:has(span)',
};
// Activate the tab temporarily
await chrome.tabs.update(tabId, { active: true });
// Perform actions on the tab
await executeScriptOnTabLoad(
tabId,
facebookAutoPostScript,
selectors,
data,
imageBlob
);
// Deactivate the tab again
await chrome.tabs.update(tabId, { active: false });
resolve(tabId);
} catch (error) {
console.log(error);
reject(error);
}
});
}
function openFacebookTab() {
function createNewFacebookTab(resolve, reject) {
chrome.tabs.create(
{ url: "https://facebook.com", active: false },
(tab) => {
if (tab) {
facebook_tabId = tab.id; // Store the new tab ID
resolve(tab.id);
} else {
reject(new Error("Failed to create a new Facebook tab"));
}
}
);
}
return new Promise((resolve, reject) => {
// Check if the Facebook tab is already open
if (facebook_tabId) {
chrome.tabs.get(facebook_tabId, (tab) => {
if (chrome.runtime.lastError || !tab) {
// If tab is not found, create a new one
createNewFacebookTab(resolve, reject);
} else {
// If tab is found, reuse it
chrome.tabs.update(facebook_tabId, { url: "https://facebook.com" });
resolve(facebook_tabId);
}
});
} else {
// If tab ID is not set, create a new tab
createNewFacebookTab(resolve, reject);
}
});
}