fixed level caching

This commit is contained in:
Lauchmelder 2022-03-20 01:23:01 +01:00
parent 97a173ad47
commit 03ea59286b
No known key found for this signature in database
GPG key ID: C2403C69D78F011D

View file

@ -22,33 +22,46 @@ const query = (token, url) =>
}) })
const updateCache = async (token, oldLevel, newLevel) => { const updateCache = async (token, oldLevel, newLevel) => {
// If oldLevel is undefined, then a sync has never been performed (first time user)
if(oldLevel === undefined) if(oldLevel === undefined)
oldLevel = 1 oldLevel = 1
// Create a list of levels that need to be synced
// If the new level is bigger than the old level (user leveled up)
// --> Just fetch the new level(s)
// If the new level is smaller than the old level (user reset)
// --> Fetch everything up until the new level
var levelArray = [] var levelArray = []
for(var i = oldLevel; i < newLevel; i++) var startLevel = newLevel > oldLevel ? oldLevel : 1
for(var i = startLevel; i < newLevel; i++)
levelArray.push(i) levelArray.push(i)
// Turn the array of levels into a comma separated list
var levelURLString = levelArray.join(",") var levelURLString = levelArray.join(",")
// API endpoint + response data buffers
var url = "https://api.wanikani.com/v2/subjects?types=vocabulary&levels=" + levelURLString var url = "https://api.wanikani.com/v2/subjects?types=vocabulary&levels=" + levelURLString
var vocabulary = [] var vocabulary = []
// WaniKani only sends 1000 elements in one response and then provides us with a link to the
// next "page" of the data. We need to loop until the next page is null
do do
{ {
// Query API, extract all the important info and then update the URL to the next page
var response = await query(token, url).catch(reason => console.error("WaniKani API request failed: " + reason)) var response = await query(token, url).catch(reason => console.error("WaniKani API request failed: " + reason))
if(response === undefined) if(response === undefined)
break break
for(let i in response.data) for(let i in response.data)
vocabulary.push(response.data[i].data.characters) vocabulary.push(response.data[i].data.characters)
url = response.pages.next_url url = response.pages.next_url
} while(url !== null) } while(url !== null)
// Extract Kanji as well
var url = "https://api.wanikani.com/v2/subjects?types=kanji&levels=" + levelURLString var url = "https://api.wanikani.com/v2/subjects?types=kanji&levels=" + levelURLString
var kanji = [] var kanji = []
do do
{ {
var response = await query(token, url).catch(reason => console.error("WaniKani API request failed: " + reason)) var response = await query(token, url).catch(reason => console.error("WaniKani API request failed: " + reason))
@ -61,6 +74,7 @@ const updateCache = async (token, oldLevel, newLevel) => {
url = response.pages.next_url url = response.pages.next_url
} while(url !== null) } while(url !== null)
// If the old level is less than the new level add the old data to the new data
if(oldLevel < newLevel) if(oldLevel < newLevel)
{ {
await chrome.storage.local.get(["vocabulary", "kanji"], (data) => { await chrome.storage.local.get(["vocabulary", "kanji"], (data) => {
@ -69,40 +83,51 @@ const updateCache = async (token, oldLevel, newLevel) => {
}) })
} }
// Cache the data
chrome.storage.local.set({ chrome.storage.local.set({
"vocabulary": vocabulary, "vocabulary": vocabulary,
"kanji": kanji "kanji": kanji,
"level": newLevel
}) })
chrome.storage.local.set({"level": newLevel});
} }
// Synchronizes local data with wanikanis data
const sync = () => const sync = () =>
new Promise((resolve, reject) => { new Promise((resolve, reject) => {
chrome.storage.local.get(["level", "token"], async (data) => { chrome.storage.local.get(["level", "token"], async (data) => {
// See if wanikani token is well formed
const apiTokenPattern = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/ const apiTokenPattern = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/
if(!apiTokenPattern.test(data.token)) if(!apiTokenPattern.test(data.token))
return reject("Please set a valid WaniKani API Token") return reject("Please set a valid WaniKani API Token")
// Get user info
var user = await query(data.token, "https://api.wanikani.com/v2/user").catch(reason => reject("WaniKani API request failed: " + reason)) var user = await query(data.token, "https://api.wanikani.com/v2/user").catch(reason => reject("WaniKani API request failed: " + reason))
if(user === undefined) if(user === undefined)
return return
// Get user level
level = user.data.level level = user.data.level
chrome.storage.local.set({"validUserLevel": level <= user.data.subscription.max_level_granted}) // If the users level is somehow larger than their max allowed level, set the flag
// if users level is larger than max allowed level, abort
if(level > user.data.subscription.max_level_granted) if(level > user.data.subscription.max_level_granted)
{
chrome.storage.local.set({"validUserLevel": false})
return reject("User account level exceeds account level limit") return reject("User account level exceeds account level limit")
}
// If the wanikani level differs from the local leve, update the cache
if(level !== data.level) if(level !== data.level)
updateCache(data.token, data.level, level) updateCache(data.token, data.level, level)
chrome.storage.local.set({"validUserLevel": true})
resolve("Successfully synchronized data!") resolve("Successfully synchronized data!")
}) })
}) })
// Message listener for the Sync button
chrome.runtime.onMessage.addListener((data, sender, sendResponse) => { chrome.runtime.onMessage.addListener((data, sender, sendResponse) => {
if(data.type === "sync") if(data.type === "sync")
sync() sync()
@ -116,4 +141,5 @@ chrome.runtime.onMessage.addListener((data, sender, sendResponse) => {
return true; return true;
}) })
// At browser start, sync with wanikani
sync().then(value => console.log(value)).catch(reason => console.error(reason)) sync().then(value => console.log(value)).catch(reason => console.error(reason))