Exemple #1
0
        public bool WithPagesFolder(int galleryId, Action <string> action)
        {
            string cachedPagesPath;

            if (PathFormatter.IsEnabled)
            {
                string cachedMetadataFilePath = PathFormatter.GetMetadata(galleryId);

                Metadata metadata = SearchResultCache.Find(galleryId) ?? JsonUtility.LoadFromFile <Metadata>(cachedMetadataFilePath);

                if (metadata == null)
                {
                    return(false);
                }

                cachedPagesPath = PathFormatter.GetPages(metadata);
            }
            else
            {
                cachedPagesPath = string.Format(CultureInfo.InvariantCulture, "{0}{1}/", PathFormatter.GetCacheDirectory(), galleryId);
            }

            if (!Directory.Exists(cachedPagesPath))
            {
                return(false);
            }

            if (action != null)
            {
                action.Invoke(cachedPagesPath);
            }

            return(true);
        }
Exemple #2
0
        public int[] GetCachedPageIndices(int galleryId)
        {
            List <int> indices = new List <int>();

            string cachedMetadataFilePath;

            if (PathFormatter.IsEnabled)
            {
                cachedMetadataFilePath = PathFormatter.GetMetadata(galleryId);
            }
            else
            {
                cachedMetadataFilePath = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", PathFormatter.GetCacheDirectory(), galleryId, ".json");
            }

            Metadata metadata = SearchResultCache.Find(galleryId) ?? JsonUtility.LoadFromFile <Metadata>(cachedMetadataFilePath);

            if (metadata == null)
            {
                return(indices.ToArray());
            }

            string cachedPagesPath;

            if (PathFormatter.IsEnabled)
            {
                cachedPagesPath = PathFormatter.GetPages(metadata);
            }
            else
            {
                cachedPagesPath = string.Format(CultureInfo.InvariantCulture, "{0}{1}/", PathFormatter.GetCacheDirectory(), galleryId);
            }

            if (!Directory.Exists(cachedPagesPath))
            {
                return(indices.ToArray());
            }

            DirectoryInfo dirInfo = new DirectoryInfo(cachedPagesPath);

            foreach (FileInfo fileInfo in dirInfo.EnumerateFiles())
            {
                string fileTitle = Path.GetFileNameWithoutExtension(fileInfo.Name).TrimStart(new char[] { '0' });
                int    num;

                if (int.TryParse(fileTitle, out num))
                {
                    if (num >= 1 && num <= metadata.Images.Pages.Count)
                    {
                        indices.Add(num);
                    }
                }
            }

            return(indices.ToArray());
        }
Exemple #3
0
        public bool WithArchive(int galleryId, Action <string> action)
        {
            List <string> cachedArcihveFilePaths = new List <string>();

            if (PathFormatter.IsEnabled)
            {
                string cachedMetadataFilePath = PathFormatter.GetMetadata(galleryId);

                Metadata metadata = SearchResultCache.Find(galleryId) ?? JsonUtility.LoadFromFile <Metadata>(cachedMetadataFilePath);

                if (metadata == null)
                {
                    return(false);
                }

                foreach (IArchiveWriter archiveWriter in ArchiveWriters)
                {
                    string archivePath = PathFormatter.GetArchive(metadata, archiveWriter);

                    cachedArcihveFilePaths.Add(archivePath);
                }
            }
            else
            {
                foreach (IArchiveWriter archiveWriter in ArchiveWriters)
                {
                    string archivePath = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", PathFormatter.GetCacheDirectory(), galleryId, archiveWriter.FileExtension);

                    cachedArcihveFilePaths.Add(archivePath);
                }
            }

            foreach (string archivePath in cachedArcihveFilePaths)
            {
                if (!File.Exists(archivePath))
                {
                    continue;
                }

                if (action != null)
                {
                    action.Invoke(archivePath);
                }

                return(true);
            }

            return(false);
        }
Exemple #4
0
        private static Metadata GetGalleryMetadata(int galleryId, IPathFormatter pathFormatter, ISearchResultCache searchResultCache)
        {
            string cachedMetadataFilePath;

            if (pathFormatter.IsEnabled)
            {
                cachedMetadataFilePath = pathFormatter.GetMetadata(galleryId);
            }
            else
            {
                cachedMetadataFilePath = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", pathFormatter.GetCacheDirectory(), galleryId, ".json");
            }

            Metadata metadata = searchResultCache.Find(galleryId) ?? JsonUtility.LoadFromFile <Metadata>(cachedMetadataFilePath);

            return(metadata);
        }
Exemple #5
0
        public void ShowToolTip(Control control)
        {
            if (!associatedControls.ContainsKey(control))
            {
                return;
            }

            int    associatedGalleryId = associatedControls[control];
            string cachedMetadataFileName;

            if (PathFormatter.IsEnabled)
            {
                cachedMetadataFileName = PathFormatter.GetMetadata(associatedGalleryId);
            }
            else
            {
                cachedMetadataFileName = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", PathFormatter.GetCacheDirectory(), associatedGalleryId, ".json");
            }

            Metadata metadata = JsonUtility.LoadFromFile <Metadata>(cachedMetadataFileName);

            if (metadata == null)
            {
                return;
            }

            string html = GalleryTooltipTemplate.GetFormattedText(metadata);

            if (string.IsNullOrEmpty(html))
            {
                return;
            }

            Point toolTipLocation = control.Location;

            toolTipLocation.Offset(0, control.Height);

            Location = toolTipLocation;

            webBrowser.DocumentText = html;
        }
Exemple #6
0
        public bool DoesCoverExists(int galleryId)
        {
            string cachedMetadataFilePath;

            if (PathFormatter.IsEnabled)
            {
                cachedMetadataFilePath = PathFormatter.GetMetadata(galleryId);
            }
            else
            {
                cachedMetadataFilePath = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", PathFormatter.GetCacheDirectory(), galleryId, ".json");
            }

            Metadata metadata = SearchResultCache.Find(galleryId) ?? JsonUtility.LoadFromFile <Metadata>(cachedMetadataFilePath);

            if (metadata == null)
            {
                return(false);
            }

            return(WithCover(metadata, null));
        }
Exemple #7
0
        // NOTE: at the moment both details and download share the same webbrowser.
        private bool ShowDetailsOrDownload(int galleryId, Action <Metadata> action)
        {
            DetailsModel.AddSearch(galleryId);

            string cachedMetadataFilePath;

            if (PathFormatter.IsEnabled)
            {
                cachedMetadataFilePath = PathFormatter.GetMetadata(galleryId);
            }
            else
            {
                cachedMetadataFilePath = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", PathFormatter.GetCacheDirectory(), galleryId, ".json");
            }

            Metadata metadata = SearchResultCache.Find(galleryId) ?? JsonUtility.LoadFromFile <Metadata>(cachedMetadataFilePath);

            if (metadata == null)
            {
                // let it download in the background, DetailsBrowserView will respond to its completion event.
                GalleryDownloader.Download(galleryId);

                return(false);
            }

            if (metadata == null)
            {
                MessageBox.Show("can't find metadata");

                return(false);
            }

            if (action != null)
            {
                action.Invoke(metadata);
            }

            return(true);
        }
Exemple #8
0
        public bool DoesPageExists(int galleryId, int pageIndex)
        {
            string cachedMetadataFilePath;

            if (PathFormatter.IsEnabled)
            {
                cachedMetadataFilePath = PathFormatter.GetMetadata(galleryId);
            }
            else
            {
                cachedMetadataFilePath = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", PathFormatter.GetCacheDirectory(), galleryId, ".json");
            }

            Metadata metadata = SearchResultCache.Find(galleryId) ?? JsonUtility.LoadFromFile <Metadata>(cachedMetadataFilePath);

            if (metadata == null ||
                pageIndex < 0 ||
                pageIndex > metadata.Images.Pages.Count - 1)
            {
                return(false);
            }

            return(WithPage(metadata, pageIndex, null));
        }
