forked from pcouy/YoutubeAutotranslateCanceler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AntiTranslate.user.js
228 lines (194 loc) · 10.5 KB
/
AntiTranslate.user.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
// ==UserScript==
// @name Youtube Auto-translate Canceler
// @namespace https://github.com/Bertaz/YoutubeAutotranslateCanceler
// @downloadURL https://github.com/Bertaz/YoutubeAutotranslateCanceler/raw/master/AntiTranslate.user.js
// @version 0.6.1
// @description Remove auto-translated youtube titles
// @author Bertaz
// @author Pierre Couy
// @match https://www.youtube.com/*
// @grant GM.setValue
// @grant GM.getValue
// @grant GM.deleteValue
// ==/UserScript==
(async () => {
'use strict';
//SETTINGS////////////
const fixPopup = true //untranslates the popups appearing when hovering with the mouse over the title (default true)
/////////////////////
/*
Get a YouTube Data v3 API key from https://console.developers.google.com/apis/library/youtube.googleapis.com?q=YoutubeData
*/
var NO_API_KEY = false;
var 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("NO API KEY PRESENT");
}
const API_KEY = await GM.getValue("api_key");
var API_KEY_VALID = false;
console.log(API_KEY);
var url_template = "https://www.googleapis.com/youtube/v3/videos?part=snippet&id={IDs}&key=" + API_KEY;
var cachedTitles = {} // Dictionary(id, title): Cache of API fetches, survives only Youtube Autoplay
var currentLocation; // String: Current page URL
var changedDescription; // Bool: Changed description
var alreadyChanged; // List(string): Links already changed
function getVideoID(a)
{
while(a.tagName != "A"){
a = a.parentNode;
}
var href = a.href;
var tmp = href.split('v=')[1];
return tmp.split('&')[0];
}
function getTitleNode(b){
while(b.title == ""){
b = b.parentNode;
}
return b;
}
function resetChanged(){
console.log(" --- Page Change detected! --- ");
currentLocation = document.title;
changedDescription = false;
alreadyChanged = [];
}
resetChanged();
function changeTitles(){
if(currentLocation !== document.title) resetChanged();
// MAIN TITLE - no API key required
if (window.location.href.includes ("/watch")){
var titleMatch = document.title.match (/^(?:\([0-9]+\) )?(.*?)(?: - YouTube)$/); // ("(n) ") + "TITLE - YouTube"
var pageTitle = document.getElementsByClassName("title style-scope ytd-video-primary-info-renderer");
if (pageTitle.length > 0 && pageTitle[0] !== undefined && titleMatch != null) {
if (pageTitle[0].innerText != titleMatch[1]){
console.log ("Reverting main video title '" + pageTitle[0].innerText + "' to '" + titleMatch[1] + "'");
pageTitle[0].innerText = titleMatch[1];
}
}
}
if (NO_API_KEY) {
return;
}
var APIcallIDs;
// REFERENCED VIDEO TITLES - find video link elements in the page that have not yet been changed
var links = Array.prototype.slice.call(document.getElementsByTagName("a")).filter( a => {
return (a.id == 'video-title' || a.parentNode.id == 'title')
&& !a.className.includes("-radio-")
&& !a.className.includes("-playlist-")
&& alreadyChanged.indexOf(a) == -1;
} );
var home = Array.prototype.slice.call(document.getElementsByTagName("yt-formatted-string")).filter( a => {
return a.id == 'video-title' && alreadyChanged.indexOf(a) == -1;
} );
var spans = Array.prototype.slice.call(document.getElementsByTagName("span")).filter( a => {
return a.id == 'video-title'
&& !a.className.includes("-radio-")
&& !a.className.includes("-playlist-")
&& alreadyChanged.indexOf(a) == -1;
} );
links = links.concat(home, spans).slice(0,30);
// MAIN VIDEO DESCRIPTION - request to load original video description
var mainVidID = "";
if (!changedDescription && window.location.href.includes ("/watch")){
mainVidID = window.location.href.split('v=')[1].split('&')[0];
}
if(mainVidID != "" || links.length > 0)
{ // Initiate API request
console.log("Checking " + (mainVidID != ""? "main video and " : "") + links.length + " video titles!");
// Get all videoIDs to put in the API request
var IDs = links.map( a => getVideoID (a));
var APIFetchIDs = IDs.filter(id => cachedTitles[id] === undefined);
var requestUrl = url_template.replace("{IDs}", (mainVidID != ""? (mainVidID + ",") : "") + APIFetchIDs.join(','));
// Issue API request
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function ()
{
if (xhr.readyState === 4)
{ // Success
var data = JSON.parse(xhr.responseText);
if(data.kind == "youtube#videoListResponse")
{
API_KEY_VALID = true;
data = data.items;
if (mainVidID != "")
{ // Replace Main Video Description
var videoDescription = data[0].snippet.description;
var pageDescription = document.getElementsByClassName("content style-scope ytd-video-secondary-info-renderer");
if (pageDescription.length > 0 && videoDescription != null && pageDescription[0] !== undefined) {
// linkify replaces links correctly, but without redirect or other specific youtube stuff (no problem if missing)
// Still critical, since it replaces ALL descriptions, even if it was not translated in the first place (no easy comparision possible)
pageDescription[0].innerHTML = linkify(videoDescription);
console.log ("Reverting main video description!");
changedDescription = true;
}
else console.log ("Failed to find main video description!");
}
// Create dictionary for all IDs and their original titles
data = data.forEach( v => {
cachedTitles[v.id] = v.snippet.title;
} );
// Change all previously found link elements
for(var i=0 ; i < links.length ; i++){
var curID = getVideoID(links[i]);
if (curID !== IDs[i]) { // Can happen when Youtube was still loading when script was invoked
console.log ("YouTube was too slow again...");
changedDescription = false; // Might not have been loaded aswell - fixes rare errors
}
if (cachedTitles[curID] !== undefined)
{
var originalTitle = cachedTitles[curID];
var pageTitle = links[i].innerText.trim();
if(pageTitle != originalTitle.replace(/\s{2,}/g, ' '))
{
console.log ("'" + pageTitle + "' --> '" + originalTitle + "'");
links[i].innerText = originalTitle;
if (fixPopup){
getTitleNode(links[i]).title = originalTitle;
}
}
alreadyChanged.push(links[i]);
}
}
}
else
{
console.log("API Request Failed!");
console.log(requestUrl);
console.log(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) {
GM_setValue('api_key', '');
console.log("API Key Fail! Please Reload!");
}
}
}
};
xhr.open('GET', requestUrl);
xhr.send();
}
}
function linkify(inputText) {
var 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-simple-endpoint style-scope yt-formatted-string" 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-simple-endpoint style-scope yt-formatted-string" 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-simple-endpoint style-scope yt-formatted-string" spellcheck="false" href="mailto:$1">$1</a>');
return replacedText;
}
// Execute every seconds in case new content has been added to the page
// DOM listener would be good if it was not for the fact that Youtube changes its DOM frequently
setInterval(changeTitles, 1000);
})();