Skip to content

Instantly share code, notes, and snippets.

@zetavg
Created July 20, 2021 16:32
Show Gist options
  • Save zetavg/8d26ee2205e8ca1f0afc5fd145da5186 to your computer and use it in GitHub Desktop.
Save zetavg/8d26ee2205e8ca1f0afc5fd145da5186 to your computer and use it in GitHub Desktop.
Some JavaScript script for Lingvist.
function delay(ms = 1000) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
function getCourseIdFromPath() {
try {
const [, id] = window.location.hash.match(/course-wizard\/edit\/([^/]+)/);
return id;
} catch (e) {
throw new Error(`Cannot get the course ID from URL path. Are you on the course editing page? (Should be something like "https://learn.lingvist.com/#course-wizard/edit/xxx", we got "${window.location}")`);
}
}
function getToken() {
try {
return JSON.parse(localStorage['PSP_STORAGE/anonymous/authentication']).token;
} catch (e) {
throw new Error(`Cannot get token from localStorage: ${e}`);
}
}
/**
* Example:
*
* addWord(getToken(), getCourseIdFromPath(), 'same', 'Same is サメ is Shark!')
*/
async function addWord(token, courseId, word, note) {
const url = `https://api.lingvist.com/2.0/lessons/${courseId}/add-cards`;
const body = {
include_known: true,
intent: 'vocabulary',
manual: true,
seed_text: word,
};
const response = await fetch(
url,
{
headers: {
'content-type': 'application/json',
'authorization': `Bearer ${token}`,
},
method: 'POST',
body: JSON.stringify(body),
}
);
const json = await response.json();
const card = json.cards[0];
if (!card) {
throw new Error(`Card not created for word ${word}`);
}
await delay(1000); // Give some time for the card creation, otherwise the following operation might return 404
const editedCard = await editCard(token, courseId, card.id, { ...card, form_translation_comment: note });
return editedCard;
return card;
}
/**
* Example:
*
* editCard(getToken(), getCourseIdFromPath(), 8497183, { form_translation_comment: 'Same is サメ is Shark!' })
*/
async function editCard(token, courseId, cardId, data) {
const response = await fetch(
`https://api.lingvist.com/2.0/lessons/${courseId}/cards/${cardId}`,
{
headers: {
'content-type': 'application/json',
'authorization': `Bearer ${token}`,
},
method: 'POST',
body: JSON.stringify(data),
}
);
const card = await response.json();
return card;
}
/**
* Example:
*
* const words = [
* ['same', 'Same is サメ is Shark!'],
* ['yabai', 'Yabai, you guys!'],
* ];
*
* batchAdd(words);
*/
async function batchAdd(words, batchSize = 5) {
const token = getToken();
const courseId = getCourseIdFromPath();
const errors = {};
const ws = [...words];
const totalBatchs = Math.ceil(ws.length / batchSize);
let b = 0;
while (ws.length > 0) {
b += 1;
console.log(`adding... (${b}/${totalBatchs})`);
const cws = ws.splice(0, 5);
await Promise.all(
cws.map(
([word, note]) =>
addWord(token, courseId, word, note)
.catch((e) => errors[word] = e)
)
)
}
const result = {
errors: Object.keys(errors).length > 0 ? errors : null
};
console.log('batchAdd Complete!', result)
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment