Пример #1
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));
        }
Пример #2
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));
        }
Пример #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);
        }
Пример #4
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);
        }
Пример #5
0
        public void CreateMetadataEmbed(IMetadataConverter metadataConverter, Metadata metadata)
        {
            string result;

            if (metadataConverter.Write(metadata, out result))
            {
                string filePath;
                if (PathFormatter.IsEnabled)
                {
                    filePath = PathFormatter.GetConvertedMetadata(metadata, metadataConverter);
                }
                else
                {
                    filePath = string.Format(CultureInfo.InvariantCulture, "{0}{1}/{2}", PathFormatter.GetCacheDirectory(), metadata.Id, metadataConverter.FileName);
                }

                try
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(filePath));
                    File.WriteAllText(filePath, result);
                }
                catch (Exception ex)
                {
                    Logger.ErrorLineFormat("Failed to write metadata embed: {0}", filePath);
                    Logger.ErrorLineFormat(ex.ToString());
                }
            }
        }
Пример #6
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);
        }
Пример #7
0
 public string GetSessionFileName(string query, int pageIndex)
 {
     return(PathFormatter.GetSession(GetSessionQuery(query, pageIndex)));
 }
Пример #8
0
        private static void Main()
        {
            try
            {
                string    currentProcessName = Process.GetCurrentProcess().ProcessName;
                Process[] activeProcesses    = Process.GetProcessesByName(currentProcessName);

                if (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;
                }

                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;
                    }
                }

                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.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
            }
        }
Пример #9
0
 public void DeleteExpiredSessions()
 {
     DeleteExpiredSessions(RecentSearchLifeSpan, PathFormatter.GetSessionDirectory("all"));
     DeleteExpiredSessions(QuerySearchLifeSpan, PathFormatter.GetSessionDirectory("search"));
     DeleteExpiredSessions(TaggedSearchLifeSpan, PathFormatter.GetSessionDirectory("tagged"));
 }
Пример #10
0
 public string GetSessionFileName(int tagId, int pageIndex)
 {
     return(PathFormatter.GetSession(GetSessionQuery(tagId, pageIndex)));
 }
Пример #11
0
        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;
        }
Пример #12
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);
        }
Пример #13
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 &&
                    !NetworkSettings.Offline)
                {
                    FileInfo cachedSessionFileInfo = new FileInfo(cachedSearchResultsFilePath);
                    DateTime now = DateTime.Now;

                    if ((now - cachedSessionFileInfo.CreationTime).TotalMilliseconds > lifetime)
                    {
                        //SessionManager.DeleteSession(cachedSearchResultsFilePath);
                        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);
                }
            }
            else
            {
                if (NetworkSettings.Offline)
                {
                    throw new InvalidHttpResponseException("This page does not exist in the cache and is thus unavailable while in offline mode.");
                }
            }

            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);
        }
Пример #14
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());
        }
Пример #15
0
        public bool WithCover(Metadata metadata, Action <string> action)
        {
            string cachedCoverFilePath;

            if (PathFormatter.IsEnabled)
            {
                cachedCoverFilePath = PathFormatter.GetCover(metadata);
            }
            else
            {
                cachedCoverFilePath = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", PathFormatter.GetCacheDirectory(), metadata.Id, metadata.Images.Cover.GetFileExtension());
            }

            if (!File.Exists(cachedCoverFilePath))
            {
                return(false);
            }

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

            return(true);
        }
Пример #16
0
        public bool WithMetadata(int galleryId, 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");
            }

            if (!File.Exists(cachedMetadataFilePath))
            {
                return(false);
            }

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

            return(true);
        }
Пример #17
0
        public bool WithPage(Metadata metadata, int pageIndex, Action <string> action)
        {
            if (metadata == null ||
                pageIndex < 0 ||
                pageIndex > metadata.Images.Pages.Count - 1)
            {
                return(false);
            }

            string pageCachedFilePath;

            if (PathFormatter.IsEnabled)
            {
                pageCachedFilePath = PathFormatter.GetPage(metadata, pageIndex);
            }
            else
            {
                string paddedIndex = (pageIndex + 1).ToString(CultureInfo.InvariantCulture).PadLeft(GetBaseCount(metadata.Images.Pages.Count), '0');

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

            if (!File.Exists(pageCachedFilePath))
            {
                return(false);
            }

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

            return(true);
        }
Пример #18
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;
        }
Пример #19
0
        public void CreateArchive(IArchiveWriter archiveWriter, Metadata metadata, string pagesPath)
        {
            string archiveFilePath;

            if (PathFormatter.IsEnabled)
            {
                archiveFilePath = PathFormatter.GetArchive(metadata, archiveWriter);
            }
            else
            {
                archiveFilePath = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", PathFormatter.GetCacheDirectory(), metadata.Id, archiveWriter.FileExtension);
            }

            if (Directory.Exists(pagesPath))
            {
                archiveWriter.CreateFromDirectory(pagesPath, archiveFilePath);
            }
            else
            {
                archiveWriter.CreateEmpty(archiveFilePath);
            }
        }