/// <summary> /// Starts a background task to perform the request in the background. /// </summary> private async Task RequestApi() { //// Check the worker //if (_worker != null) //{ //_worker.Dispose(); //} // Initialize values IsComplete = false; IsError = false; IsWorking = true; Error = string.Empty; Result = null; await DoRequestApi(); IsWorking = false; //// Run the initialization in the background. //_worker = new BackgroundWorker(); //_worker.DoWork += DoRequestApi; //_worker.RunWorkerCompleted += DoneRequestApi; //_worker.RunWorkerAsync(); //((BackgroundWorker)sender).DoWork -= DoRequestApi; //((BackgroundWorker)sender).RunWorkerCompleted -= DoneRequestApi; }
/// <summary> /// Starts a background task to perform the request in the background. /// </summary> private void RequestApi() { // Check the worker if (_worker != null) { _worker.Dispose(); } // Initialize values IsComplete = false; IsError = false; IsWorking = true; Error = string.Empty; Result = null; // Run the initialization in the background. _worker = new BackgroundWorker(); _worker.DoWork += DoRequestApi; _worker.RunWorkerCompleted += DoneRequestApi; _worker.RunWorkerAsync(); }
/// <summary> /// Background task work method. /// Contacts the WaniKani API. /// </summary> private void DoRequestApi(object sender, DoWorkEventArgs e) { string[] responses; try { List <string> uri = new List <string>(); if (_parent.ImportMode == WkImportMode.All || _parent.ImportMode == WkImportMode.Kanji) { uri.Add(string.Format("https://www.wanikani.com/api/v1.2/user/{0}/kanji", _parent.ApiKey)); } if (_parent.ImportMode == WkImportMode.All || _parent.ImportMode == WkImportMode.Vocab) { uri.Add(string.Format("https://www.wanikani.com/api/v1.2/user/{0}/vocabulary/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", _parent.ApiKey)); uri.Add(string.Format("https://www.wanikani.com/api/v1.2/user/{0}/vocabulary/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", _parent.ApiKey)); } responses = new string[uri.Count]; for (int i = 0; i < uri.Count(); i++) { responses[i] = Request(uri[i]); } } catch (Exception ex) { LogHelper.GetLogger("WkImport").Error("An error occured during the request to the WaniKani API.", ex); Error = "An error occured while trying to request the data. Please consult your log file for more details."; IsError = true; return; } // Now read that response! try { JObject[] jroots = new JObject[responses.Count()]; bool isOk = true; for (int i = 0; i < jroots.Count(); i++) { jroots[i] = JObject.Parse(responses[i]); if (CheckError(jroots[i])) { isOk = false; break; } } if (isOk) { // No error. WkImportResult result = new WkImportResult(); result.Username = (string)jroots[0]["user_information"]["username"]; List <WkItem> items = new List <WkItem>(); for (int i = 0; i < jroots.Count(); i++) { foreach (WkItem item in ReadItems(jroots[i], i == 0 && (_parent.ImportMode == WkImportMode.All || _parent.ImportMode == WkImportMode.Kanji))) { items.Add(item); } } result.Items = items; Result = result; IsComplete = true; } } catch (Exception ex) { LogHelper.GetLogger("WkImport").Error("An error occured during the JSON parsing.", ex); Error = "An error occured while trying to read the data. Please consult your log file for more details."; IsError = true; return; } }
/// <summary> /// Background task work method. /// Contacts the WaniKani API. /// </summary> private async Task DoRequestApi() { try { using (var client = new HttpClient()) { var baseUrl = "https://api.wanikani.com/v2/"; client.DefaultRequestHeaders.Add("Authorization", $"Bearer {_parent.ApiKey}"); List <string> subjectTypes = new List <string>(); if (_parent.ImportMode == WkImportMode.All || _parent.ImportMode == WkImportMode.Kanji) { subjectTypes.Add("kanji"); } if (_parent.ImportMode == WkImportMode.All || _parent.ImportMode == WkImportMode.Vocab) { subjectTypes.Add("vocabulary"); } if (subjectTypes.Count > 0) { List <(JToken, JToken)> results = new List <(JToken, JToken)>(); JObject response = JObject.Parse(await client.GetStringAsync(baseUrl + $"assignments?subject_types={String.Join(",", subjectTypes)}")); JObject subRes = JObject.Parse(await client.GetStringAsync(baseUrl + $"subjects?ids={String.Join(",", response["data"].Select(t => t["data"]["subject_id"]))}")); results.AddRange(response["data"].Select(r => (subRes["data"].First(s => (int)s["id"] == (int)r["data"]["subject_id"])["data"], r["data"]))); while (response["pages"]["next_url"] != null && results.Count < (int)response["total_count"]) { response = JObject.Parse(await client.GetStringAsync((string)response["pages"]["next_url"])); subRes = JObject.Parse(await client.GetStringAsync(baseUrl + $"subjects?ids={String.Join(",", response["data"].Select(t => t["data"]["subject_id"]))}")); results.AddRange(response["data"].Select(r => (subRes["data"].First(s => (int)s["id"] == (int)r["data"]["subject_id"])["data"], r["data"]))); } WkImportResult result = new WkImportResult(); //TODO: Level 0 is "haven't completed the lesson" - what do with those? //TODO: Hint vs Mnemonic: Mnemonic is the one that comes up in lessons, hint comes up in reviews (and only exists for some objects?). // Which does the user want? result.Items = results.Where(t => (int)t.Item2["srs_stage"] != 0).Select(((JToken s, JToken a)t) => new WkItem { IsKanji = (string)t.a["subject_type"] == "kanji", KanjiReading = (string)t.s["characters"], MeaningNote = (string)t.s["meaning_hint"] ?? (string)t.s["meaning_mnemonic"], ReadingNote = (string)t.s["reading_hint"] ?? (string)t.s["reading_mnemonic"], Meanings = string.Join(',', t.s["meanings"].Where(m => (bool)m["accepted_answer"]).Select(m => (string)m["meaning"])), NextReviewDate = (DateTime?)t.a["available_at"], Readings = string.Join(',', t.s["readings"].Where(r => (bool)r["accepted_answer"]).Select(r => (string)r["reading"])), SrsLevel = (short)((short)t.a["srs_stage"] - 1), WkLevel = (int)t.s["level"], }).ToList(); Result = result; IsComplete = true; } } } catch (Exception ex) { LogHelper.GetLogger("WkImport").Error("An error occured during the request to the WaniKani API.", ex); Error = "An error occured while trying to request the data. Please consult your log file for more details."; IsError = true; return; } }