private static void DownloadGalleryBackgroundWorker_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker backgroundWorker = sender as BackgroundWorker; DownloadGalleryRunArg runArg = e.Argument as DownloadGalleryRunArg; string cachedMetadataPath; if (runArg.PathFormatter.IsEnabled) { cachedMetadataPath = runArg.PathFormatter.GetMetadata(runArg.Id); } else { cachedMetadataPath = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", runArg.PathFormatter.GetCacheDirectory(), runArg.Id, ".json"); } Metadata metadata = runArg.SearchResultCache.Find(runArg.Id); if (metadata == null) { metadata = JsonUtility.LoadFromFile <Metadata>(cachedMetadataPath); } if (metadata == null) { string error = ""; try { string uri = string.Format(CultureInfo.InvariantCulture, "https://nhentai.net/api/gallery/{0}", runArg.Id); using (HttpResponseMessage response = Task.Run(() => runArg.HttpClient.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead)).GetAwaiter().GetResult()) { if (!response.IsSuccessStatusCode) { response.EnsureSuccessStatusCode(); //error = string.Format(CultureInfo.InvariantCulture, "{0} ({1})", response.ReasonPhrase, response.StatusCode); } else { try { string jsonText = Task.Run(() => response.Content.ReadAsStringAsync()).GetAwaiter().GetResult(); // TODO: show actual download progress... { int currentDownloadSize = 1; int totalDownloadSize = 1; GalleryDownloadProgressArg progressArg = new GalleryDownloadProgressArg(0, 0, error); backgroundWorker.ReportProgress((int)(currentDownloadSize / (float)totalDownloadSize * 100), progressArg); } metadata = JsonConvert.DeserializeObject <Metadata>(jsonText); // TODO: handle unsafe concurrent workers downloading at the same time. //if (!File.Exists(cachedMetadataPath)) { try { Directory.CreateDirectory(Path.GetDirectoryName(cachedMetadataPath)); File.WriteAllText(cachedMetadataPath, JsonConvert.SerializeObject(metadata, Formatting.Indented)); } catch (Exception ex) { GalleryDownloadCancelledArg cancelledArg = new GalleryDownloadCancelledArg(runArg.Id, ex.Message); e.Result = cancelledArg; return; } } } catch (Exception ex) { GalleryDownloadCancelledArg cancelledArg = new GalleryDownloadCancelledArg(runArg.Id, ex.Message); e.Result = cancelledArg; return; } } } } catch (Exception ex) { GalleryDownloadCancelledArg cancelledArg = new GalleryDownloadCancelledArg(runArg.Id, ex.Message); e.Result = cancelledArg; return; } } GalleryDownloadCompletedArg completedArg = new GalleryDownloadCompletedArg(runArg.Id, metadata); e.Result = completedArg; }
private void DownloadGalleryBackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) { GalleryDownloadProgressArg arg = e.UserState as GalleryDownloadProgressArg; OnGalleryDownloadReportProgress(new GalleryDownloadReportProgressEventArgs(arg.DownloadedBytes, arg.DownloadSize, arg.Error)); }