Exemple #9
0
        private SearchResult Search(bool checkSession, int lifetime, string uri, string searchQuery)
        {
            SearchResult searchResult;
            string       url         = "https://nhentai.net/api/galleries/" + uri;
            string       sessionName = uri.Replace("?", "/");

            if (SearchResultCache.Items.TryGetValue(sessionName, out searchResult))
            {
                BrowsingModel.AddSearchHistory(searchQuery);

                Logger.InfoLineFormat("Loaded SearchResult from memory cache: {0}", searchQuery);

                return(searchResult);
            }

            string cachedSearchResultsFilePath = PathFormatter.GetSession(sessionName);

            if (File.Exists(cachedSearchResultsFilePath))
            {
                if (checkSession &&
                    lifetime > 0)
                {
                    FileInfo cachedSessionFileInfo = new FileInfo(cachedSearchResultsFilePath);
                    DateTime now = DateTime.Now;

                    if ((now - cachedSessionFileInfo.CreationTime).TotalMilliseconds > lifetime)
                    {
                        File.Delete(cachedSearchResultsFilePath);
                    }
                }

                searchResult = JsonUtility.LoadFromFile <SearchResult>(cachedSearchResultsFilePath);

                if (searchResult != null)
                {
                    if (lifetime != 0)
                    {
                        SearchResultCache.Items.Add(sessionName, searchResult);
                    }

                    BrowsingModel.AddSearchHistory(searchQuery);

                    Logger.InfoLineFormat("Loaded SearchResult from file cache: {0}", searchQuery);

                    return(searchResult);
                }
            }

            Logger.InfoLineFormat("Downloading SearchResult: {0}", searchQuery);

            try
            {
                using (HttpResponseMessage response = Task.Run(() => HttpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead)).GetAwaiter().GetResult())
                {
                    if (!response.IsSuccessStatusCode)
                    {
                        Logger.ErrorLineFormat("{0} ({1})", response.ReasonPhrase, response.StatusCode);
                        response.EnsureSuccessStatusCode();
                        return(null);
                    }

                    string jsonText = Task.Run(() => response.Content.ReadAsStringAsync()).GetAwaiter().GetResult();

                    searchResult = JsonConvert.DeserializeObject <SearchResult>(jsonText);

                    if (lifetime != 0)
                    {
                        if (searchResult != null)
                        {
                            if (searchResult.Error)
                            {
                                Logger.WarnLineFormat("The server returned an error while downloading search result.");
                                throw new InvalidHttpResponseException("The server returned an error while downloading search result.");
                            }

                            Logger.LogLineFormat("File caching SearchResult: {0}", searchQuery);

                            SearchResultCache.Items.Add(sessionName, searchResult);

                            Directory.CreateDirectory(Path.GetDirectoryName(cachedSearchResultsFilePath));
                            File.WriteAllText(cachedSearchResultsFilePath, jsonText);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.ErrorLine(ex.ToString());
                throw;
            }

            BrowsingModel.AddSearchHistory(searchQuery);

            return(searchResult);
        }
Exemple #10
0
 private void ReadLibraryFilters()
 {
     Settings.Library.ToolStrip.Filters = JsonUtility.LoadFromFile <List <string> >(pathFormatter.GetConfiguration("library-filters")) ?? new List <string>();
 }
Exemple #11
0
 private void ReadSearchFilters()
 {
     Settings.Gallery.ToolStrip.Filters = JsonUtility.LoadFromFile <List <string> >(pathFormatter.GetConfiguration("search-filters")) ?? new List <string>();
 }
Exemple #12
0
 private void ReadVisitedGalleryHistory()
 {
     Settings.Details.ToolStrip.History = JsonUtility.LoadFromFile <List <int> >(pathFormatter.GetConfiguration("details-searches")) ?? new List <int>();
 }
Exemple #13
0
 private void ReadVisitedSearchHistory()
 {
     Settings.Gallery.ToolStrip.History = JsonUtility.LoadFromFile <List <string> >(pathFormatter.GetConfiguration("search-searches")) ?? new List <string>();
 }
Exemple #14
0
        private static void Main()
        {
            try
            {
                string assemblyLocation  = Assembly.GetEntryAssembly().Location;
                string assemblyDirectory = Path.GetDirectoryName(assemblyLocation).Replace('\\', '/');

                ApplicationPath = assemblyDirectory;
                SourcePath      = Directory.GetCurrentDirectory();

                Directory.SetCurrentDirectory(ApplicationPath);

                StartupSettings = JsonUtility.LoadFromFile <Configuration.StartupSettings>(assemblyDirectory + "/assets/defaults/startup.json") ?? new Configuration.StartupSettings();

                if (string.IsNullOrEmpty(StartupSettings.SettingsPath))
                {
                    StartupSettings.SettingsPath = "{SpecialFolder.MyDocuments}/NHxD/user/";
                }

                {
                    PathFormatter pathFormatter = new PathFormatter(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), Directory.GetCurrentDirectory(), null, null, null, false);

                    Settings = new Configuration.Settings();
                    JsonUtility.PopulateFromFile(pathFormatter.GetPath(StartupSettings.SettingsPath + "/settings.json"), Settings);

                    // always override settings paths.
                    if (Settings.PathFormatter != null)
                    {
                        Settings.PathFormatter.Custom["DefaultSettingsPath"] = StartupSettings.DefaultSettingsPath;
                        Settings.PathFormatter.Custom["SettingsPath"]        = StartupSettings.SettingsPath;
                    }
                }

                string    currentProcessName = Process.GetCurrentProcess().ProcessName;
                Process[] activeProcesses    = Process.GetProcessesByName(currentProcessName);

                if (!Settings.Process.AllowMultipleInstances &&
                    activeProcesses.Length > 1)
                {
                    IntPtr hWnd = IntPtr.Zero;

                    hWnd = activeProcesses[0].MainWindowHandle;
                    User32.NativeMethods.ShowWindowAsync(new HandleRef(null, hWnd), User32.NativeMethods.SW_RESTORE);
                    User32.NativeMethods.SetForegroundWindow(activeProcesses[0].MainWindowHandle);

                    return;
                }

                InstanceIndex = activeProcesses.Length - 1;

                if (Settings.Eula.CheckLegalAge)
                {
                    DialogResult dialogResult = MessageBox.Show("If you are under the age of 18 years, or under the age of majority in the location from where you are launching this program, you do not have authorization or permission to use this program or access any of its materials.\r\n\r\nBy clicking on the \"Yes\" button, you agree and certify under penalty of perjury that you are an adult.", "End-User License Agreement", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

                    if (dialogResult != DialogResult.Yes)
                    {
                        return;
                    }

                    Settings.Eula.CheckLegalAge = false;
                }

                if (Settings.Eula.PleadArtistSupport)
                {
                    MessageBox.Show("If you find something you really like, please consider buying a copy to support the artist!", "NHxD", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    Settings.Eula.PleadArtistSupport = false;
                }

                if (Settings.Log.Filters != LogFilters.None)
                {
                    PathFormatter PathFormatter = new PathFormatter(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), Directory.GetCurrentDirectory(), Settings.PathFormatter.Custom, Settings.PathFormatter, Settings.Lists.Tags.LanguageNames, Settings.PathFormatter.IsEnabled);
                    string        logPath       = Settings.Log.KeepSeparateLogs ? PathFormatter.GetLog(DateTime.Now) : PathFormatter.GetLog();

                    if (Settings.Log.Overwrite &&
                        File.Exists(logPath))
                    {
                        File.WriteAllText(logPath, "");
                    }

                    Logger = new Logger(logPath, Settings.Log.Filters);

                    FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location);

                    Logger.WriteSeparator('=');
                    Logger.WriteLineFormat("{0} version {1}", fileVersionInfo.ProductName, fileVersionInfo.FileVersion);
                    Logger.WriteLine(DateTime.Now.ToString(CultureInfo.InvariantCulture));
                    Logger.WriteSeparator('=');
                }
                else
                {
                    Logger = new Logger();
                }

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new MainForm());
            }
            catch (Exception ex)
            {
#if DEBUG
                if (MessageBox.Show("Debug?" + Environment.NewLine + Environment.NewLine + ex.ToString(), "Un unhandled exception occured.", MessageBoxButtons.YesNo, MessageBoxIcon.Error) == DialogResult.Yes)
                {
                    throw;
                }
#else
                MessageBox.Show(ex.ToString(), "Un unhandled exception occured.", MessageBoxButtons.OK, MessageBoxIcon.Error);
#endif
            }
        }
