-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
490 lines (449 loc) · 14.9 KB
/
script.js
File metadata and controls
490 lines (449 loc) · 14.9 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
const targetLocales = [
"ar",
"am",
"bg",
"bn",
"ca",
"cs",
"da",
"de",
"el",
"en",
"es",
"et",
"fa",
"fi",
"fr",
"gu",
"he",
"hi",
"hr",
"hu",
"id",
"it",
"ja",
"kn",
"ko",
"lt",
"lv",
"ml",
"mr",
"ms",
"ml",
"no",
"pl",
"pt",
"ro",
"ru",
"sk",
"sl",
"sr",
"sv",
"sw",
"ta",
"te",
"th",
"tr",
"uk",
"vi",
"zh-CN",
"zh-TW",
];
const defaultLocales = ["en", "es", "zh_CN", "hi", "ar"];
const x1 = "QUl6YVN5QktjRTNkNjVXVU";
const x2 = "Z6VDJFTTlQSnJrZUtINFZDcThzelBn";
document.addEventListener("DOMContentLoaded", async function () {
var uploadedZip = null;
var defaultLocale = "";
// Function to handle the click event of the upload button
function handleUploadButtonClick() {
document.getElementById("uploadZip").click();
gtag("event", "click", {
event_category: "Upload",
event_label: "Upload Button",
});
}
// Function to handle the change event of the file input
function handleFileInputChange(e) {
var file = e.target.files[0];
if (file && file.type === "application/zip") {
uploadedZip = file;
extractManifestFromZip(file);
gtag("event", "upload", {
event_category: "Upload",
event_label: "Zip File",
});
} else {
resetUploadedZip();
displayUploadError("Invalid file type. Please upload a valid zip file.");
gtag("event", "error", {
event_category: "Upload",
event_label: "Invalid File Type",
});
}
}
// Function to extract the manifest.json file from the zip
function extractManifestFromZip(file) {
console.log("extracting manifest file");
JSZip.loadAsync(file)
.then(function (zip) {
if (zip.files["manifest.json"]) {
zip
.file("manifest.json")
.async("string")
.then(function (content) {
var manifest = JSON.parse(content);
defaultLocale = manifest.default_locale || "en";
gtag("event", "extract", {
event_category: "Manifest",
event_label: "Success",
});
if (zip.files["_locales/"]) {
updateDefaultLocale(defaultLocale);
enableTranslateButton();
displayUploadSuccess("Extension uploaded successfully!");
setActiveCard("translateCard");
} else {
displayUploadError(
'Missing "_locales" directory in the zip file.'
);
gtag("event", "error", {
event_category: "Manifest",
event_label: "Missing Locales Directory",
});
}
});
} else {
displayUploadError('Missing "manifest.json" file in the zip file.');
gtag("event", "error", {
event_category: "Manifest",
event_label: "Missing Manifest File",
});
}
})
.catch(function (error) {
displayUploadError("Error extracting manifest file: " + error.message);
gtag("event", "error", {
event_category: "Manifest",
event_label: "Extraction Error",
});
});
}
// Function to reset the uploaded zip and related UI elements
function resetUploadedZip() {
uploadedZip = null;
updateDefaultLocale("");
disableTranslateButton();
disableDownloadButton();
setActiveCard("uploadCard");
}
// Function to update the default locale UI element
function updateDefaultLocale(locale) {
document.getElementById("defaultLocale").textContent =
"Detected Default Locale: " + locale;
}
// Function to enable the translate button
function enableTranslateButton() {
document.getElementById("translateBtn").disabled = false;
}
// Function to disable the translate button
function disableTranslateButton() {
document.getElementById("translateBtn").disabled = true;
}
// Function to disable the download button
function disableDownloadButton() {
document.getElementById("downloadBtn").disabled = true;
}
// Function to handle the click event of the select locales link
function handleSelectLocalesLinkClick(event) {
event.preventDefault();
var localesList = document.getElementById("localesList");
if (localesList.style.display === "none") {
localesList.style.display = "block";
} else {
localesList.style.display = "none";
}
}
// Uncheck all checkboxes
function handleDeselectAllLocalsClick(event) {
var checkboxes = document.querySelectorAll(
'#localesList input[type="checkbox"]'
);
checkboxes.forEach(function (checkbox) {
checkbox.checked = false;
});
}
// Function to get selected locales
function getSelectedLocales() {
var selectedLocales = [];
var checkboxes = document.querySelectorAll(
'#localesList input[type="checkbox"]'
);
checkboxes.forEach(function (checkbox) {
if (checkbox.checked) {
selectedLocales.push(checkbox.value);
}
});
return selectedLocales;
}
// Function to update translation progress
function updateTranslationProgress(current, total) {
var progressBar = document.getElementById("translationProgress");
var progressPercentage = Math.round((current / total) * 100);
progressBar.style.width = progressPercentage + "%";
progressBar.setAttribute("aria-valuenow", progressPercentage);
progressBar.innerHTML = `${progressPercentage}%`;
// Show the progress bar and translation status when translation begins
document.querySelector(".progress").style.display = "block";
}
// Function to handle the click event of the translate button
function handleTranslateButtonClick() {
if (uploadedZip) {
// Hide the progress bar before starting a new translation
document.querySelector(".progress").style.display = "none";
translateExtension(uploadedZip);
}
}
// Function to translate the extension using the Google Translate API
function translateExtension(zip) {
JSZip.loadAsync(zip).then(function (zip) {
zip
.file("_locales/" + defaultLocale + "/messages.json")
.async("string")
.then(function (content) {
var messages = JSON.parse(content);
var apiKey = atob(x1 + x2);
console.log("api key:", apiKey);
var selectedLocales = getSelectedLocales();
var translatedCount = 0;
var translatePromises = selectedLocales.map(function (locale) {
var translationPromises = Object.keys(messages).map(function (key) {
var message = messages[key].message;
var url =
"https://translation.googleapis.com/language/translate/v2?key=" +
apiKey;
url += "&q=" + encodeURIComponent(message);
url += "&target=" + locale;
return fetch(url)
.then(function (response) {
return response.json();
})
.then(function (data) {
return {
key: key,
message: data.data.translations[0].translatedText,
};
});
});
return Promise.all(translationPromises).then(function (
translatedMessages
) {
var translatedContent = {};
translatedMessages.forEach(function (translatedMessage) {
translatedContent[translatedMessage.key] = {
message: translatedMessage.message,
};
});
zip.file(
"_locales/" + locale + "/messages.json",
JSON.stringify(translatedContent, null, 2)
);
updateTranslationProgress(
++translatedCount,
selectedLocales.length
);
});
});
Promise.all(translatePromises)
.then(function () {
enableDownloadButton();
displayTranslateSuccess("Extension translated successfully!");
setActiveCard("downloadCard");
})
.catch(function (error) {
displayTranslateError(
"Error translating extension: " + error.message
);
});
});
});
}
// Function to enable the download button
function enableDownloadButton() {
document.getElementById("downloadBtn").disabled = false;
}
// Function to handle the click event of the download button
function handleDownloadButtonClick() {
if (uploadedZip) {
downloadTranslatedExtension(uploadedZip);
}
}
// Function to download the translated extension
function downloadTranslatedExtension(zip) {
JSZip.loadAsync(zip).then(function (zip) {
zip.generateAsync({ type: "blob" }).then(function (content) {
var link = document.createElement("a");
link.href = URL.createObjectURL(content);
link.download = "translated_extension.zip";
link.click();
displayDownloadSuccess("Extension downloaded successfully!");
});
});
}
// Function to handle the click event of the fetch extension button
function handleFetchExtensionButtonClick() {
var extensionUrl = document.getElementById("extensionUrl").value;
var extensionIdPattern =
/^https?:\/\/chromewebstore.google.com\/detail(?:\/[^\/]+)?\/([a-z]{32})(?=[\/#?]|$)/;
var match = extensionUrl.match(extensionIdPattern);
if (match && match[1]) {
var extensionId = match[1];
fetchExtensionFromWebStore(extensionId);
gtag("event", "click", {
event_category: "Fetch Extension",
event_label: "Fetch Button",
});
} else {
displayUploadError("Invalid Chrome extension URL.");
gtag("event", "error", {
event_category: "Fetch Extension",
event_label: "Invalid URL",
});
}
}
// Function to fetch extension from Chrome Web Store
function fetchExtensionFromWebStore(extensionId) {
var url = `https://clients2.google.com/service/update2/crx?response=redirect&prodversion=91.0.1609.0&acceptformat=crx2,crx3&x=id%3D${extensionId}%26uc`;
fetch(url, { method: "POST", mode: "no-cors", redirect: "follow" })
.then(function (response) {
console.log("response", response);
if (response.ok) {
return response.blob();
} else {
throw new Error(
"Failed to fetch extension from Chrome Web Store. status: ",
response.status,
response
);
}
})
.then(function (blob) {
uploadedZip = new File([blob], "extension.zip", {
type: "application/zip",
});
extractManifestFromZip(uploadedZip);
gtag("event", "fetch", {
event_category: "Fetch Extension",
event_label: "Success",
});
})
.catch(function (error) {
displayUploadError("Error fetching extension: " + error.message);
gtag("event", "error", {
event_category: "Fetch Extension",
event_label: "Fetch Error",
});
});
}
// Function to display upload error message
function displayUploadError(message) {
document.getElementById("uploadMessage").innerHTML =
'<div class="alert alert-danger">' + message + "</div>";
}
// Function to display upload success message
function displayUploadSuccess(message) {
document.getElementById("uploadMessage").innerHTML =
'<div class="alert alert-success">' + message + "</div>";
}
// Function to display translate error message
function displayTranslateError(message) {
document.getElementById("translateMessage").innerHTML =
'<div class="alert alert-danger">' + message + "</div>";
}
// Function to display translate success message
function displayTranslateSuccess(message) {
document.getElementById("translateMessage").innerHTML =
'<div class="alert alert-success">' + message + "</div>";
}
// Function to display download success message
function displayDownloadSuccess(message) {
document.getElementById("downloadMessage").innerHTML =
'<div class="alert alert-success">' + message + "</div>";
}
// Function to set the active card
function setActiveCard(cardId) {
var cards = document.querySelectorAll(".card");
cards.forEach(function (card) {
card.classList.remove("active");
});
document.getElementById(cardId).classList.add("active");
}
// Function to handle the change event of the locale checkboxes
function handleLocaleCheckboxChange() {
var selectedLocales = getSelectedLocales();
if (selectedLocales.length > 5) {
this.checked = false;
displayLocaleNotice(getSelectedLocales());
} else {
hideLocaleNotice();
updateSelectedLocales(selectedLocales);
}
}
// Function to display the locale notice
function displayLocaleNotice(selectedLocales) {
var localeNotice = document.getElementById("localeNotice");
localeNotice.innerHTML =
"You can only select up to 5 locales at a time (for now due to resource constraints). Selected: " +
selectedLocales.join(", ");
localeNotice.style.display = "block";
}
// Function to hide the locale notice
function hideLocaleNotice() {
document.getElementById("localeNotice").style.display = "none";
}
// Function to update the selected locales display
function updateSelectedLocales(selectedLocales) {
document.getElementById("selectedLocales").textContent =
"Target Locales: " + selectedLocales.join(", ");
}
// Function to set the default locales checked
function setDefaultLocalesChecked() {
var checkboxes = document.querySelectorAll(
'#localesList input[type="checkbox"]'
);
checkboxes.forEach(function (checkbox) {
checkbox.checked = defaultLocales.includes(checkbox.value);
});
updateSelectedLocales(getSelectedLocales());
}
document
.querySelectorAll('#localesList input[type="checkbox"]')
.forEach(function (checkbox) {
checkbox.addEventListener("change", handleLocaleCheckboxChange);
});
// Set the default locales checked on page load
setDefaultLocalesChecked();
// Event listeners
document
.getElementById("uploadBtn")
.addEventListener("click", handleUploadButtonClick);
document
.getElementById("uploadZip")
.addEventListener("change", handleFileInputChange);
// document
// .getElementById("fetchExtensionBtn")
// .addEventListener("click", handleFetchExtensionButtonClick);
document
.getElementById("selectLocalesLink")
.addEventListener("click", handleSelectLocalesLinkClick);
// Function to handle the click event of the deselect all button
document
.getElementById("deselectAllBtn")
.addEventListener("click", handleDeselectAllLocalsClick);
document
.getElementById("translateBtn")
.addEventListener("click", handleTranslateButtonClick);
document
.getElementById("downloadBtn")
.addEventListener("click", handleDownloadButtonClick);
});