-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathduolingo.js
258 lines (242 loc) · 7.45 KB
/
duolingo.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
/// <reference path="chrome.d.ts"/>
const questionTypes = {
"Write this in English": "wordSelectEnglish",
"Write this in Spanish": "wordSelectSpanish",
"Mark the correct meaning": "multipleChoice"
}
/**
* Pauses execution for the specified amount of `ms`
* @param {number} ms The amount of milliseconds to sleep
*/
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
/**
* Gets the given items from chrome storage
* @param {object} keys The values to get, with the defaults
*/
function storageGetAsync(keys) {
return new Promise((resolve, reject) => {
try {
chrome.storage.sync.get(keys, (items) => {
resolve(items)
})
} catch (e) {
reject(e)
}
})
}
/**
* Sets the given items in chrome storage
* @param {object} keys The values to set
*/
function storageSetAsync(keys) {
return new Promise((resolve, reject) => {
try {
chrome.storage.sync.set(keys, () => {
resolve()
})
} catch (e) {
reject(e)
}
})
}
function editDistance(s1, s2) {
s1 = s1.toLowerCase();
s2 = s2.toLowerCase();
var costs = new Array();
for (var i = 0; i <= s1.length; i++) {
var lastValue = i;
for (var j = 0; j <= s2.length; j++) {
if (i == 0)
costs[j] = j;
else {
if (j > 0) {
var newValue = costs[j - 1];
if (s1.charAt(i - 1) != s2.charAt(j - 1))
newValue = Math.min(Math.min(newValue, lastValue),
costs[j]) + 1;
costs[j - 1] = lastValue;
lastValue = newValue;
}
}
}
if (i > 0)
costs[s2.length] = lastValue;
}
return costs[s2.length];
}
function similarity(s1, s2) {
var longer = s1;
var shorter = s2;
if (s1.length < s2.length) {
longer = s2;
shorter = s1;
}
var longerLength = longer.length;
if (longerLength == 0) {
return 1.0;
}
return (longerLength - editDistance(longer, shorter)) / parseFloat(longerLength);
}
const toArray = (variable) => [...variable]
let curQuestion = null
/**
* Translates text to given language
* @param {string} text The text to translate
* @param {"en"|"es"} lang The language
* @returns {string} The translated text
*/
async function getApiTranslated(text, lang) {
const reqData = {
headers: {
"Content-Type": "application/json",
"Ocp-Apim-Subscription-Key": (await storageGetAsync({duolingoSolverKey: ''})).duolingoSolverKey,
"Ocp-Apim-Subscription-Region": "centralus"
},
body: JSON.stringify(
[
{
"Text": text
}
]
),
method: "POST"
}
const spanish = await fetch(
"https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to="+lang,
reqData
)
const json = await spanish.json()
try {
return json[0].translations[0].text
} catch {
const haste = await fetch("https://hst.sh/documents", {
method: "POST",
body: JSON.stringify(json, null, 4),
mode: "no-cors"
})
throw new Error("Invalid api response, response: " + await haste.text())
}
}
/**
* Gets the correct answer from a list of answers
* @param {string} question The question
* @param {string[]} answers The possible answers
* @returns {string} The correct answer
*/
async function getMultipleChoiceAnswer(question, answers) {
const saved = (await storageGetAsync({ savedDuolingoAnswers: {} })).savedDuolingoAnswers
if (saved[question]) {
return saved[question]
}
const translated = await getApiTranslated(question, "es")
const correct = answers.sort((a, b) => {
return similarity(a, translated) - similarity(b, translated)
})[2]
saved[question] = correct
await storageSetAsync({ savedDuolingoAnswers: saved })
return correct
}
/**
* Gets the correct answer from word select
* @param {string} question The question
* @param {"en"|"es"} lang The language
* @returns {string} The correct answer
*/
async function getWordSelectAnswer(question, lang) {
const saved = (await storageGetAsync({ savedDuolingoWordAnswers: {} })).savedDuolingoWordAnswers
if (saved[question]) {
return saved[question]
}
const translated = await getApiTranslated(question, lang)
saved[question] = translated
await storageSetAsync({ savedDuolingoWordAnswers: saved })
return translated
}
setInterval(async () => {
if (typeof chrome.app.isInstalled !== 'undefined') {
const enabled = await storageGetAsync({duolingoSolver: false})
if (!enabled.duolingoSolver) return
try {
/**
* @type {[Element, string][]}
*/
const header = [...document.querySelectorAll('[data-test="challenge-header"]').values()][0]?.innerText
if (!header) return
const questionType = questionTypes[header]
switch (questionType) {
case "multipleChoice": {
const q = document.getElementsByClassName("_3-JBe")[0]?.innerHTML
if (q === curQuestion || !(typeof q == "string")) return
/**
* @type {[Element, string][]}
*/
const answers = toArray(document.querySelectorAll('[data-test="challenge-judge-text"]').values()).map(v => [v, v.innerHTML])
if (answers.length != 3) return
curQuestion = q
const correct = await getMultipleChoiceAnswer(q, answers.map(e => e[1]))
answers.forEach(e => {
e[1] == correct ? (
e[0].style.color = 'green',
e[0].click()
) : (
e[0].style.color = 'red'
)
})
break
}
case "wordSelectEnglish": {
const q = [...document.querySelectorAll('[data-test="hint-sentence"]').values()][0].innerText
if (q === curQuestion || !(typeof q == "string")) return
curQuestion = q
const swapAnswerMethod = document.querySelectorAll('[data-test="challenge-translate-input"]')[0]
if (swapAnswerMethod?.innerHTML == "Use keyboard") swapAnswerMethod.click()
/**
* @type {Element}
*/
const textBox = [...document.querySelectorAll('[data-test="challenge-translate-input"]').values()][0]
const answer = await getWordSelectAnswer(q, "en")
textBox.value = answer
const i = setInterval(() => {
textBox.value = answer
}, 100)
setTimeout(() => {
clearInterval(i)
}, 1000)
// const button = [...document.getElementsByClassName("_2orIw whuSQ _2gwtT _1nlVc _2fOC9 t5wFJ _3dtSu _25Cnc _3yAjN UCrz7 yTpGk _3B3OD")][0]
// textBox.dispatchEvent(new KeyboardEvent('keydown',{'key':'a'}));
break
}
case "wordSelectSpanish": {
const q = [...document.querySelectorAll('[data-test="hint-sentence"]').values()][0].innerText
if (q === curQuestion || !(typeof q == "string")) return
curQuestion = q
const swapAnswerMethod = document.querySelectorAll('[data-test="challenge-translate-input"]')[0]
if (swapAnswerMethod?.innerHTML == "Use keyboard") swapAnswerMethod.click()
/**
* @type {Element}
*/
const textBox = [...document.querySelectorAll('[data-test="challenge-translate-input"]').values()][0]
const answer = await getWordSelectAnswer(q, "es")
textBox.value = answer
const i = setInterval(() => {
textBox.value = answer
}, 100)
setTimeout(() => {
clearInterval(i)
}, 1000)
// const button = [...document.getElementsByClassName("_2orIw whuSQ _2gwtT _1nlVc _2fOC9 t5wFJ _3dtSu _25Cnc _3yAjN UCrz7 yTpGk _3B3OD")][0]
// textBox.dispatchEvent(new KeyboardEvent('keydown',{'key':'a'}));
break
}
default: {
console.warn("Invalid question type " + header)
break
}
}
} catch (e) {
console.error(e)
}
}
}, 500)