Exemple #15
0
        private static void DownloadPagesBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker    backgroundWorker = sender as BackgroundWorker;
            DownloadPagesRunArg runArg           = e.Argument as DownloadPagesRunArg;
            Metadata            metadata         = runArg.SearchResultCache.Find(runArg.Id);

            if (metadata == null)
            {
                string metadataFilePath;

                if (runArg.PathFormatter.IsEnabled)
                {
                    metadataFilePath = runArg.PathFormatter.GetMetadata(runArg.Id);
                }
                else
                {
                    // NOTE: must be an absolute path for the webbrowser to display the images correctly.
                    metadataFilePath = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", runArg.PathFormatter.GetCacheDirectory(), runArg.Id, ".json");
                }

                metadata = JsonUtility.LoadFromFile <Metadata>(metadataFilePath);

                if (metadata == null)
                {
                    // TODO? redownload it instead of aborting?

                    e.Result = runArg.Id;
                    //e.Cancel = true;
                    return;
                }
            }

            int maxCount = (runArg.PageIndices != null && runArg.PageIndices.Length > 0) ?
                           runArg.PageIndices.Count() : metadata.Images.Pages.Count;
            int loadCount = 0;

            int[] cachedPageIndices = runArg.CacheFileSystem.GetCachedPageIndices(metadata.Id);
            int   cacheCount        = cachedPageIndices.Length;

            for (int i = 0; i < metadata.Images.Pages.Count; ++i)
            {
                if (backgroundWorker.CancellationPending)
                {
                    PageDownloadCompletedArg cancelledArg = new PageDownloadCompletedArg(loadCount, maxCount, cacheCount, metadata);

                    e.Result = cancelledArg;
                    //e.Cancel = true;
                    return;
                }

                string error = "";
                string pageCachedFilePath;
                if (runArg.PathFormatter.IsEnabled)
                {
                    pageCachedFilePath = runArg.PathFormatter.GetPage(metadata, i);
                }
                else
                {
                    string paddedIndex = (i + 1).ToString(CultureInfo.InvariantCulture).PadLeft(global::NHxD.Frontend.Winforms.PathFormatter.GetBaseCount(metadata.Images.Pages.Count), '0');

                    pageCachedFilePath = string.Format(CultureInfo.InvariantCulture, "{0}{1}/{2}{3}",
                                                       runArg.PathFormatter.GetCacheDirectory(), metadata.Id, paddedIndex, metadata.Images.Pages[i].GetFileExtension()).Replace('\\', '/');
                }

                bool shouldFilter = (runArg.PageIndices != null && runArg.PageIndices.Length > 0) ?
                                    ShouldFilterPage(metadata, i, runArg.PageIndices)
                                        : false;

                if (shouldFilter)
                {
                    pageCachedFilePath = "";
                    error = "SKIP";
                }
                else
                {
                    ++loadCount;

                    if (!File.Exists(pageCachedFilePath))
                    {
                        try
                        {
                            var mediaServerId = -1;

                            {
                                var url = $"https://nhentai.net/g/{metadata.Id}/{i + 1}/";

                                Program.Logger.LogLine($"Downloading gallery webpage {url}...");

                                using (var response = Task.Run(() => runArg.HttpClient?.GetAsync(url, HttpCompletionOption.ResponseHeadersRead)).GetAwaiter().GetResult())
                                {
                                    if (!response.IsSuccessStatusCode)
                                    {
                                        Program.Logger.ErrorLine($"{response.ReasonPhrase} ({response.StatusCode})");
                                        response.EnsureSuccessStatusCode();
                                    }
                                    else
                                    {
                                        var html = Task.Run(() => response.Content.ReadAsStringAsync()).GetAwaiter().GetResult();
                                        var mediaServerIdRegExp = new Regex(@"media_server:\s*(\d+),");
                                        var mediaServerIdMatch  = mediaServerIdRegExp.Match(html);

                                        if (!mediaServerIdMatch.Success)
                                        {
                                            throw new Exception("Could not find media server id.");
                                        }
                                        else
                                        {
                                            mediaServerId = int.Parse(mediaServerIdMatch.Groups[1].Value);
                                        }
                                    }
                                }
                            }

                            string uri = string.Format(CultureInfo.InvariantCulture, "https://i{3}.nhentai.net/galleries/{0}/{1}{2}", metadata.MediaId, i + 1, metadata.Images.Pages[i].GetFileExtension(), mediaServerId);

                            Program.Logger.LogLine($"Downloading gallery page {uri}...");

                            using (HttpResponseMessage response = Task.Run(() => runArg.HttpClient?.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead)).GetAwaiter().GetResult())
                            {
                                if (!response.IsSuccessStatusCode)
                                {
                                    Program.Logger.ErrorLine($"{response.ReasonPhrase} ({response.StatusCode})");
                                    response.EnsureSuccessStatusCode();
                                }
                                else
                                {
                                    byte[] imageData = Task.Run(() => response.Content.ReadAsByteArrayAsync()).GetAwaiter().GetResult();

                                    // TODO: the issue is that I have designed things to be immutable so metadatas can't change.
                                    // but even if I do change the metadata and replace it in the searchResult,
                                    // it won't affect other cached searchResults with the same metadata. (because searchresults embed metadatas directly instead of storing indices to them)
                                    // so I might be able to save the changes to the metadata (file), one searchResult, but not everything (without greatly impacting performances)

                                    /*
                                     * //if (runArg.FixFileExtension)
                                     * {
                                     *      ImageType pageImageType = metadata.Images.Pages[i].Type;
                                     *      ImageType? realPageImageType = null;
                                     *
                                     *      if (imageData.Length >= 8
                                     *              && imageData.Match(0, 8, PngFileSignature))
                                     *      {
                                     *              realPageImageType = ImageType.Png;
                                     *      }
                                     *      else if (imageData.Length >= 8
                                     *              && imageData.Match(0, 2, JfifStartOfImageSegmentHeader)
                                     *              && imageData.Match(2, 2, JfifStartOfImageSegmentHeader)
                                     *              && imageData.Match(6, 5, JfifApp0SegmentSegmentIdentifier))
                                     *      {
                                     *              realPageImageType = ImageType.Jpeg;
                                     *      }
                                     *      else if (imageData.Length >= 8
                                     *              && imageData.Match(0, 8, GifFileSignature))
                                     *      {
                                     *              realPageImageType = ImageType.Gif;
                                     *      }
                                     *      else
                                     *      {
                                     *              // unknown format.
                                     *      }
                                     *
                                     *      if (pageImageType != realPageImageType)
                                     *      {
                                     *
                                     *      }
                                     * }
                                     */
                                    Directory.CreateDirectory(Path.GetDirectoryName(pageCachedFilePath));
                                    File.WriteAllBytes(pageCachedFilePath, imageData);

                                    ++cacheCount;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            //pageCachedFilePath = "";
                            error = ex.Message;

                            Program.Logger.ErrorLine(ex.ToString());
                        }
                    }
                }

                PageDownloadProgressArg progressArg = new PageDownloadProgressArg(loadCount, maxCount, cacheCount, i, metadata, pageCachedFilePath, 0, 0, error);

                backgroundWorker.ReportProgress((int)(loadCount / (float)maxCount * 100), progressArg);
            }

            PageDownloadCompletedArg completedArg = new PageDownloadCompletedArg(loadCount, maxCount, cacheCount, metadata);

            e.Result = completedArg;
        }
