/// <summary>
        /// Clear out ALL data and config created by the application
        /// <see cref="ResetApplication"/>
        /// </summary>
        public void ResetApplication()
        {
            try
            {
                var  warning = _deleteEverythingFactory();
                bool?result  = _windowManager.ShowDialog(warning);
                switch (result)
                {
                case null:
                    return;

                case true:
                {
                    DeleteEverything();
                    break;
                }

                default:
                    return;
                }
            }
            catch (Exception e)
            {
                App.Logger.Warning(e, "Failed to reset application");
                SentryHelper.SendException(e, null, SentryLevel.Error);
            }
        }
        /// <summary>
        /// Fill the Sexual dropdown list with available values
        /// </summary>
        private void FillSexualDropdown()
        {
            try
            {
                if (App.UserSettings.SettingsVndb != null)
                {
                    switch (App.UserSettings.MaxSexualRating)
                    {
                    case SexualRating.Safe:
                        MaxSexualIndex = (int)SexualRating.Safe;
                        break;

                    case SexualRating.Suggestive:
                        MaxSexualIndex = (int)SexualRating.Suggestive;
                        break;

                    case SexualRating.Explicit:
                        MaxSexualIndex = (int)SexualRating.Explicit;
                        break;

                    default:
                        MaxSexualIndex = 0;
                        _windowManager.ShowMessageBox(App.ResMan.GetString("UserSettingsInvalid"), App.ResMan.GetString("Error"));
                        App.Logger.Warning("UserSetting Sexual Rating is invalid");
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                App.Logger.Warning(e, "Failed to fill Sexual dropdown on Settings");
                SentryHelper.SendException(e, null, SentryLevel.Warning);
            }
        }
        /// <summary>
        /// Save the currently selected settings
        /// </summary>
        /// <param name="useEncryption"></param>
        public void SaveUserSettings(bool useEncryption)
        {
            UserSettingsVndb vndb = new UserSettingsVndb
            {
                Spoiler = (SpoilerLevel)SpoilerIndex
            };
            UserSettings settings = new UserSettings
            {
                SettingsVndb         = vndb,
                RequirePasswordEntry = useEncryption,
                MaxSexualRating      = (SexualRating)MaxSexualIndex,
                MaxViolenceRating    = (ViolenceRating)MaxViolenceIndex
            };

            try
            {
                UserSettingsHelper.SaveUserSettings(settings);
                App.UserSettings = settings;

                _windowManager.ShowMessageBox(App.ResMan.GetString("SettingsSavedMessage"), App.ResMan.GetString("SettingsSavedTitle"));
            }
            catch (Exception ex)
            {
                App.Logger.Error(ex, "Couldn't write to config file");
                SentryHelper.SendException(ex, null, SentryLevel.Error);
                throw;
            }
        }
        /// <summary>
        /// Export the Userdata and images into the .vnbak file
        /// <see cref="ExportUserData"/>
        /// </summary>
        public void ExportUserData()
        {
            try
            {
                string savePath;
                var    settings = new FolderBrowserDialogSettings();
                bool?  result   = _dialogService.ShowFolderBrowserDialog(this, settings);
                if (result == true)
                {
                    savePath = settings.SelectedPath;
                }
                else
                {
                    return;
                }


                var fileName  = $@"{savePath}\VnManager_Export_{DateTime.UtcNow:yyyy-MMMM-dd}.vnbak";
                var didCreate = ImportExportHelper.Compact(fileName);
                if (didCreate)
                {
                    _windowManager.ShowMessageBox($"{App.ResMan.GetString("UserDataExportedPath")}\n{fileName}", $"{App.ResMan.GetString("UserDataExportedTitle")}");
                }
            }
            catch (Exception e)
            {
                App.Logger.Warning(e, "Failed to export userData");
                SentryHelper.SendException(e, null, SentryLevel.Error);
            }
        }
        /// <summary>
        /// Check how many games there are, and display the correct view accourdingly
        /// </summary>
        /// <param name="gameGrid"></param>
        /// <param name="noGames"></param>
        private void CheckGames(Func <GameGridViewModel> gameGrid, Func <NoGamesViewModel> noGames)
        {
            try
            {
                var cred = CredentialManager.GetCredentials(App.CredDb);
                if (cred == null || cred.UserName.Length < 1)
                {
                    return;
                }

                int gameCount;
                using (var db = new LiteDatabase($"{App.GetDbStringWithoutPass}'{cred.Password}'"))
                {
                    gameCount = db.GetCollection <UserDataGames>(DbUserData.UserData_Games.ToString()).Count();
                }

                if (gameCount < 1)
                {
                    ActivateItem(noGames());
                }
                else
                {
                    ActivateItem(gameGrid());
                }
            }
            catch (Exception e)
            {
                App.Logger.Warning(e, "Failed to check games for GameGrid");
                SentryHelper.SendException(e, null, SentryLevel.Warning);
            }
        }
        /// <summary>
        /// Fill the Spoiler dropdown list with available values
        /// </summary>
        private void FillSpoilerDropdown()
        {
            try
            {
                if (App.UserSettings.SettingsVndb != null)
                {
                    switch (App.UserSettings.SettingsVndb.Spoiler)
                    {
                    case SpoilerLevel.None:
                        SpoilerIndex = (int)SpoilerLevel.None;
                        break;

                    case SpoilerLevel.Minor:
                        SpoilerIndex = (int)SpoilerLevel.Minor;
                        break;

                    case SpoilerLevel.Major:
                        SpoilerIndex = (int)SpoilerLevel.Major;
                        break;

                    default:
                        SpoilerIndex = 0;
                        _windowManager.ShowMessageBox(App.ResMan.GetString("UserSettingsInvalid"), App.ResMan.GetString("Error"));
                        App.Logger.Warning("UserSetting Spoiler Level is invalid");
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                App.Logger.Warning(e, "Failed to fill Spoiler dropdown on Settings");
                SentryHelper.SendException(e, null, SentryLevel.Warning);
            }
        }
Exemple #7
0
 /// <summary>
 /// Download Vndb cover image
 /// </summary>
 /// <param name="vnId"></param>
 /// <returns></returns>
 internal static async Task DownloadCoverImageAsync(uint vnId)
 {
     try
     {
         RootViewModel.StatusBarPage.InfoText = App.ResMan.GetString("DownCoverImage");
         var cred = CredentialManager.GetCredentials(App.CredDb);
         if (cred == null || cred.UserName.Length < 1)
         {
             return;
         }
         using var db = new LiteDatabase($"{App.GetDbStringWithoutPass}'{cred.Password}'");
         VnInfo entry = db.GetCollection <VnInfo>(DbVnInfo.VnInfo.ToString()).Query().Where(x => x.VnId == vnId).FirstOrDefault();
         if (entry == null)
         {
             return;
         }
         if (entry.ImageLink != null)
         {
             var uri = new Uri(entry.ImageLink);
             RootViewModel.StatusBarPage.IsFileDownloading = true;
             string path = $@"{App.AssetDirPath}\sources\vndb\images\cover\{entry.VnId}.jpg";
             await ImageHelper.DownloadImageAsync(uri, NsfwHelper.RawRatingIsNsfw(entry.ImageRating), path);
         }
     }
     catch (Exception ex)
     {
         App.Logger.Warning(ex, "Failed to download cover image");
         SentryHelper.SendException(ex, null, SentryLevel.Error);
     }
     finally
     {
         RootViewModel.StatusBarPage.IsFileDownloading = false;
         RootViewModel.StatusBarPage.InfoText          = string.Empty;
     }
 }
Exemple #8
0
 /// <summary>
 /// Checks if maximum categories has been reached
 /// </summary>
 /// <param name="input"></param>
 /// <returns></returns>
 private bool IsNotMaxCategoriesCount(string input)
 {
     try
     {
         if (input == null || input == AllCategory)
         {
             return(false);
         }
         var cred = CredentialManager.GetCredentials(App.CredDb);
         if (cred == null || cred.UserName.Length < 1)
         {
             return(false);
         }
         using var db = new LiteDatabase($"{App.GetDbStringWithoutPass}'{cred.Password}'");
         var userCategories = db.GetCollection <UserDataCategories>(DbUserData.UserData_Categories.ToString()).Query()
                              .ToArray();
         if (userCategories != null && userCategories.Length <= MaxCategories)
         {
             return(true);
         }
         else
         {
             return(false);
         }
     }
     catch (Exception e)
     {
         App.Logger.Warning(e, "Failed to check if max categories has been reached");
         SentryHelper.SendException(e, null, SentryLevel.Warning);
         return(false);
     }
 }
Exemple #9
0
        /// <summary>
        /// Create new category
        /// <see cref="CreateNewCategory"/>
        /// </summary>
        /// <returns></returns>
        public async Task CreateNewCategory()
        {
            try
            {
                bool result = await ValidateAsync();

                if (result)
                {
                    var cred = CredentialManager.GetCredentials(App.CredDb);
                    if (cred == null || cred.UserName.Length < 1)
                    {
                        return;
                    }
                    using (var db = new LiteDatabase($"{App.GetDbStringWithoutPass}'{cred.Password}'"))
                    {
                        var dbUserCategories = db.GetCollection <UserDataCategories>(DbUserData.UserData_Categories.ToString());
                        var newCategory      = new UserDataCategories {
                            CategoryName = NewCategoryValue
                        };
                        dbUserCategories.Insert(newCategory);
                    }
                    _windowManager.ShowMessageBox($"{App.ResMan.GetString("CreatedCategory")} {NewCategoryValue}", App.ResMan.GetString("CreatedCategory"));
                    _events.PublishOnUIThread(new UpdateEvent {
                        ShouldUpdate = true
                    }, EventChannels.RefreshCategoryList.ToString());
                    FillCategories();
                    NewCategoryValue = string.Empty;
                }
            }
            catch (Exception e)
            {
                App.Logger.Warning(e, "Failed to create new category");
                SentryHelper.SendException(e, null, SentryLevel.Error);
            }
        }
        /// <summary>
        /// Fill the Violence dropdown list with available values
        /// </summary>
        private void FillViolenceDropdown()
        {
            try
            {
                if (App.UserSettings.SettingsVndb != null)
                {
                    switch (App.UserSettings.MaxViolenceRating)
                    {
                    case ViolenceRating.Tame:
                        MaxViolenceIndex = (int)ViolenceRating.Tame;
                        break;

                    case ViolenceRating.Violent:
                        MaxViolenceIndex = (int)ViolenceRating.Violent;
                        break;

                    case ViolenceRating.Brutal:
                        MaxViolenceIndex = (int)ViolenceRating.Brutal;
                        break;

                    default:
                        MaxViolenceIndex = 0;
                        _windowManager.ShowMessageBox(App.ResMan.GetString("UserSettingsInvalid"), App.ResMan.GetString("Error"));
                        App.Logger.Warning("UserSetting Violence Rating is invalid");
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                App.Logger.Warning(e, "Failed to fill Violence dropdown on Settings");
                SentryHelper.SendException(e, null, SentryLevel.Warning);
            }
        }
Exemple #11
0
        /// <summary>
        /// Delete the specified category
        /// <see cref="SaveRemoveCategory"/>
        /// </summary>
        public void SaveRemoveCategory()
        {
            try
            {
                var cred = CredentialManager.GetCredentials(App.CredDb);
                if (cred == null || cred.UserName.Length < 1)
                {
                    return;
                }
                using (var db = new LiteDatabase($"{App.GetDbStringWithoutPass}'{cred.Password}'"))
                {
                    var dbUserData = db.GetCollection <UserDataGames>(DbUserData.UserData_Games.ToString());
                    var entry      = SelectedGame;
                    if (entry.Categories.Count > 0)
                    {
                        SelectedGame.Categories.Remove(SelectedRemoveValue);
                        SelectedGame.Categories = new Collection <string>(SelectedGame.Categories
                                                                          .Where(s => !string.IsNullOrWhiteSpace(s)).Distinct().ToList());
                    }

                    dbUserData.Update(SelectedGame);
                }
                FillCategories();
            }
            catch (Exception e)
            {
                App.Logger.Warning(e, "Failed to remove category");
                SentryHelper.SendException(e, null, SentryLevel.Error);
            }
        }
        /// <summary>
        /// Get Vndb GameCards
        /// </summary>
        /// <param name="userDataArray"></param>
        /// <param name="vndbInfo"></param>
        private void GetVndbData(UserDataGames[] userDataArray, VnInfo[] vndbInfo)
        {
            try
            {
                foreach (var entry in userDataArray)
                {
                    var game = vndbInfo.FirstOrDefault(x => x.VnId == entry.GameId);
                    if (game == null)
                    {
                        continue;
                    }
                    var coverPath = $@"{App.AssetDirPath}\sources\vndb\images\cover\{game.VnId}.jpg";

                    var rating = NsfwHelper.RawRatingIsNsfw(game.ImageRating);

                    var card = _gameCard();
                    card.UserDataId = entry.Id;
                    card.ShouldDisplayNsfwContent = !NsfwHelper.UserIsNsfw(game.ImageRating);
                    card.Title            = !string.IsNullOrEmpty(entry.CustomGameName) ? entry.CustomGameName : game.Title;
                    card.LastPlayedString = $"Last Played: {TimeDateChanger.GetHumanDate(entry.LastPlayed)}";
                    card.TotalTimeString  = $"Play Time: {TimeDateChanger.GetHumanTime(entry.PlayTime)}";

                    if (rating == true && File.Exists($"{coverPath}.aes"))
                    {
                        var imgBytes  = File.ReadAllBytes($"{coverPath}.aes");
                        var imgStream = Secure.DecStreamToStream(new MemoryStream(imgBytes));
                        var imgNsfw   = ImageHelper.CreateBitmapFromStream(imgStream);
                        var bi        = new BindingImage {
                            Image = imgNsfw, IsNsfw = NsfwHelper.RawRatingIsNsfw(game.ImageRating)
                        };

                        card.CoverImage = bi;
                    }
                    else
                    {
                        if (File.Exists(coverPath))
                        {
                            var bi = new BindingImage {
                                Image = ImageHelper.CreateBitmapFromPath(coverPath), IsNsfw = false
                            };
                            card.CoverImage = bi;
                        }
                        else
                        {
                            var bi = new BindingImage {
                                Image = ImageHelper.CreateEmptyBitmapImage(), IsNsfw = false
                            };
                            card.CoverImage = bi;
                        }
                    }
                    _gameCollection.Add(card);
                }
            }
            catch (Exception e)
            {
                App.Logger.Warning(e, "Failed to create Vndb GameCards");
                SentryHelper.SendException(e, null, SentryLevel.Warning);
            }
        }
Exemple #13
0
        private void MainOrChildProcessExited(object sender, EventArgs e)
        {
            try
            {
                var parent  = (VndbContentViewModel)Parent;
                var process = (Process)sender;
                if (process == null)
                {
                    return;
                }
                var children = process.GetChildProcesses().ToArray();
                if (children.Length > 0)
                {
                    foreach (var childProcess in children)
                    {
                        childProcess.EnableRaisingEvents = true;
                        childProcess.Exited += MainOrChildProcessExited;
                    }
                    parent.ProcessList.AddRange(children);

                    parent.ProcessList = parent.ProcessList.Where(x => x.HasExited == false).ToList();
                }
                else
                {
                    parent.GameStopwatch.Stop();
                    var cred = CredentialManager.GetCredentials(App.CredDb);
                    if (cred == null || cred.UserName.Length < 1)
                    {
                        return;
                    }

                    using (var db = new LiteDatabase($"{App.GetDbStringWithoutPass}'{cred.Password}'"))
                    {
                        var dbUserData = db.GetCollection <UserDataGames>(DbUserData.UserData_Games.ToString());

                        SentrySdk.AddBreadcrumb($"MainChildExited{dbUserData.FindAll().Count()}, VnId:{VndbContentViewModel.SelectedGame.Id}");
                        var gameEntry = dbUserData.Query().Where(x => x.Id == VndbContentViewModel.SelectedGame.Id).FirstOrDefault();
                        gameEntry.LastPlayed = DateTime.UtcNow;
                        gameEntry.PlayTime   = gameEntry.PlayTime + parent.GameStopwatch.Elapsed;
                        LastPlayed           = $"{App.ResMan.GetString("LastPlayed")}: {TimeDateChanger.GetHumanDate(gameEntry.LastPlayed)}";
                        PlayTime             = $"{App.ResMan.GetString("PlayTime")}: {TimeDateChanger.GetHumanTime(gameEntry.PlayTime)}";
                        dbUserData.Update(gameEntry);
                        VndbContentViewModel.SelectedGame = gameEntry;
                    }
                    parent.GameStopwatch.Reset();
                    parent.IsGameRunning = false;
                    IsStartButtonVisible = Visibility.Visible;
                }
            }
            catch (Win32Exception ex)
            {
                App.Logger.Warning(ex, "Failed to exit the process, W32");
            }
            catch (Exception exception)
            {
                App.Logger.Warning(exception, "Failed to deal with an exited Process");
                SentryHelper.SendException(exception, null, SentryLevel.Error);
            }
        }
Exemple #14
0
        public static TagTraitBinding[] GetTags(int vnId)
        {
            try
            {
                List <VnInfoTags> tagList;
                List <VnTagData>  tagDump;

                var cred = CredentialManager.GetCredentials(App.CredDb);
                if (cred == null || cred.UserName.Length < 1)
                {
                    return(new[] { new TagTraitBinding() });
                }
                using (var db = new LiteDatabase($"{App.GetDbStringWithoutPass}'{cred.Password}'"))
                {
                    tagList = db.GetCollection <VnInfoTags>(DbVnInfo.VnInfo_Tags.ToString()).Query()
                              .Where(x => x.VnId == VndbContentViewModel.VnId).ToList();
                    tagDump = db.GetCollection <VnTagData>(DbVnDump.VnDump_TagData.ToString()).Query().ToList();

                    SentrySdk.AddBreadcrumb($"tagList: {tagList.Count}, VnId:{VndbContentViewModel.VnId}");

                    tagList = tagList.Where(t => t.Spoiler <= App.UserSettings.SettingsVndb.Spoiler).ToList();
                    tagList = tagList.OrderByDescending(x => x.Spoiler).ToList();
                }

                var tagsWithParent = GetParentTags(tagList, tagDump).ToList();
                tagsWithParent.RemoveAll(x => x.Parent.Contains(_sexualString) && App.UserSettings.MaxSexualRating < SexualRating.Explicit);

                var noSpoilerTags    = tagsWithParent.Where(x => x.Spoiler == SpoilerLevel.None).ToList();
                var minorSpoilerTags = tagsWithParent.Where(x => x.Spoiler == SpoilerLevel.Minor).ToList();
                var majorSpoilerTags = tagsWithParent.Where(x => x.Spoiler == SpoilerLevel.Major).ToList();

                var sexualTags = tagsWithParent.Where(x => x.Parent.Contains(_sexualString) && x.Spoiler < SpoilerLevel.Major).ToList();


                var tempList = (from tag in noSpoilerTags let colorText = Colors.WhiteSmoke.ToString(CultureInfo.InvariantCulture) select(tag.Parent, tag.Child, colorText)).ToList();
                tempList.AddRange(from tag in minorSpoilerTags let colorText = Colors.Gold.ToString(CultureInfo.InvariantCulture) select(tag.Parent, tag.Child, colorText));
                tempList.AddRange(from tag in majorSpoilerTags let colorText = Colors.Red.ToString(CultureInfo.InvariantCulture) select(tag.Parent, tag.Child, colorText));

                tempList = tempList.Except(tempList.Where(p => sexualTags.Any(c => c.Child == p.Child))).ToList();
                tempList.AddRange(from tag in sexualTags let colorText = Colors.HotPink.ToString(CultureInfo.InvariantCulture) select(tag.Parent, tag.Child, colorText));


                var tagBindingList = (from @group in tempList.GroupBy(x => x.Parent)
                                      let tuple = @group.Select(tag => new Tuple <string, string>(tag.Child, tag.colorText)).ToArray()
                                                  select new TagTraitBinding {
                    Parent = @group.Key, Children = tuple
                }).OrderBy(x => x.Parent).ToArray();
                return(tagBindingList);
            }
            catch (Exception e)
            {
                App.Logger.Warning(e, "GetTags failed");
                SentryHelper.SendException(e, null, SentryLevel.Warning);
                return(new TagTraitBinding[0]);
            }
        }
Exemple #15
0
        //should exit if it can't read the database
        /// <summary>
        /// Checks if the program can successfully open the database.
        /// If it encounters an error, the program will exit, as the program can't function if it can't read the database
        /// </summary>
        private void CheckDbError()
        {
            string appExit = App.ResMan.GetString("AppExit");
            string dbError = App.ResMan.GetString("DbError");

            string errorStr;

            try
            {
                var cred = CredentialManager.GetCredentials(App.CredDb);
                if (cred == null || cred.UserName.Length < 1)
                {
                    errorStr = $"{App.ResMan.GetString("PasswordNoEmpty")}\n{appExit}";
                    _windowManager.ShowMessageBox(errorStr, dbError);
                    Environment.Exit(1);
                }
                else
                {
                    using (var db = new LiteDatabase($"Filename={Path.Combine(App.ConfigDirPath, App.DbPath)};Password='******'"))
                    {
                        //do nothing. This is checking if the database can be opened
                    }
                }
            }
            catch (IOException)
            {
                errorStr = $"{App.ResMan.GetString("DbIsLockedProc")}\n{appExit}";
                _windowManager.ShowMessageBox(errorStr, dbError);
                Environment.Exit(1);
            }
            catch (LiteException ex)
            {
                if (ex.Message == "Invalid password")
                {
                    errorStr = $"{App.ResMan.GetString("PassIncorrect")}\n{appExit}";
                    _windowManager.ShowMessageBox(errorStr, dbError);
                    Environment.Exit(1);
                }
                else
                {
                    errorStr = $"{ex.Message}\n{appExit}";
                    _windowManager.ShowMessageBox(errorStr, dbError);
                    App.Logger.Error(ex, "CheckDb LiteException error");
                    SentryHelper.SendException(ex, null, SentryLevel.Error);
                    Environment.Exit(1);
                }
            }
            catch (Exception e)
            {
                errorStr = $"{App.ResMan.GetString("UnknownException")}\n{appExit}";
                _windowManager.ShowMessageBox(errorStr, dbError);
                App.Logger.Error(e, "CheckDbError failed");
                SentryHelper.SendException(e, null, SentryLevel.Error);
                Environment.Exit(1);
            }
        }
Exemple #16
0
        /// <summary>
        /// Creates a backup format for use with VnManager
        /// </summary>
        /// <param name="outputFile"></param>
        /// <returns></returns>
        public static bool Compact(string outputFile)
        {
            try
            {
                var cred = CredentialManager.GetCredentials(App.CredDb);
                if (cred == null || cred.UserName.Length < 1)
                {
                    return(false);
                }
                File.Copy(Path.Combine(App.ConfigDirPath, App.DbPath), @$ "{App.AssetDirPath}\Import.db");
                var fileName = @$ "{App.AssetDirPath}\Import.db";
                using (var db = new LiteDatabase($"Filename={fileName};Password='******'"))
                {
                    db.Rebuild(new RebuildOptions {
                        Password = App.ImportExportDbKey
                    });
                }


                var backup = new BackupFormat();
                ZipFile.CreateFromDirectory(@$ "{App.AssetDirPath}\sources", @$ "{App.AssetDirPath}\Images.zip");
                using (ZipArchive archive = ZipFile.Open(@$ "{App.AssetDirPath}\output.zip", ZipArchiveMode.Create))
                {
                    archive.CreateEntryFromFile(@$ "{App.AssetDirPath}\Images.zip", "Images.zip");
                    archive.CreateEntryFromFile(@$ "{App.AssetDirPath}\Import.db", "Import.db");
                }
                File.Delete(@$ "{App.AssetDirPath}\Images.zip");
                File.Delete(@$ "{App.AssetDirPath}\Import.db");

                byte[] originalBytes = File.ReadAllBytes(@$ "{App.AssetDirPath}\output.zip");
                File.Delete(@$ "{App.AssetDirPath}\output.zip");

                backup.ZippedData = originalBytes;

                if (File.Exists(outputFile))
                {
                    File.Delete(outputFile);
                }
                using (var fs = new FileStream(outputFile, FileMode.CreateNew, FileAccess.Write, FileShare.Write))
                {
                    using (var writer = new BinaryWriter(fs, Encoding.UTF8, true))
                    {
                        writer.Write(backup.HeaderBytes);
                        writer.Write(backup.ZippedData);
                    }
                }

                return(true);
            }
            catch (Exception e)
            {
                App.Logger.Error(e, "Failed to compact into backup");
                SentryHelper.SendException(e, null, SentryLevel.Error);
                throw;
            }
        }
Exemple #17
0
        /// <summary>
        /// Get the main Vndb data
        /// </summary>
        private void LoadMainData()
        {
            try
            {
                if (VndbContentViewModel.VnId == 0)
                {
                    return;
                }
                var cred = CredentialManager.GetCredentials(App.CredDb);
                if (cred == null || cred.UserName.Length < 1)
                {
                    return;
                }
                using (var db = new LiteDatabase($"{App.GetDbStringWithoutPass}'{cred.Password}'"))
                {
                    var vnInfoEntry = db.GetCollection <VnInfo>(DbVnInfo.VnInfo.ToString()).Query().Where(x => x.VnId == VndbContentViewModel.VnId).FirstOrDefault();
                    Title        = vnInfoEntry.Title;
                    MainTitle    = vnInfoEntry.Title;
                    Aliases      = vnInfoEntry.Aliases;
                    ReleasedDate = TimeDateChanger.GetHumanDate(DateTime.Parse(vnInfoEntry.Released, CultureInfo.InvariantCulture));
                    VnLength     = vnInfoEntry.Length;
                    Popularity   = $"{vnInfoEntry.Popularity:F}";
                    Rating       = $"{vnInfoEntry.Rating:F}";
                    LoadLanguages(ref vnInfoEntry);
                    var coverPath = $@"{App.AssetDirPath}\sources\vndb\images\cover\{vnInfoEntry.VnId}.jpg";

                    var rawRating = NsfwHelper.RawRatingIsNsfw(vnInfoEntry.ImageRating);
                    if (rawRating && File.Exists($"{coverPath}.aes"))
                    {
                        var imgBytes  = File.ReadAllBytes($"{coverPath}.aes");
                        var imgStream = Secure.DecStreamToStream(new MemoryStream(imgBytes));
                        var imgNsfw   = ImageHelper.CreateBitmapFromStream(imgStream);
                        CoverImage = imgNsfw;
                        if (NsfwHelper.UserIsNsfw(vnInfoEntry.ImageRating))
                        {
                            const int blurWeight = 10;
                            SentrySdk.AddBreadcrumb($"BlurCoverImage-{VndbContentViewModel.VnId}");
                            CoverImage = ImageHelper.BlurImage(imgNsfw, blurWeight);
                        }
                    }
                    else
                    {
                        CoverImage = File.Exists(coverPath) ? ImageHelper.CreateBitmapFromPath(coverPath) : ImageHelper.CreateEmptyBitmapImage();
                    }

                    DescriptionInLine = BBCodeHelper.Helper(vnInfoEntry.Description);
                }
            }
            catch (Exception e)
            {
                App.Logger.Warning(e, "Failed to load Main Vndb Data");
                SentryHelper.SendException(e, null, SentryLevel.Warning);
            }
        }
 /// <summary>
 /// Add a game to the database
 /// <see cref="ShowAddGameDialog"/>
 /// </summary>
 public void ShowAddGameDialog()
 {
     try
     {
         _windowManager.ShowDialog(_addGameFactory());
     }
     catch (Exception e)
     {
         App.Logger.Error(e, "Failed to show AddGameDialog");
         SentryHelper.SendException(e, null, SentryLevel.Error);
     }
 }
Exemple #19
0
        /// <summary>
        /// Loads the database, then fills the table with the UserData
        /// </summary>
        /// <param name="filePath">Path to the import database file</param>
        private void LoadDatabase(string filePath)
        {
            string dbError = App.ResMan.GetString("DbError");

            try
            {
                var didExpand = ImportExportHelper.Expand(filePath);
                if (!didExpand)
                {
                    return;
                }
                var dbPath = @$ "{App.AssetDirPath}\Import.db";
                if (!File.Exists(dbPath))
                {
                    return;
                }
                using (var db = new LiteDatabase($"Filename={dbPath};Password={App.ImportExportDbKey}"))
                {
                    IEnumerable <UserDataGames> dbUserData =
                        db.GetCollection <UserDataGames>(DbUserData.UserData_Games.ToString()).FindAll().ToArray();
                    var addList = new List <UserDataGames>();
                    foreach (var item in dbUserData)
                    {
                        var result = _validator.Validate(item);
                        foreach (var error in result.Errors)
                        {
                            item.SetError(error.PropertyName, error.ErrorMessage);
                        }

                        addList.Add(item);
                    }


                    UserDataGamesCollection.AddRange(addList);
                    File.Copy(@$ "{App.AssetDirPath}\Import.db", Path.Combine(App.ConfigDirPath, @"database\Import.db"));
                }

                DatabaseName = Path.GetFileName(filePath);
            }
            catch (IOException)
            {
                var errorStr = App.ResMan.GetString("DbIsLockedProc");
                _windowManager.ShowMessageBox(errorStr, dbError, MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }
            catch (Exception ex)
            {
                App.Logger.Warning(ex, "Failed to load database for import");
                SentryHelper.SendException(ex, null, SentryLevel.Error);
                _windowManager.ShowMessageBox($"{App.ResMan.GetString("ImportInvalidDb")}\n{Path.GetFileName(filePath)}",
                                              $"{App.ResMan.GetString("ImportInvalidDbTitle")}", MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }
        }
Exemple #20
0
        /// <summary>
        /// Delete the Vndb Data from the Db
        /// </summary>
        internal void DeleteVndbContent()
        {
            try
            {
                var cred = CredentialManager.GetCredentials(App.CredDb);
                if (cred == null || cred.UserName.Length < 1)
                {
                    return;
                }
                var vnid = SelectedGame.GameId.Value;
                using (var db = new LiteDatabase($"{App.GetDbStringWithoutPass}'{cred.Password}'"))
                {
                    var dbInfo          = db.GetCollection <VnInfo>(DbVnInfo.VnInfo.ToString());
                    var dbInfoLinks     = db.GetCollection <VnInfoLinks>(DbVnInfo.VnInfo_Links.ToString());
                    var dbInfoRelations = db.GetCollection <VnInfoRelations>(DbVnInfo.VnInfo_Relations.ToString());
                    var dbInfoScreens   = db.GetCollection <VnInfoScreens>(DbVnInfo.VnInfo_Screens.ToString());
                    var dbInfoTags      = db.GetCollection <VnInfoTags>(DbVnInfo.VnInfo_Tags.ToString());

                    var dbCharacter       = db.GetCollection <VnCharacterInfo>(DbVnCharacter.VnCharacter.ToString());
                    var dbCharacterTraits = db.GetCollection <VnCharacterTraits>(DbVnCharacter.VnCharacter_Traits.ToString());

                    var charIds = dbCharacter.Query().Where(x => x.VnId == vnid).Select(x => x.CharacterId).ToList();

                    dbInfo.DeleteMany(x => x.VnId == vnid);
                    dbInfoLinks.DeleteMany(x => x.VnId == vnid);
                    dbInfoRelations.DeleteMany(x => x.VnId == vnid);
                    dbInfoScreens.DeleteMany(x => x.VnId == vnid);
                    dbInfoTags.DeleteMany(x => x.VnId == vnid);


                    var charExclude = new List <uint>();
                    foreach (var characterInfo in dbCharacter.FindAll())
                    {
                        if (charIds.Contains(characterInfo.CharacterId) && characterInfo.VnId != vnid)
                        {
                            charExclude.Add(characterInfo.CharacterId);
                        }
                    }

                    var charDeleteIds = charIds.Except(charExclude).ToList();
                    dbCharacter.DeleteMany(x => charDeleteIds.Contains(x.CharacterId));
                    dbCharacterTraits.DeleteMany(x => charDeleteIds.Contains(x.CharacterId));
                }
                DeleteVndbImages(vnid);
            }
            catch (Exception e)
            {
                App.Logger.Error(e, "Failed to Delete Vndb Data from Db");
                SentryHelper.SendException(e, null, SentryLevel.Error);
                throw;
            }
        }
Exemple #21
0
        /// <summary>
        /// Saves info when the processes exit
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainOrChildProcessExited(object sender, EventArgs e)
        {
            try
            {
                var process = (Process)sender;
                if (process == null)
                {
                    return;
                }
                var children = process.GetChildProcesses().ToArray();
                if (children.Length > 0)
                {
                    foreach (var childProcess in children)
                    {
                        childProcess.EnableRaisingEvents = true;
                        childProcess.Exited += MainOrChildProcessExited;
                    }
                    _processList.AddRange(children);
                    _processList = _processList.Where(x => x.HasExited == false).ToList();
                }
                else
                {
                    _gameStopwatch.Stop();
                    var cred = CredentialManager.GetCredentials(App.CredDb);
                    if (cred == null || cred.UserName.Length < 1)
                    {
                        return;
                    }

                    using (var db = new LiteDatabase($"{App.GetDbStringWithoutPass}'{cred.Password}'"))
                    {
                        var dbUserData = db.GetCollection <UserDataGames>(DbUserData.UserData_Games.ToString());
                        var gameEntry  = dbUserData.Query().Where(x => x.Id == _selectedGame.Id).FirstOrDefault();
                        gameEntry.LastPlayed = DateTime.UtcNow;
                        gameEntry.PlayTime   = gameEntry.PlayTime + _gameStopwatch.Elapsed;
                        LastPlayed           = $"{App.ResMan.GetString("LastPlayed")}: {TimeDateChanger.GetHumanDate(gameEntry.LastPlayed)}";
                        PlayTime             = $"{App.ResMan.GetString("PlayTime")}: {TimeDateChanger.GetHumanTime(gameEntry.PlayTime)}";
                        dbUserData.Update(gameEntry);
                        _selectedGame = gameEntry;
                    }
                    _gameStopwatch.Reset();
                    _isGameRunning       = false;
                    IsStartButtonVisible = Visibility.Visible;
                }
            }
            catch (Exception exception)
            {
                App.Logger.Error(exception, "Failed to deal with an exited NoSource process");
                SentryHelper.SendException(exception, null, SentryLevel.Warning);
                throw;
            }
        }
Exemple #22
0
 public void NavTest()
 {
     try
     {
         CauseException();
     }
     catch (Exception e)
     {
         SentryHelper.SendException(e, "bad information", SentryLevel.Fatal);
         //Console.WriteLine(e);
         throw;
     }
 }
        /// <summary>
        /// Get the current games from UserData
        /// </summary>
        private void GetGameData()
        {
            try
            {
                List <UserDataGames> dbUserData = new List <UserDataGames>();
                List <VnInfo>        dbVnInfo   = new List <VnInfo>();
                var cred = CredentialManager.GetCredentials(App.CredDb);
                if (cred == null || cred.UserName.Length < 1)
                {
                    return;
                }
                using (var db = new LiteDatabase($"{App.GetDbStringWithoutPass}'{cred.Password}'"))
                {
                    var dbAll = db.GetCollection <UserDataGames>(DbUserData.UserData_Games.ToString()).Query().ToList();
                    GameCollection.Clear();
                    foreach (var userData in dbAll)
                    {
                        if (userData.Categories != null && (userData.Categories.Contains(CategoryListViewModel.SelectedCategory)) || CategoryListViewModel.SelectedCategory == null)
                        {
                            dbUserData.Add(userData);
                        }
                    }
                    dbVnInfo.AddRange(db.GetCollection <VnInfo>(DbVnInfo.VnInfo.ToString()).Query().ToList());
                }

                var userDataGamesEnumerable = dbUserData.ToArray();
                var vndbData     = userDataGamesEnumerable.Where(x => x.SourceType == AddGameSourceType.Vndb).ToArray();
                var noSourceData = userDataGamesEnumerable.Where(x => x.SourceType == AddGameSourceType.NoSource).ToArray();
                if (noSourceData.Length > 0)
                {
                    CreateNoSourceCards(noSourceData);
                }

                if (vndbData.Length > 0)
                {
                    GetVndbData(vndbData, dbVnInfo.ToArray());
                }

                var gameCollection = _gameCollection.OrderBy(x => x.Title);
                GameCollection.AddRange(gameCollection);
                GameCollection.Refresh();
                RootViewModel.StatusBarPage.GameCount = GameCollection.Count.ToString();
            }
            catch (Exception e)
            {
                App.Logger.Error(e, "Failed to get GameData");
                SentryHelper.SendException(e, null, SentryLevel.Error);
            }
        }
Exemple #24
0
 /// <summary>
 /// Main navigation controller for changing the main screen
 /// </summary>
 /// <param name="mainGrid"></param>
 /// <param name="vndbHost"></param>
 /// <param name="noSource"></param>
 public NavigationController(Func <MainGridViewModel> mainGrid, Func <VndbContentViewModel> vndbHost, Func <NoSourceMainViewModel> noSource)
 {
     try
     {
         this._mainGridFactory = mainGrid;
         this._vndbHostFactory = vndbHost;
         this._noSourceFactory = noSource;
     }
     catch (Exception e)
     {
         App.Logger.Error(e, "Failed to init NavigationController");
         SentryHelper.SendException(e, null, SentryLevel.Error);
         throw;
     }
 }
Exemple #25
0
        /// <summary>
        /// Get character data
        /// </summary>
        /// <param name="client"></param>
        /// <param name="vnid"></param>
        /// <param name="ro"></param>
        /// <returns></returns>
        internal async Task <List <Character> > GetCharactersAsync(VndbSharp.Vndb client, uint vnid, RequestOptions ro)
        {
            try
            {
                stopwatch.Restart();

                int              pageCount      = 1;
                bool             shouldContinue = true;
                List <Character> characterList  = new List <Character>();
                while (shouldContinue)
                {
                    ro.Page = pageCount;
                    VndbResponse <Character> characters = await client.GetCharacterAsync(VndbFilters.VisualNovel.Equals(vnid), VndbFlags.FullCharacter, ro);

                    switch (characters)
                    {
                    case null when client.GetLastError().Type == ErrorType.Throttled:
                        await HandleVndbErrors.ThrottledWaitAsync((ThrottledError)client.GetLastError(), 0);

                        break;

                    case null:
                        HandleVndbErrors.HandleErrors(client.GetLastError());
                        _didErrorOccur = true;
                        return(null);

                    default:
                    {
                        shouldContinue = characters.HasMore;     //When false, it will exit the while loop
                        characterList.AddRange(characters.Items);
                        pageCount++;
                        if (stopwatch.Elapsed > maxTime)
                        {
                            return(null);
                        }
                        break;
                    }
                    }
                }
                return(characterList);
            }
            catch (Exception e)
            {
                App.Logger.Warning(e, "Failed to Get Visual novel characters");
                SentryHelper.SendException(e, null, SentryLevel.Warning);
                return(null);
            }
        }
Exemple #26
0
        /// <summary>
        /// Delete specified category
        /// <see cref="DeleteCategory"/>
        /// </summary>
        public void DeleteCategory()
        {
            try
            {
                var result = _windowManager.ShowMessageBox($"{App.ResMan.GetString("ConfirmDeleteCategoryMsg")} {NewCategoryValue}",
                                                           App.ResMan.GetString("ConfirmDeleteCategory"), MessageBoxButton.YesNo);
                if (result == MessageBoxResult.No)
                {
                    return;
                }
                var cred = CredentialManager.GetCredentials(App.CredDb);
                if (cred == null || cred.UserName.Length < 1)
                {
                    return;
                }
                using (var db = new LiteDatabase($"{App.GetDbStringWithoutPass}'{cred.Password}'"))
                {
                    var dbUserCategories = db.GetCollection <UserDataCategories>(DbUserData.UserData_Categories.ToString());
                    var dbUserData       = db.GetCollection <UserDataGames>(DbUserData.UserData_Games.ToString());
                    List <UserDataGames> newGamesList = new List <UserDataGames>();
                    foreach (var userData in dbUserData.Query().ToArray())
                    {
                        if (userData.Categories != null && userData.Categories.Count > 1 && DeleteCategorySelectedValue != "All")
                        {
                            userData.Categories = new Collection <string>(userData.Categories.Where(x => x != DeleteCategorySelectedValue).ToList());
                            newGamesList.Add(userData);
                        }
                    }

                    foreach (var newGame in newGamesList)
                    {
                        dbUserData.Update(newGame);
                    }
                    dbUserCategories.DeleteMany(c => c.CategoryName == DeleteCategorySelectedValue);
                }

                _events.PublishOnUIThread(new UpdateEvent {
                    ShouldUpdate = true
                }, EventChannels.RefreshCategoryList.ToString());
                FillCategories();
            }
            catch (Exception e)
            {
                App.Logger.Warning(e, "Failed to delete category");
                SentryHelper.SendException(e, null, SentryLevel.Error);
            }
        }
Exemple #27
0
 /// <summary>
 /// Load the main NoSource data
 /// </summary>
 private void LoadMainData()
 {
     try
     {
         Title      = _selectedGame.Title;
         GameIcon   = ImageHelper.CreateIcon(!string.IsNullOrEmpty(_selectedGame.IconPath) ? _selectedGame.IconPath : _selectedGame.ExePath);
         LastPlayed = TimeDateChanger.GetHumanDate(_selectedGame.LastPlayed);
         PlayTime   = TimeDateChanger.GetHumanTime(_selectedGame.PlayTime);
         var coverName = $"{Path.Combine(App.AssetDirPath, @"sources\noSource\images\cover\")}{_selectedGame.Id}.png";
         CoverImage           = File.Exists(coverName) ? ImageHelper.CreateBitmapFromPath(coverName) : ImageHelper.CreateEmptyBitmapImage();
         IsStartButtonVisible = Visibility.Visible;
     }
     catch (Exception e)
     {
         App.Logger.Warning(e, "Failed to load NoSource MainData");
         SentryHelper.SendException(e, null, SentryLevel.Error);
     }
 }
Exemple #28
0
 /// <summary>
 /// Get wikipedia link from WikiData ID
 /// </summary>
 /// <param name="wikiDataId"></param>
 /// <returns></returns>
 private static string GetWikipediaLink(string wikiDataId)
 {
     try
     {
         var xmlResult = new WebClient().
                         DownloadString(@$ "https://www.wikidata.org/w/api.php?action=wbgetentities&format=xml&props=sitelinks&ids={wikiDataId}&sitefilter=enwiki");
         XmlSerializer serializer   = new XmlSerializer(typeof(WikiDataApi), new XmlRootAttribute("api"));
         StringReader  stringReader = new StringReader(xmlResult);
         var           xmlData      = (WikiDataApi)serializer.Deserialize(stringReader);
         var           wikiTitle    = xmlData.WdEntities?.WdEntity?.WdSitelinks?.WdSitelink?.Title;
         return(wikiTitle);
     }
     catch (Exception e)
     {
         App.Logger.Warning(e, "Failed to get wikipedia link");
         SentryHelper.SendException(e, null, SentryLevel.Warning);
         return(string.Empty);
     }
 }
        public static IEnumerable <Process> GetChildProcesses(this Process process)
        {
            try
            {
                if (process == null)
                {
                    return(new List <Process>());
                }
                ManagementObjectSearcher mos = new ManagementObjectSearcher($"Select * From Win32_Process Where ParentProcessID={process.Id}");

                var childList = (from ManagementObject mo in mos.Get() select Process.GetProcessById(Convert.ToInt32(mo["ProcessID"]))).ToList();
                return(childList);
            }
            catch (Exception ex)
            {
                App.Logger.Warning(ex, "Failed to get child processes");
                SentryHelper.SendException(ex, null, SentryLevel.Error);
                throw;
            }
        }
Exemple #30
0
        private void CheckForUpdates()
        {
            try
            {
                var  updateCheck     = new GithubUpdateCheck("micah686", "VnManager");
                bool updateAvailable = updateCheck.IsUpdateAvailable(App.VersionString, VersionChange.Build);
                if (updateAvailable == false)
                {
                    return;
                }
                var result = _windowManager.ShowMessageBox(App.ResMan.GetString("UpdateMsg"), App.ResMan.GetString("UpdateAvailable"), MessageBoxButton.YesNo);
                if (result == MessageBoxResult.Yes)
                {
                    const int twoMegaBytes = 2000000;
                    var       releasePath  = new Uri(@"https://github.com/micah686/VnManager/releases/latest/download/VnManagerInstaller.exe");
                    var       tempFolder   = Path.GetTempPath();
                    var       filePath     = $@"{tempFolder}VnManager-{Guid.NewGuid()}.exe";
                    using (var client = new WebClient())
                    {
                        client.DownloadFile(releasePath, filePath);
                    }

                    var totalBytes = new FileInfo(filePath).Length;
                    if (totalBytes > twoMegaBytes)
                    {
                        var ps = new ProcessStartInfo(filePath)
                        {
                            UseShellExecute = true,
                            Verb            = "open"
                        };
                        Process.Start(ps);
                        Environment.Exit(0);
                    }
                }
            }
            catch (Exception e)
            {
                App.Logger.Warning(e, "Failed to check for Updates");
                SentryHelper.SendException(e, null, SentryLevel.Warning);
            }
        }