-
Notifications
You must be signed in to change notification settings - Fork 1
/
universalTranslator.js
54 lines (47 loc) · 2.11 KB
/
universalTranslator.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
// Translate Neflix Captions Using the Google Translate API.
(function initTranslator(apiKey, lang) {
var translateURL = 'https://translation.googleapis.com/language/translate/v2?key=' + apiKey;
function makeSafe(s) { return s.replace(/[^a-z0-9]/gi, '') }
function getSubtitleObj() { return document.getElementsByClassName('player-timedtext-text-container')[0] }
function setSubtitleText(elem, text) {
for (var i = 0; i < elem.children.length; i += 1) { elem.children[i].innerText = ''; }
elem.children[0].innerText = text;
}
// Cache lets us handle common statements without lookup costs.
var translationCache = {}
function translateCaption(text, done) {
if (translationCache[text]) return done(null, translationCache[text]);
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', translateURL);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4) {
var translated = JSON.parse(xmlhttp.response).data.translations[0].translatedText
translated = translated.replace(/<br>/g, '\n')
translationCache[text] = translated
done(null, translationCache[text])
}
}
xmlhttp.send(JSON.stringify({ q: text.replace(/[\r\n]/g, '<br>'), target: lang }));
}
var lastSet = "";
var processing = false;
function checkCaptions() {
var subtitles = getSubtitleObj();
if (!subtitles || processing || makeSafe(lastSet) === makeSafe(subtitles.innerText)) return;
if (subtitles.innerText == '') return;
var text = subtitles.innerText;
// Hide Original While Sending
setSubtitleText(subtitles, '');
// Mutex to prevent multiple requests
processing = true;
translateCaption(text, function (err, toSet) {
processing = false;
lastSet = toSet;
setSubtitleText(subtitles, toSet);
});
}
var procNum = setInterval(checkCaptions, 10)
console.log('System Online; Translating to "' + lang + '"')
console.log('You can kill the translator using \'clearInterval(' + procNum + ')\'')
})('<API_KEY>', '<2_LETTER_LANG_CODE>')