Exemple #16
0
        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;
        }
        public void ShowToolTip(TreeNode control)
        {
            if (showing)
            {
                return;
            }

            if (!associatedControls.ContainsKey(control))
            {
                if (control != null)
                {
                    //MessageBox.Show(control.Name + " has not been associated.");
                }

                HideToolTip();

                return;
            }

            showing = true;

            //Hide();

            Screen screen          = Screen.FromControl(this);
            Point  toolTipLocation = new Point(control.TreeView.Bounds.Left, control.Bounds.Location.Y);

            toolTipLocation.Offset(control.TreeView.Bounds.Width, control.Bounds.Height * 2);
            toolTipLocation.Offset(control.TreeView.Margin.Horizontal, 0);

            if (toolTipLocation.X + Size.Width > screen.WorkingArea.Width)
            {
                toolTipLocation.X -= Size.Width;
            }

            if (toolTipLocation.Y + Size.Height > screen.WorkingArea.Height)
            {
                toolTipLocation.Y -= Size.Height;
            }

            Location = toolTipLocation;

            int    associatedGalleryId = associatedControls[control];
            string cachedMetadataFileName;

            if (PathFormatter.IsEnabled)
            {
                cachedMetadataFileName = PathFormatter.GetMetadata(associatedGalleryId);
            }
            else
            {
                cachedMetadataFileName = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", PathFormatter.GetCacheDirectory(), associatedGalleryId, ".json");
            }

            Metadata metadata = JsonUtility.LoadFromFile <Metadata>(cachedMetadataFileName);

            if (metadata == null)
            {
                //Logger.LogLineFormat("{0} has no associated metadata.", associatedGalleryId);
                showing = false;
                return;
            }

            string html = GalleryTooltipTemplate.GetFormattedText(metadata);

            if (string.IsNullOrEmpty(html))
            {
                //Logger.LogLine("Failed to get template html.");
                showing = false;
                return;
            }

            webBrowser.DocumentText = html;
        }
