forked from ibnunes/YoutubeAutotranslateCanceler
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAntiTranslate.user.js
More file actions
298 lines (246 loc) · 11.2 KB
/
AntiTranslate.user.js
File metadata and controls
298 lines (246 loc) · 11.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
// ==UserScript==
// @name Youtube Auto-translate Canceler
// @namespace https://github.com/ibnunes/YoutubeAutotranslateCanceler
// @version 0.5
// @description Remove auto-translated youtube titles
// @author Pierre Couy
// @match https://www.youtube.com/*
// @grant GM.setValue
// @grant GM.getValue
// @require https://cdn.jsdelivr.net/npm/dompurify@3.2.4/dist/purify.min.js
// ==/UserScript==
(async () => {
'use strict';
/*
Get a YouTube Data v3 API key from https://console.developers.google.com/apis/library/youtube.googleapis.com?q=YoutubeData
*/
let NO_API_KEY = false;
let api_key_awaited = await GM.getValue("api_key");
if (api_key_awaited === undefined || api_key_awaited === null || api_key_awaited === "") {
await GM.setValue("api_key", prompt("Enter your API key. Go to https://developers.google.com/youtube/v3/getting-started to know how to obtain an API key, then go to https://console.developers.google.com/apis/api/youtube.googleapis.com/ in order to enable Youtube Data API for your key."));
}
api_key_awaited = await GM.getValue("api_key");
if (api_key_awaited === undefined || api_key_awaited === null || api_key_awaited === "") {
NO_API_KEY = true; // Resets after page reload, still allows local title to be replaced
console.log("Youtube Auto-translate Canceler: NO API KEY PRESENT");
}
const API_KEY = await GM.getValue("api_key");
let API_KEY_VALID = false;
// console.log(API_KEY);
console.log("Youtube Auto-translate Canceler: Got API key");
const URL_TEMPLATE = "https://www.googleapis.com/youtube/v3/videos?part=snippet&id={IDs}&key=" + API_KEY;
// Dictionary(id, title): Cache of API fetches, survives only Youtube Autoplay
let cachedTitles = {}
// (id, desc linkified TrustedHTML)
let cachedDescriptions = {}
function videoIdFromUrl(url_string) {
const url = new URL(url_string);
if (url.pathname.includes("/watch")) {
return url.searchParams.get('v') || null;
}
if (url.pathname.includes("/shorts")) {
const splits = url.pathname.split('/');
return splits.length >= 3 ? splits[2] : null;
}
if (url.pathname.includes("/live")) {
const splits = url.pathname.split('/');
return splits.length >= 3 ? splits[2] : null;
}
return null;
}
function videoIdFromA(a) {
while (a.tagName != "A") {
a = a.parentNode;
}
if (!a || !a.href) return null;
return videoIdFromUrl(a.href);
}
function collectVideoElements() {
let links = Array
.from(document.querySelectorAll(
'a[href*="/watch"]:not([href*="&list="]) [role="text"], '
+ 'a[href*="/watch"] [id="video-title"], '
+ 'a[href*="/watch"] .ytp-videowall-still-info-title, '
+ 'a[href*="/shorts"] [role="text"], '
+ 'a[href*="/shorts"] [id="video-title"], '
+ 'a[href*="/live"] [role="text"], '
+ 'a[href*="/watch"][id="video-title"]'
))
.filter(a => { return a.textContent?.trim().length > 0; });
return links;
}
async function fetchVideoData(videoIDs) {
if (videoIDs.length === 0) return;
const requestUrl = URL_TEMPLATE.replace("{IDs}", videoIDs.join(','));
// Issue API request
let data;
try {
data = await fetch(requestUrl).then((r) => r.json());
} catch (err) {
console.log("Exception while fetching:", err);
}
if (!data || data.kind !== "youtube#videoListResponse") {
console.log("API Request Failed!", requestUrl, data);
// This ensures that occasional fails don't stall the script
// But if the first query is a fail then it won't try repeatedly
NO_API_KEY = !API_KEY_VALID;
if (NO_API_KEY) {
console.log("API Key Fail! Please Reload!");
}
return;
}
API_KEY_VALID = true;
const validSet = new Set();
// Create dictionary for all IDs and their original titles
for (const v of data.items) {
validSet.add(v.id);
cachedTitles[v.id] = v.snippet.title.replace(/^\s+|\s+$/gu, '');
cachedDescriptions[v.id] = DOMPurify.sanitize(
linkify(v.snippet.description), { RETURN_TRUSTED_TYPE: true });
}
for (const id of videoIDs) {
if (!validSet.has(id)) {
cachedTitles[id] = null;
cachedDescriptions[id] = null;
}
}
}
function updateMainVideo(mainVidID) {
if (!mainVidID) return;
// Replace Main Video title
const untranslatedTitle = cachedTitles[mainVidID]
const mainTitle = document.querySelector('#title > h1 > yt-formatted-string');
if (mainTitle
&& untranslatedTitle
&& (mainTitle.innerText !== untranslatedTitle
|| mainTitle.getAttribute('is-empty') !== null)) {
mainTitle.innerText = untranslatedTitle
mainTitle.title = untranslatedTitle
mainTitle.removeAttribute('is-empty')
document.title = `${untranslatedTitle} - YouTube`
}
const fullscreenTitle = document.querySelector('.ytp-title a.ytp-title-link');
if (fullscreenTitle
&& untranslatedTitle
&& (fullscreenTitle.innerText !== untranslatedTitle
|| fullscreenTitle.getAttribute('is-empty') !== null)) {
fullscreenTitle.innerText = untranslatedTitle
fullscreenTitle.removeAttribute('is-empty')
document.title = `${untranslatedTitle} - YouTube`
}
const shortsTitle = document.querySelector('#metapanel span[role="text"]');
if (shortsTitle
&& untranslatedTitle
&& (shortsTitle.innerText !== untranslatedTitle
|| shortsTitle.getAttribute('is-empty') !== null)) {
shortsTitle.innerText = untranslatedTitle
shortsTitle.title = untranslatedTitle
shortsTitle.removeAttribute('is-empty')
document.title = `${untranslatedTitle} - YouTube`
}
// Replace Main Video Description
const videoDescription = cachedDescriptions[mainVidID];
const pageDescription = document
.querySelector('#description-inline-expander yt-attributed-string > span')
// Still critical, since it replaces ALL descriptions, even if it was not translated in the first place (no easy comparision possible)
if (videoDescription && pageDescription.innerHTML !== videoDescription.toString()) {
pageDescription.innerHTML = videoDescription;
}
}
function updateAllLinkTitles(links, IDs) {
// Change all previously found link elements
for (let i = 0; i < links.length; i++) {
const curID = videoIdFromA(links[i]);
if (!curID) continue;
if (curID !== IDs[i]) {
// Can happen when Youtube was still loading when script was invoked
console.log("YouTube was too slow again...");
continue;
}
const originalTitle = cachedTitles[curID];
if (!originalTitle) continue;
const linkEl = links[i].querySelector('#video-title') || links[i]
const pageTitle = linkEl.innerText.trim();
if (pageTitle === originalTitle.replace(/\s{2,}/g, ' ')
|| pageTitle === originalTitle) continue;
console.log("Revert translation: '" + pageTitle + "' --> '" + originalTitle + "'");
linkEl.textContent = originalTitle;
linkEl.title = originalTitle;
}
}
async function changeTitles() {
if (NO_API_KEY) return;
const links = collectVideoElements();
const mainVidID = videoIdFromUrl(window.location.href);
const IDs = [...links.map(a => videoIdFromA(a)), ...(mainVidID ? [mainVidID] : [])];
const APIFetchIDs = IDs
.filter(id => !(id in cachedTitles) || !(id in cachedDescriptions))
.slice(0, 30);
if (IDs.length == 0) return;
await fetchVideoData(APIFetchIDs);
// Begin to update the DOM
updateMainVideo(mainVidID);
updateAllLinkTitles(links, IDs);
}
// linkify replaces links correctly, but without redirect or other specific youtube
// stuff (no problem if missing)
function linkify(inputText) {
let replacedText, replacePattern1, replacePattern2, replacePattern3;
//URLs starting with http://, https://, or ftp://
replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
replacedText = inputText.replace(replacePattern1, '<a class="yt-core-attributed-string__link yt-core-attributed-string__link--call-to-action-color" spellcheck="false" href="$1">$1</a>');
//URLs starting with "www." (without // before it, or it'd re-link the ones done above).
replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
replacedText = replacedText.replace(replacePattern2, '<a class="yt-core-attributed-string__link yt-core-attributed-string__link--call-to-action-color" spellcheck="false" href="http://$1">$1</a>');
//Change email addresses to mailto:: links.
replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
replacedText = replacedText.replace(replacePattern3, '<a class="yt-core-attributed-string__link yt-core-attributed-string__link--call-to-action-color" spellcheck="false" href="mailto:$1">$1</a>');
replacedText = replacedText.replaceAll('\n', '<br />')
return replacedText;
}
// create a throttled function with a trailing call when requested in the down time
// adapted from https://rahultomar092.medium.com/throttling-in-js-with-leading-and-trailing-4a60d5d99122
function throttle(func, delay) {
let waiting = false;
let lastArgs = null;
let lastThis = null;
let needTrailingCall = false;
function startWait() {
setTimeout(() => {
if (!needTrailingCall) {
waiting = false;
return;
}
func.apply(lastThis, lastArgs);
lastArgs = null;
lastThis = null;
needTrailingCall = false;
startWait();
}, delay);
}
function wrapper(...args) {
if (waiting) {
// only keep the latest arguments around for the trailing call
lastArgs = args;
lastThis = this;
needTrailingCall = true;
return;
}
func.apply(this, args);
waiting = true;
startWait();
};
return wrapper;
}
// at most one update per second
const throttledChangeTitles = throttle(() => {
changeTitles().catch(() => { })
}, 1000);
const observer = new MutationObserver(() => {
throttledChangeTitles()
});
observer.observe(document.body, {
childList: true,
subtree: true
});
})();