public byte[] DownloadPost(long postId) { var post = _dbContext.Posts .Include(x => x.Sections) .Include(x => x.Author) .FirstOrDefault(x => x.PostId == postId); if (post == null) { throw new PostException(PostError.PostNotFound); } return(DownloaderHelper.GetInstance().GeneratePostPdf(post.Title, post.Author.Alias, post.CreationDate, post.Sections.Select(x => x.Content))); }
/// <summary> /// Download the data using HttpWebRequest. It will read a buffer of bytes from the /// response stream, and store the buffer to a MemoryStream cache first. /// If the cache is full, or the download is paused, canceled or completed, write /// the data in cache to local file. /// </summary> void DownloadInternal(object obj) { if (this.Status != DownloadStatus.Waiting) { return; } HttpWebRequest webRequest = null; HttpWebResponse webResponse = null; Stream responseStream = null; MemoryStream downloadCache = null; this.lastStartTime = DateTime.Now; try { if (!HasChecked) { string filename = string.Empty; CheckUrlAndFile(out filename); } this.EnsurePropertyValid(); // Set the status. this.Status = DownloadStatus.Downloading; // Create a request to the file to be downloaded. webRequest = DownloaderHelper.InitializeHttpWebRequest(this); // Specify the block to download. if (EndPoint != int.MaxValue) { webRequest.AddRange((int)StartPoint + (int)DownloadedSize, (int)EndPoint); } else { webRequest.AddRange((int)StartPoint + (int)DownloadedSize); } // Retrieve the response from the server and get the response stream. webResponse = (HttpWebResponse)webRequest.GetResponse(); responseStream = webResponse.GetResponseStream(); // Cache data in memory. downloadCache = new MemoryStream(this.MaxCacheSize); byte[] downloadBuffer = new byte[this.BufferSize]; int bytesSize = 0; CachedSize = 0; int receivedBufferCount = 0; // Download the file until the download is paused, canceled or completed. while (true) { // Read a buffer of data from the stream. bytesSize = responseStream.Read(downloadBuffer, 0, downloadBuffer.Length); // If the cache is full, or the download is paused, canceled or // completed, write the data in cache to local file. if (this.Status != DownloadStatus.Downloading || bytesSize == 0 || this.MaxCacheSize < CachedSize + bytesSize) { try { // Write the data in cache to local file. WriteCacheToFile(downloadCache, CachedSize); this.DownloadedSize += CachedSize; // Stop downloading the file if the download is paused, // canceled or completed. if (this.Status != DownloadStatus.Downloading || bytesSize == 0) { break; } // Reset cache. downloadCache.Seek(0, SeekOrigin.Begin); CachedSize = 0; } catch (Exception ex) { // Fire the DownloadCompleted event with the error. this.OnDownloadCompleted( new DownloadCompletedEventArgs( null, this.DownloadedSize, this.TotalSize, this.TotalUsedTime, ex)); return; } } // Write the data from the buffer to the cache in memory. downloadCache.Write(downloadBuffer, 0, bytesSize); CachedSize += bytesSize; receivedBufferCount++; // Fire the DownloadProgressChanged event. if (receivedBufferCount == this.BufferCountPerNotification) { InternalDownloadProgressChanged(CachedSize); receivedBufferCount = 0; } } // Update the used time when the current doanload is stopped. usedTime = usedTime.Add(DateTime.Now - lastStartTime); // Update the status of the client. Above loop will be stopped when the // status of the client is pausing, canceling or completed. if (this.Status == DownloadStatus.Pausing) { this.Status = DownloadStatus.Paused; } else if (this.Status == DownloadStatus.Canceling) { this.Status = DownloadStatus.Canceled; } else { this.Status = DownloadStatus.Completed; return; } } catch (Exception ex) { // Fire the DownloadCompleted event with the error. this.OnDownloadCompleted( new DownloadCompletedEventArgs( null, this.DownloadedSize, this.TotalSize, this.TotalUsedTime, ex)); return; } finally { // When the above code has ended, close the streams. if (responseStream != null) { responseStream.Close(); } if (webResponse != null) { webResponse.Close(); } if (downloadCache != null) { downloadCache.Close(); } } }
/// <summary> /// Check whether the destination file exists. If not, create a file with the same /// size as the file to be downloaded. /// </summary> void CheckFileOrCreateFile() { DownloaderHelper.CheckFileOrCreateFile(this, fileLocker); }
/// <summary> /// Check the Uri to find its size, and whether it supports "Pause". /// </summary> public void CheckUrl(out string fileName) { fileName = DownloaderHelper.CheckUrl(this); }
private void SearchSpace_Loaded(object sender, RoutedEventArgs e) { #if true bool loading = false; // Metadata 로딩 Task.Run(async() => { if (IsMetadataLoaded || StartsLoading) { return; } StartsLoading = true; Profiler.Push("Check metadata exists"); if (!HitomiIndex.Instance.CheckMetadataExist() || Settings.Instance.Hitomi.AutoSync) { //#if !DEBUG // Koromo_Copy.Monitor.Instance.ControlEnable = true; // Koromo_Copy.Monitor.Instance.Push("다운로드가 계속 진행되지 않는다면 이 창에서 Enter키를 눌러주세요"); // Koromo_Copy.Console.Console.Instance.Show(); //#endif Profiler.Push("Start download metadata"); MainWindow.Instance.Fade_MiddlePopup(true, (string)FindResource("msg_download_metadata")); #if true //HitomiIndex.Instance.MetadataDownloadStatusEvent = UpdateDownloadText; await HitomiIndex.Instance.DownloadMetadata(); #endif MainWindow.Instance.FadeOut_MiddlePopup((string)FindResource("msg_download_data_complete"), false); Koromo_Copy.Monitor.Instance.ControlEnable = false; } else { Profiler.Push("Load metadata, hiddendata"); try { HitomiIndex.Instance.Load(); //MainWindow.Instance.Fade_MiddlePopup(false); } catch (Exception ex) { Koromo_Copy.Monitor.Instance.Push($"[Hitomi DataLoad] {ex.Message}\r\n{ex.StackTrace}"); } } if (Settings.Instance.Hitomi.UsingOriginalTitle) { Profiler.Push("Check titles exists"); if (!HitomiTitle.Instance.CheckExist()) { MainWindow.Instance.ModifyText_MiddlePopup((string)FindResource("msg_download_title")); await HitomiTitle.Instance.DownloadTitle(); MainWindow.Instance.FadeOut_MiddlePopup((string)FindResource("msg_download_data_complete"), false); } HitomiTitle.Instance.Load(); HitomiTitle.Instance.ReplaceToOriginTitle(); Koromo_Copy.Monitor.Instance.Push($"Loaded titles: '{HitomiTitle.Instance.Count.ToString("#,#")}' articles."); } MainWindow.Instance.Fade_MiddlePopup(false); Profiler.Push("Rebuild tag data"); HitomiIndex.Instance.RebuildTagData(); if (HitomiIndex.Instance.metadata_collection != null) { Koromo_Copy.Monitor.Instance.Push($"Loaded metadata: '{HitomiIndex.Instance.metadata_collection.Count.ToString("#,#")}' articles."); if (Settings.Instance.Hitomi.UsingOptimization) { HitomiIndex.Instance.OptimizeMetadata(); Koromo_Copy.Monitor.Instance.Push($"Optimize metadata: '{HitomiIndex.Instance.metadata_collection.Count.ToString("#,#")}' articles."); } } GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); loading = true; }).ContinueWith(t => { if ((IsMetadataLoaded || StartsLoading) && !loading) { return; } TotalProgress.IsIndeterminate = false; TotalProgress.Value = 0; IsMetadataLoaded = true; Storyboard sb = TotalProgress.FindResource("FadeProgressStoryboard") as Storyboard; if (sb != null) { sb.Completed += Sb_Completed; BeginStoryboard(sb); } RecommendSpace.Instance.Update(); if (Koromo_Copy.Version.RequireTidy(System.Reflection.Assembly.GetExecutingAssembly().Location)) { (new PatchNoteWindow()).Show(); //Process.Start("https://github.com/dc-koromo/koromo-copy/blob/master/Document/Update.md"); } Task.Run(() => CheckUpdate()).ContinueWith((x) => ScriptManager.Instance.Initialization()).ContinueWith((x) => SettingViewScript.Instance.Init()); Task.Run(() => DownloaderHelper.LoadOthersAsync()); Task.Run(() => DPIB.Instance.Start()); }, TaskScheduler.FromCurrentSynchronizationContext()); #endif Window w = Window.GetWindow(this); // 이거 지우면 디자이너 오류남 if (w != null) { w.LocationChanged += (object obj, EventArgs args) => { var offset = AutoComplete.HorizontalOffset; AutoComplete.HorizontalOffset = offset + 1; AutoComplete.HorizontalOffset = offset; }; } logic = new AutoCompleteLogic(SearchText, AutoComplete, AutoCompleteList); }
private void Button_Click(object sender, RoutedEventArgs e) { var tag = (sender as Button).Tag.ToString(); if (tag == "Search" && IsMetadataLoaded) { lock (load_lock) { if (!loading) { AppendAsync(SearchText.Text); } else { StopLoad(); } } } else if (tag == "Tidy") { if (!Settings.Instance.UXSetting.UsingThumbnailSearchElements) { int count = SearchPanel.Children.Count / 2; SearchPanel.Children.Clear(); GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); if (count > 0) { MainWindow.Instance.FadeOut_MiddlePopup($"{count}{(string)FindResource("msg_tidy")}", false); } } else { int count = SearchMaterialPanel.Children.Count / 2; SearchMaterialPanel.Children.Clear(); GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); if (count > 0) { MainWindow.Instance.FadeOut_MiddlePopup($"{count}{(string)FindResource("msg_tidy")}", false); } } } else if (tag == "SelectAll") { if (!Settings.Instance.UXSetting.UsingThumbnailSearchElements) { SearchPanel.Children.OfType <SearchElements>().ToList().ForEach(x => x.Select = true); } else { SearchMaterialPanel.Children.OfType <SearchMaterialElements>().ToList().ForEach(x => x.Select = true); } } else if (tag == "DeSelectAll") { if (!Settings.Instance.UXSetting.UsingThumbnailSearchElements) { SearchPanel.Children.OfType <SearchElements>().ToList().ForEach(x => x.Select = false); } else { SearchMaterialPanel.Children.OfType <SearchMaterialElements>().ToList().ForEach(x => x.Select = false); } } else if (tag == "Download") { if (!Settings.Instance.UXSetting.UsingThumbnailSearchElements) { int count = 0; SearchPanel.Children.OfType <SearchElements>().ToList().Where(x => x.Select).ToList().ForEach(x => { var ha = x.Article as HitomiArticle; var prefix = HitomiCommon.MakeDownloadDirectory(ha, SearchText.Text); Directory.CreateDirectory(prefix); if (!ha.IsUnstable) { DownloadSpace.Instance.RequestDownload(x.Article.Title, x.Article.ImagesLink.Select(y => HitomiCommon.GetDownloadImageAddress((x.Article as HitomiArticle).Magic, y)).ToArray(), x.Article.ImagesLink.Select(y => Path.Combine(prefix, y)).ToArray(), Koromo_Copy.Interface.SemaphoreExtends.Default, prefix, x.Article); } else { DownloaderHelper.ProcessUnstable(ha.UnstableModel); } count++; }); if (count > 0) { MainWindow.Instance.FadeOut_MiddlePopup($"{count}{(string)FindResource("msg_download_start")}"); } } else { int count = 0; SearchMaterialPanel.Children.OfType <SearchMaterialElements>().ToList().Where(x => x.Select).ToList().ForEach(x => { var ha = x.Article as HitomiArticle; var prefix = HitomiCommon.MakeDownloadDirectory(x.Article as HitomiArticle, SearchText.Text); Directory.CreateDirectory(prefix); if (!ha.IsUnstable) { DownloadSpace.Instance.RequestDownload(x.Article.Title, x.Article.ImagesLink.Select(y => HitomiCommon.GetDownloadImageAddress((x.Article as HitomiArticle).Magic, y)).ToArray(), x.Article.ImagesLink.Select(y => Path.Combine(prefix, y)).ToArray(), Koromo_Copy.Interface.SemaphoreExtends.Default, prefix, x.Article); } else { DownloaderHelper.ProcessUnstable(ha.UnstableModel); } count++; }); if (count > 0) { MainWindow.Instance.FadeOut_MiddlePopup($"{count}{(string)FindResource("msg_download_start")}"); } } } }
private async void AppendAsync(string content) { if (content.Trim().StartsWith("http://") || content.Trim().StartsWith("https://")) { DownloaderHelper.ProcessOthers(content.Trim()); return; } try { List <HitomiIndexMetadata> result; int start_element = 0; int count_element = 0; if (content.Split(' ').Any(x => x.StartsWith("/"))) { var elem = content.Split(' ').Where(x => x.StartsWith("/")).ElementAt(0); start_element = Convert.ToInt32(elem.Substring(1)); content = content.Replace(elem, " "); } if (content.Split(' ').Any(x => x.StartsWith("?"))) { var elem = content.Split(' ').Where(x => x.StartsWith("?")).ElementAt(0); count_element = Convert.ToInt32(elem.Substring(1)); content = content.Replace(elem, " "); } if (!Settings.Instance.Hitomi.UsingAdvancedSearch || content.Contains("recent:")) { result = await HitomiDataParser.SearchAsync(content.Trim()); if (content.Contains("recent:")) { var elem = content.Split(' ').Where(x => x.StartsWith("recent:")).ElementAt(0); int recent_count = 0; int recent_start = 0; if (elem.Substring("recent:".Length).Contains("-")) { recent_start = Convert.ToInt32(elem.Substring("recent:".Length).Split('-')[0]); recent_count = Convert.ToInt32(elem.Substring("recent:".Length).Split('-')[1]); } else { recent_count = Convert.ToInt32(elem.Substring("recent:".Length)); } SearchText.Text = "recent:" + (recent_start + recent_count) + "-" + recent_count; } } else { result = await HitomiDataSearchAdvanced.Search(content.Trim()); } if (start_element != 0 && start_element <= result.Count) { result.RemoveRange(0, start_element); } if (count_element != 0 && count_element < result.Count) { result.RemoveRange(count_element, result.Count - count_element); } SearchCount.Text = $"{FindResource("searched")}: {(result.Count != 0 ? result.Count.ToString("#,#") : "0")}{(FindResource("count_postfix"))}"; SearchButton.Content = $"{FindResource("stop")}"; _ = Task.Run(() => LoadThumbnail(result)); } catch { SearchCount.Text = (string)FindResource("msg_incorret_search_grammar"); } }
private void Button_Click(object sender, RoutedEventArgs e) { var btn = sender as Button; if (btn.Tag.ToString() == "DownloadAll") { int count = 0; ArticlePanel.Children.OfType <SearchSimpleElements>().ToList().ForEach(x => { var ha = x.Article as HitomiArticle; ha.Artists = new string[] { Artist }; var prefix = HitomiCommon.MakeDownloadDirectory(ha); Directory.CreateDirectory(prefix); if (!ha.IsUnstable) { DownloadSpace.Instance.RequestDownload(x.Article.Title, x.Article.ImagesLink.Select(y => HitomiCommon.GetDownloadImageAddress((x.Article as HitomiArticle).Magic, y)).ToArray(), x.Article.ImagesLink.Select(y => Path.Combine(prefix, y)).ToArray(), Koromo_Copy.Interface.SemaphoreExtends.Default, prefix, x.Article); } else { DownloaderHelper.ProcessUnstable(ha.UnstableModel); } count++; }); if (count > 0) { MainWindow.Instance.FadeOut_MiddlePopup($"{count}{FindResource("msg_download_start")}"); } MainWindow.Instance.Activate(); MainWindow.Instance.FocusDownload(); Close(); } else if (btn.Tag.ToString() == "Download") { int count = 0; ArticlePanel.Children.OfType <SearchSimpleElements>().ToList().Where(x => x.Select).ToList().ForEach(x => { var ha = x.Article as HitomiArticle; ha.Artists = new string[] { Artist }; var prefix = HitomiCommon.MakeDownloadDirectory(ha); Directory.CreateDirectory(prefix); if (!ha.IsUnstable) { DownloadSpace.Instance.RequestDownload(x.Article.Title, x.Article.ImagesLink.Select(y => HitomiCommon.GetDownloadImageAddress((x.Article as HitomiArticle).Magic, y)).ToArray(), x.Article.ImagesLink.Select(y => Path.Combine(prefix, y)).ToArray(), Koromo_Copy.Interface.SemaphoreExtends.Default, prefix, x.Article); } else { DownloaderHelper.ProcessUnstable(ha.UnstableModel); } count++; }); if (count > 0) { MainWindow.Instance.FadeOut_MiddlePopup($"{count}{FindResource("msg_download_start")}"); } MainWindow.Instance.Activate(); MainWindow.Instance.FocusDownload(); } }
private void Button_Click(object sender, RoutedEventArgs e) { var btn = sender as Button; if (btn.Tag.ToString() == "DownloadAll") { try { int count = 0; ArticlePanel.Children.OfType <SearchSimpleElements>().ToList().ForEach(x => { var ha = x.Article as HitomiArticle; ha.Artists = new string[] { Artist }; var prefix = HitomiCommon.MakeDownloadDirectory(ha); Directory.CreateDirectory(prefix); if (!ha.IsUnstable) { DownloadSpace.Instance.RequestDownload(x.Article.Title, ha.ImagesLink.Select(y => HitomiCommon.GetDownloadImageAddress((x.Article as HitomiArticle).Magic, y, ha.HasWebp[y], ha.HasWebp[y] || ha.Hashs[y].Length > 3 ? ha.Hashs[y] : "")).ToArray(), ha.ImagesLink.Select(y => Path.Combine(prefix, ha.HasWebp[y] ? y + ".webp" : y)).ToArray(), Koromo_Copy.Interface.SemaphoreExtends.Default, prefix, x.Article); } else { DownloaderHelper.ProcessUnstable(ha.UnstableModel); } count++; }); if (count > 0) { MainWindow.Instance.FadeOut_MiddlePopup($"{count}{FindResource("msg_download_start")}"); } MainWindow.Instance.Activate(); MainWindow.Instance.FocusDownload(); Close(); } catch (Exception ex) { Koromo_Copy.Monitor.Instance.Push("[Artist Viewer] " + ex.Message); MessageBox.Show($"{FindResource("msg_wait_fucking_loading")}", "Koromo Copy", MessageBoxButton.OK, MessageBoxImage.Error); } } else if (btn.Tag.ToString() == "Download") { try { int count = 0; ArticlePanel.Children.OfType <SearchSimpleElements>().ToList().Where(x => x.Select).ToList().ForEach(x => { var ha = x.Article as HitomiArticle; ha.Artists = new string[] { Artist }; var prefix = HitomiCommon.MakeDownloadDirectory(ha); Directory.CreateDirectory(prefix); if (!ha.IsUnstable) { DownloadSpace.Instance.RequestDownload(x.Article.Title, ha.ImagesLink.Select(y => HitomiCommon.GetDownloadImageAddress((x.Article as HitomiArticle).Magic, y, ha.HasWebp[y], ha.HasWebp[y] || ha.Hashs[y].Length > 3 ? ha.Hashs[y] : "")).ToArray(), ha.ImagesLink.Select(y => Path.Combine(prefix, ha.HasWebp[y] ? y + ".webp" : y)).ToArray(), Koromo_Copy.Interface.SemaphoreExtends.Default, prefix, x.Article); } else { DownloaderHelper.ProcessUnstable(ha.UnstableModel); } count++; }); if (count > 0) { MainWindow.Instance.FadeOut_MiddlePopup($"{count}{FindResource("msg_download_start")}"); } MainWindow.Instance.Activate(); MainWindow.Instance.FocusDownload(); } catch (Exception ex) { Koromo_Copy.Monitor.Instance.Push("[Artist Viewer] " + ex.Message); MessageBox.Show($"{FindResource("msg_wait_fucking_all_loading")}", "Koromo Copy", MessageBoxButton.OK, MessageBoxImage.Error); } } }
private async void AppendAsync(string content) { if (content.Trim().StartsWith("http://") || content.Trim().StartsWith("https://")) { DownloaderHelper.ProcessOthers(content.Trim()); return; } try { List <HitomiMetadata> result; int start_element = 0; int count_element = 0; if (content.Contains('/')) { var elem = content.Split(' ').Where(x => x.StartsWith("/")).ElementAt(0); start_element = Convert.ToInt32(elem.Substring(1)); content = content.Replace(elem, " "); } if (content.Contains('?')) { var elem = content.Split(' ').Where(x => x.StartsWith("?")).ElementAt(0); count_element = Convert.ToInt32(elem.Substring(1)); content = content.Replace(elem, " "); } if (!Settings.Instance.Hitomi.UsingAdvancedSearch || content.Contains("recent:")) { result = await HitomiDataParser.SearchAsync(content.Trim()); if (content.Contains("recent:")) { var elem = content.Split(' ').Where(x => x.StartsWith("recent:")).ElementAt(0); int recent_count = 0; int recent_start = 0; if (elem.Substring("recent:".Length).Contains("-")) { recent_start = Convert.ToInt32(elem.Substring("recent:".Length).Split('-')[0]); recent_count = Convert.ToInt32(elem.Substring("recent:".Length).Split('-')[1]); } else { recent_count = Convert.ToInt32(elem.Substring("recent:".Length)); } SearchText.Text = "recent:" + (recent_start + recent_count) + "-" + recent_count; } } else { result = await HitomiDataSearchAdvanced.Search(content.Trim()); } if (start_element != 0 && start_element <= result.Count) { result.RemoveRange(0, start_element); } if (count_element != 0 && count_element < result.Count) { result.RemoveRange(count_element, result.Count - count_element); } SearchCount.Text = $"검색된 항목: {result.Count.ToString("#,#")}개"; _ = Task.Run(() => LoadThumbnail(result)); } catch { SearchCount.Text = "검색 문법이 잘못되었습니다."; } }
private void Button_Click(object sender, RoutedEventArgs e) { switch ((sender as Button).Tag.ToString()) { case "Preview": (new PreviewWindow(Article)).Show(); break; case "Artist": { if (Article is HitomiArticle ha) { if (ha.Artists != null) { (new ArtistViewerWindow(ha.Artists[0])).Show(); } } } break; case "Group": { if (Article is HitomiArticle ha) { if (ha.Groups != null) { (new GroupViewerWindow(ha.Groups[0])).Show(); } } } break; case "": case "Hitomi": { if (Article is HitomiArticle ha) { System.Diagnostics.Process.Start($"{HitomiCommon.HitomiAddress}galleries/{ha.Magic}.html"); } } break; case "Exhentai": { if (Article is HitomiArticle ha) { string result = ExHentaiTool.GetAddressFromMagicTitle(ha.Magic, ha.Title); if (result != "") { System.Diagnostics.Process.Start(result); } else { MainWindow.Instance.FadeOut_MiddlePopup("익헨 주소를 찾지 못했습니다 ㅠㅠ", false); } } } break; case "Series": { if (Article is HitomiArticle ha) { if (ha.Series != null) { (new FinderWindow($"series:{ha.Series[0].Replace(' ', '_')}")).Show(); } } } break; case "Character": { if (Article is HitomiArticle ha) { if (ha.Characters != null) { (new FinderWindow($"character:{ha.Characters[0].Replace(' ', '_')}")).Show(); } } } break; case "Comment": { if (Article is HitomiArticle ha) { string result = ExHentaiTool.GetAddressFromMagicTitle(ha.Magic, ha.Title); if (result != "") { (new CommentWindow(result)).Show(); } else { MainWindow.Instance.FadeOut_MiddlePopup("익헨 주소를 찾지 못했습니다 ㅠㅠ", false); } } } break; case "Download": { if (Article is HitomiArticle ha) { var prefix = HitomiCommon.MakeDownloadDirectory(ha); Directory.CreateDirectory(prefix); if (!ha.IsUnstable) { DownloadSpace.Instance.RequestDownload(ha.Title, ha.ImagesLink.Select(y => HitomiCommon.GetDownloadImageAddress(ha.Magic, y)).ToArray(), ha.ImagesLink.Select(y => Path.Combine(prefix, y)).ToArray(), Koromo_Copy.Interface.SemaphoreExtends.Default, prefix, ha); } else { DownloaderHelper.ProcessUnstable(ha.UnstableModel); } MainWindow.Instance.FadeOut_MiddlePopup($"1개 항목 다운로드 시작..."); MainWindow.Instance.Activate(); MainWindow.Instance.FocusDownload(); Close(); } } break; } }