Exemple #18
0
        public bool WithCachedPage(int galleryId, Func <int, int, int, bool> predicate, Action <string> action)
        {
            string cachedMetadataFilePath;

            if (PathFormatter.IsEnabled)
            {
                cachedMetadataFilePath = PathFormatter.GetMetadata(galleryId);
            }
            else
            {
                cachedMetadataFilePath = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", PathFormatter.GetCacheDirectory(), galleryId, ".json");
            }

            Metadata metadata = SearchResultCache.Find(galleryId) ?? JsonUtility.LoadFromFile <Metadata>(cachedMetadataFilePath);

            if (metadata == null)
            {
                return(false);
            }

            string cachedPagesPath;

            if (PathFormatter.IsEnabled)
            {
                cachedPagesPath = PathFormatter.GetPages(metadata);
            }
            else
            {
                cachedPagesPath = string.Format(CultureInfo.InvariantCulture, "{0}{1}/", PathFormatter.GetCacheDirectory(), galleryId);
            }

            if (!Directory.Exists(cachedPagesPath))
            {
                return(false);
            }

            DirectoryInfo dirInfo           = new DirectoryInfo(cachedPagesPath);
            string        firstPageFileName = null;
            int           numPages          = metadata.Images.Pages.Count;

            foreach (FileInfo fileInfo in dirInfo.EnumerateFiles())
            {
                string fileTitle = Path.GetFileNameWithoutExtension(fileInfo.Name).TrimStart(new char[] { '0' });
                int    num;

                if (int.TryParse(fileTitle, out num))
                {
                    if (predicate.Invoke(num, 1, numPages))
                    //if (num >= 1 && num <= metadata.Images.Pages.Count)
                    {
                        firstPageFileName = fileInfo.FullName;
                        break;
                    }
                }
            }

            if (string.IsNullOrEmpty(firstPageFileName))
            {
                return(false);
            }

            if (action != null)
            {
                action.Invoke(firstPageFileName);
            }

            return(true);
        }