Esempio n. 1
0
        public void DeleteGameImageCleanupTest()
        {
            var path = Path.Combine(Playnite.PlayniteTests.TempPath, "deleteimagecleanuptest.db");

            FileSystem.DeleteFile(path);

            var db = new GameDatabase(null);

            using (db.OpenDatabase(path))
            {
                db.AddFile("testimage", "testimage.png", new byte[] { 0 });
                db.AddFile("testicon", "testicon.png", new byte[] { 0 });
                Assert.AreEqual(2, db.Database.FileStorage.FindAll().Count());

                var game = new Game()
                {
                    ProviderId = "testid",
                    Name       = "Test Game",
                    Icon       = "testicon",
                    Image      = "testimage"
                };

                db.AddGame(game);
                db.DeleteGame(game);

                Assert.AreEqual(0, db.Database.FileStorage.FindAll().Count());
            }
        }
Esempio n. 2
0
        public void MultiAddtionTest()
        {
            var image = Path.Combine(Paths.ProgramFolder, "Resources", "Images", "applogo.png");
            var db    = new GameDatabase(null);

            using (db.OpenDatabase(new MemoryStream()))
            {
                db.AddFile("test.png", "test.png", File.ReadAllBytes(image));
                var id = db.AddFileNoDuplicate("test2.png", "test2.png", File.ReadAllBytes(image));
                Assert.AreEqual("test.png", id);
                Assert.AreEqual(1, db.Database.FileStorage.FindAll().Count());
            }

            db = new GameDatabase(null);
            using (db.OpenDatabase(new MemoryStream()))
            {
                db.AddFileNoDuplicate("test.png", "test.png", File.ReadAllBytes(image));
                var id = db.AddFileNoDuplicate("test2.png", "test2.png", File.ReadAllBytes(image));
                Assert.AreEqual("test.png", id);
                Assert.AreEqual(1, db.Database.FileStorage.FindAll().Count());
            }

            db = new GameDatabase(null);
            using (db.OpenDatabase(new MemoryStream()))
            {
                db.AddFileNoDuplicate("test.png", "test.png", File.ReadAllBytes(image));
                db.AddFile("test2.png", "test2.png", File.ReadAllBytes(image));
                Assert.AreEqual(2, db.Database.FileStorage.FindAll().Count());
            }
        }
Esempio n. 3
0
        public void MultiAddtionTest()
        {
            var image = Path.Combine(Paths.ProgramFolder, "Resources", "Images", "applogo.png");
            var path  = Path.Combine(Playnite.PlayniteTests.TempPath, "filemulti.db");

            FileSystem.DeleteFile(path);
            var db = new GameDatabase(null);

            using (db.OpenDatabase(path))
            {
                db.AddFile("test.png", "test.png", File.ReadAllBytes(image));
                var id = db.AddFileNoDuplicate("test2.png", "test2.png", File.ReadAllBytes(image));
                Assert.AreEqual("test.png", id);
                Assert.AreEqual(1, db.Database.FileStorage.FindAll().Count());
            }

            FileSystem.DeleteFile(path);
            db = new GameDatabase(null);
            using (db.OpenDatabase(path))
            {
                db.AddFileNoDuplicate("test.png", "test.png", File.ReadAllBytes(image));
                var id = db.AddFileNoDuplicate("test2.png", "test2.png", File.ReadAllBytes(image));
                Assert.AreEqual("test.png", id);
                Assert.AreEqual(1, db.Database.FileStorage.FindAll().Count());
            }

            FileSystem.DeleteFile(path);
            db = new GameDatabase(null);
            using (db.OpenDatabase(path))
            {
                db.AddFileNoDuplicate("test.png", "test.png", File.ReadAllBytes(image));
                db.AddFile("test2.png", "test2.png", File.ReadAllBytes(image));
                Assert.AreEqual(2, db.Database.FileStorage.FindAll().Count());
            }
        }
        public void ImageReplaceTest()
        {
            using (var temp = TempDirectory.Create())
            {
                var db = new GameDatabase(temp.TempPath);
                db.OpenDatabase();
                var game = new Game()
                {
                    GameId = "testid",
                    Name   = "Test Game"
                };

                var origIcon       = db.AddFile(PlayniteTests.GenerateFakeFile(), game.Id);
                var origImage      = db.AddFile(PlayniteTests.GenerateFakeFile(), game.Id);
                var origBackground = db.AddFile(PlayniteTests.GenerateFakeFile(), game.Id);
                game.Icon            = origIcon;
                game.CoverImage      = origImage;
                game.BackgroundImage = origBackground;
                db.Games.Add(game);

                var newIcon       = PlayniteTests.GenerateFakeFile();
                var newImage      = PlayniteTests.GenerateFakeFile();
                var newBackground = PlayniteTests.GenerateFakeFile();
                File.WriteAllBytes(Path.Combine(temp.TempPath, newIcon.FileName), newIcon.Content);
                File.WriteAllBytes(Path.Combine(temp.TempPath, newImage.FileName), newImage.Content);
                File.WriteAllBytes(Path.Combine(temp.TempPath, newBackground.FileName), newBackground.Content);

                // Images are replaced
                var model = new GameEditViewModel(game, db, new MockWindowFactory(), new MockDialogsFactory(), new MockResourceProvider(), null);
                model.EditingGame.Icon            = Path.Combine(temp.TempPath, newIcon.FileName);
                model.EditingGame.CoverImage      = Path.Combine(temp.TempPath, newImage.FileName);
                model.EditingGame.BackgroundImage = Path.Combine(temp.TempPath, newBackground.FileName);
                model.ConfirmDialog();

                Assert.AreNotEqual(game.Icon, origIcon);
                Assert.AreNotEqual(game.CoverImage, origImage);
                Assert.AreNotEqual(game.BackgroundImage, origBackground);

                var dbFiles = Directory.GetFiles(db.GetFileStoragePath(game.Id));
                Assert.AreEqual(3, dbFiles.Count());
                CollectionAssert.AreEqual(newIcon.Content, File.ReadAllBytes(db.GetFullFilePath(game.Icon)));
                CollectionAssert.AreEqual(newImage.Content, File.ReadAllBytes(db.GetFullFilePath(game.CoverImage)));
                CollectionAssert.AreEqual(newBackground.Content, File.ReadAllBytes(db.GetFullFilePath(game.BackgroundImage)));
            }
        }
Esempio n. 5
0
 public void AddFileHttpTest()
 {
     using (var temp = TempDirectory.Create())
     {
         var db = new GameDatabase(temp.TempPath);
         db.OpenDatabase();
         var testId  = Guid.NewGuid();
         var addedId = db.AddFile(@"https://playnite.link/applogo.png", testId);
         FileAssert.Exists(Path.Combine(temp.TempPath, "files", addedId));
     }
 }
Esempio n. 6
0
        public void CheckSumCreationTest()
        {
            var image = Path.Combine(Paths.ProgramFolder, "Resources", "Images", "applogo.png");
            var db    = new GameDatabase(null);

            using (db.OpenDatabase(new MemoryStream()))
            {
                db.AddFile("test.png", "test.png", File.ReadAllBytes(image));
                var dbImage = db.GetFile("test.png");
                Assert.IsFalse(string.IsNullOrEmpty(dbImage.Metadata["checksum"].AsString));
            }
        }
Esempio n. 7
0
 public void AddFileTest()
 {
     using (var temp = TempDirectory.Create())
     {
         var db = new GameDatabase(temp.TempPath);
         db.OpenDatabase();
         var file    = PlayniteTests.GenerateFakeFile();
         var testId  = Guid.NewGuid();
         var addedId = db.AddFile(file.FileName, file.Content, testId);
         FileAssert.Exists(Path.Combine(temp.TempPath, "files", addedId));
     }
 }
Esempio n. 8
0
        public void FilesTest()
        {
            var path = Path.Combine(Playnite.PlayniteTests.TempPath, "dbapifiles.db");

            FileSystem.DeleteFile(path);

            var db = new GameDatabase();

            using (db.OpenDatabase(path))
            {
                var dbApi = new DatabaseAPI(db);
                Assert.AreEqual(0, dbApi.GetFiles().Count);

                db.AddFile("testid1", "testname1.png", new byte[] { 0, 1, 2 });
                db.AddFile("testid2", "testname2.png", new byte[] { 2, 1, 0 });

                var dbFiles = dbApi.GetFiles();
                Assert.AreEqual(2, dbFiles.Count);
                Assert.AreEqual("testid1", dbFiles[0].Id);
                Assert.AreEqual("testname1.png", dbFiles[0].Filename);
                Assert.AreEqual(3, dbFiles[0].Length);
                Assert.IsNotNull(dbFiles[0].Metadata["checksum"]);

                dbApi.RemoveFile(dbFiles[0].Id);
                Assert.AreEqual(1, dbApi.GetFiles().Count);

                var filePath = Path.Combine(Playnite.PlayniteTests.TempPath, "testname3.png");
                File.WriteAllBytes(filePath, new byte[] { 2, 1, 0 });

                var duplId = dbApi.AddFile("testid3", filePath);
                Assert.AreEqual("testid2", duplId);
                Assert.AreEqual(1, dbApi.GetFiles().Count);

                filePath = Path.Combine(Playnite.PlayniteTests.TempPath, "testFile2.png");
                FileSystem.DeleteFile(filePath);
                dbApi.SaveFile("testid2", filePath);
                Assert.IsTrue(File.Exists(filePath));
                Assert.AreEqual(3, File.ReadAllBytes(filePath).Count());
            }
        }
Esempio n. 9
0
        public void ImageReplaceMultiTest()
        {
            using (var temp = TempDirectory.Create())
            {
                var db = new GameDatabase(temp.TempPath);
                db.OpenDatabase();

                var game = new Game()
                {
                    GameId = "testid",
                    Name   = "Test Game"
                };

                var origIcon       = db.AddFile(PlayniteUITests.CreateFakeFile(), game.Id);
                var origImage      = db.AddFile(PlayniteUITests.CreateFakeFile(), game.Id);
                var origBackground = db.AddFile(PlayniteUITests.CreateFakeFile(), game.Id);
                game.Icon            = origIcon;
                game.CoverImage      = origImage;
                game.BackgroundImage = origBackground;
                db.Games.Add(game);

                game = new Game()
                {
                    GameId = "testid2",
                    Name   = "Test Game 2"
                };

                origIcon             = db.AddFile(PlayniteUITests.CreateFakeFile(), game.Id);
                origImage            = db.AddFile(PlayniteUITests.CreateFakeFile(), game.Id);
                origBackground       = db.AddFile(PlayniteUITests.CreateFakeFile(), game.Id);
                game.Icon            = origIcon;
                game.CoverImage      = origImage;
                game.BackgroundImage = origBackground;
                db.Games.Add(game);

                var newIcon       = PlayniteUITests.CreateFakeFile();
                var newImage      = PlayniteUITests.CreateFakeFile();
                var newBackground = PlayniteUITests.CreateFakeFile();

                // Replaces all images for all games
                var games = db.Games.ToList();
                var model = new GameEditViewModel(games, db, new MockWindowFactory(), new MockDialogsFactory(), new MockResourceProvider(), null);
                model.EditingGame.Icon            = newIcon.OriginalUrl;
                model.EditingGame.CoverImage      = newImage.OriginalUrl;
                model.EditingGame.BackgroundImage = newBackground.OriginalUrl;
                model.ConfirmDialog();

                Assert.AreEqual(3, Directory.GetFiles(db.GetFileStoragePath(games[0].Id)).Count());
                Assert.AreEqual(3, Directory.GetFiles(db.GetFileStoragePath(games[1].Id)).Count());

                CollectionAssert.AreEqual(newIcon.Content, File.ReadAllBytes(db.GetFullFilePath(games[0].Icon)));
                CollectionAssert.AreEqual(newImage.Content, File.ReadAllBytes(db.GetFullFilePath(games[0].CoverImage)));
                CollectionAssert.AreEqual(newBackground.Content, File.ReadAllBytes(db.GetFullFilePath(games[0].BackgroundImage)));

                CollectionAssert.AreEqual(newIcon.Content, File.ReadAllBytes(db.GetFullFilePath(games[1].Icon)));
                CollectionAssert.AreEqual(newImage.Content, File.ReadAllBytes(db.GetFullFilePath(games[1].CoverImage)));
                CollectionAssert.AreEqual(newBackground.Content, File.ReadAllBytes(db.GetFullFilePath(games[1].BackgroundImage)));
            }
        }
Esempio n. 10
0
 public void AddFileHttp404Test()
 {
     using (var temp = TempDirectory.Create())
     {
         var db = new GameDatabase(temp.TempPath);
         db.OpenDatabase();
         var testId  = Guid.NewGuid();
         var addedId = db.AddFile(@"https://playnite.link/doesntexists.png", testId);
         Assert.IsNull(addedId);
         var files = Directory.GetFiles(Path.Combine(temp.TempPath, "files", testId.ToString()));
         Assert.AreEqual(0, files.Count());
     }
 }
        public void DatabaseTest()
        {
            var file = Path.Combine(PlaynitePaths.ProgramPath, "Resources", "Images", "applogo.png");

            using (var temp = TempDirectory.Create())
            {
                var db = new GameDatabase(temp.TempPath);
                db.OpenDatabase();
                var image = db.AddFile("image.png", File.ReadAllBytes(file), Guid.NewGuid());
                ImageSourceManager.SetDatabase(db);
                var result = ImageSourceManager.GetImage(image, false);
                Assert.AreEqual(typeof(BitmapImage), result.GetType());
            }
        }
Esempio n. 12
0
        public void DeleteGameImageCleanupTest()
        {
            using (var temp = TempDirectory.Create())
            {
                var db = new GameDatabase(temp.TempPath);
                db.OpenDatabase();
                var game = new Game("Test");
                db.Games.Add(game);
                game.Icon            = db.AddFile(PlayniteTests.GenerateFakeFile(), game.Id);
                game.BackgroundImage = db.AddFile(PlayniteTests.GenerateFakeFile(), game.Id);
                game.CoverImage      = db.AddFile(PlayniteTests.GenerateFakeFile(), game.Id);

                Assert.IsNotEmpty(game.Icon);
                Assert.IsNotEmpty(game.BackgroundImage);
                Assert.IsNotEmpty(game.CoverImage);

                var files = Directory.GetFiles(db.GetFileStoragePath(game.Id));
                Assert.AreEqual(3, files.Count());

                db.Games.Remove(game);
                files = Directory.GetFiles(db.GetFileStoragePath(game.Id));
                Assert.AreEqual(0, files.Count());
            }
        }
        public void DatabaseTest()
        {
            var converter = new CustomImageStringToImageConverter();
            var file      = Path.Combine(PlaynitePaths.ProgramPath, "Resources", "Images", "applogo.png");

            using (var temp = TempDirectory.Create())
            {
                var db = new GameDatabase(temp.TempPath);
                db.OpenDatabase();
                var image = db.AddFile("image.png", File.ReadAllBytes(file), Guid.NewGuid());
                CustomImageStringToImageConverter.SetDatabase(db);
                var result = converter.Convert(image, null, null, CultureInfo.CurrentCulture);
                Assert.AreEqual(typeof(BitmapImage), result.GetType());
            }
        }
Esempio n. 14
0
        public void CheckSumCreationTest()
        {
            var image = Path.Combine(Paths.ProgramFolder, "Resources", "Images", "applogo.png");
            var path  = Path.Combine(Playnite.PlayniteTests.TempPath, "filechecksum.db");

            FileSystem.DeleteFile(path);

            var db = new GameDatabase(null);

            using (db.OpenDatabase(path))
            {
                db.AddFile("test.png", "test.png", File.ReadAllBytes(image));
                var dbImage = db.GetFile("test.png");
                Assert.IsFalse(string.IsNullOrEmpty(dbImage.Metadata["checksum"].AsString));
            }
        }
        public void DatabaseTest()
        {
            var converter = new CustomImageStringToImageConverter();
            var file      = Path.Combine(Paths.ProgramFolder, "Resources", "Images", "applogo.png");
            var path      = Path.Combine(PlayniteUITests.TempPath, "imageconverttest.db");

            FileSystem.DeleteFile(path);
            var db = new GameDatabase(null);

            using (db.OpenDatabase(path))
            {
                var image = "image.png";
                db.AddFile(image, image, File.ReadAllBytes(file));
                CustomImageStringToImageConverter.Database = db;
                var result = converter.Convert(image, null, null, CultureInfo.CurrentCulture);
                Assert.AreEqual(typeof(BitmapImage), result.GetType());
            }
        }
Esempio n. 16
0
        public void DeleteImageSafeTest()
        {
            var path = Path.Combine(Playnite.PlayniteTests.TempPath, "deleteimagetest.db");

            FileSystem.DeleteFile(path);

            var db = new GameDatabase(null);

            using (db.OpenDatabase(path))
            {
                db.AddFile("testimage", "testimage.png", new byte[] { 0 });
                Assert.AreEqual(1, db.Database.FileStorage.FindAll().Count());

                db.AddGame(new Game()
                {
                    ProviderId = "testid",
                    Name       = "Test Game",
                    Icon       = "testimage"
                });

                db.AddGame(new Game()
                {
                    ProviderId = "testid2",
                    Name       = "Test Game 2",
                    Icon       = "testimage"
                });

                // Doesn't remove image in use
                var games = db.GamesCollection.FindAll().ToList();
                db.DeleteImageSafe("testimage", games[0]);
                Assert.AreEqual(1, db.Database.FileStorage.FindAll().Count());

                // Removes image
                games[1].Icon = string.Empty;
                db.UpdateGameInDatabase(games[1]);
                db.DeleteImageSafe("testimage", games[0]);
                Assert.AreEqual(0, db.Database.FileStorage.FindAll().Count());
            }
        }
Esempio n. 17
0
        public void ImageReplaceMultiTest()
        {
            var path = Path.Combine(PlayniteUITests.TempPath, "imagereplacemulti.db");

            FileSystem.DeleteFile(path);

            var db = new GameDatabase(null);

            using (db.OpenDatabase(path))
            {
                var origIcon       = PlayniteUITests.CreateFakeFile();
                var origImage      = PlayniteUITests.CreateFakeFile();
                var origBackground = PlayniteUITests.CreateFakeFile();
                db.AddFile(origIcon.FileName, origIcon.FileName, origIcon.Content);
                db.AddFile(origImage.FileName, origImage.FileName, origImage.Content);
                db.AddFile(origBackground.FileName, origBackground.FileName, origBackground.Content);
                db.AddGame(new Game()
                {
                    GameId          = "testid",
                    Name            = "Test Game",
                    CoverImage      = origImage.FileName,
                    Icon            = origIcon.FileName,
                    BackgroundImage = origBackground.FileName
                });

                origIcon       = PlayniteUITests.CreateFakeFile();
                origImage      = PlayniteUITests.CreateFakeFile();
                origBackground = PlayniteUITests.CreateFakeFile();
                db.AddFile(origIcon.FileName, origIcon.FileName, origIcon.Content);
                db.AddFile(origImage.FileName, origImage.FileName, origImage.Content);
                db.AddFile(origBackground.FileName, origBackground.FileName, origBackground.Content);
                db.AddGame(new Game()
                {
                    GameId          = "testid2",
                    Name            = "Test Game 2",
                    CoverImage      = origImage.FileName,
                    Icon            = origIcon.FileName,
                    BackgroundImage = origBackground.FileName
                });

                Assert.AreEqual(6, db.Database.FileStorage.FindAll().ToList().Count());

                var newIcon       = PlayniteUITests.CreateFakeFile();
                var newImage      = PlayniteUITests.CreateFakeFile();
                var newBackground = PlayniteUITests.CreateFakeFile();

                // Replaces all images for all games
                var games = db.GamesCollection.FindAll().ToList();
                var model = new GameEditViewModel(games, db, new MockWindowFactory(), new MockDialogsFactory(), new MockResourceProvider(), null);
                model.EditingGame.Icon            = newIcon.FileId;
                model.EditingGame.CoverImage      = newImage.FileId;
                model.EditingGame.BackgroundImage = newBackground.FileId;
                model.ConfirmDialog();

                var dbFiles = db.Database.FileStorage.FindAll().ToList();
                Assert.AreEqual(3, dbFiles.Count());

                games = db.GamesCollection.FindAll().ToList();
                foreach (var game in games)
                {
                    StringAssert.StartsWith("images/custom/", game.Icon);
                    StringAssert.StartsWith("images/custom/", game.CoverImage);
                    StringAssert.StartsWith("images/custom/", game.BackgroundImage);
                }

                Assert.AreEqual(games[0].Icon, games[1].Icon);
                Assert.AreEqual(games[0].CoverImage, games[1].CoverImage);
                Assert.AreEqual(games[0].BackgroundImage, games[1].BackgroundImage);

                // Replaces only non-duplicate images
                newIcon       = PlayniteUITests.CreateFakeFile();
                newImage      = PlayniteUITests.CreateFakeFile();
                newBackground = PlayniteUITests.CreateFakeFile();
                db.AddFile(newIcon.FileName, newIcon.FileName, newIcon.Content);
                db.AddFile(newImage.FileName, newImage.FileName, newImage.Content);
                db.AddFile(newBackground.FileName, newBackground.FileName, newBackground.Content);
                games[0].Icon            = newIcon.FileName;
                games[0].CoverImage      = newImage.FileName;
                games[0].BackgroundImage = newBackground.FileName;
                db.UpdateGameInDatabase(games[0]);

                Assert.AreEqual(6, db.Database.FileStorage.FindAll().ToList().Count());

                games = db.GamesCollection.FindAll().ToList();
                model = new GameEditViewModel(games, db, new MockWindowFactory(), new MockDialogsFactory(), new MockResourceProvider(), null);
                model.EditingGame.Icon            = newIcon.FileId;
                model.EditingGame.CoverImage      = newImage.FileId;
                model.EditingGame.BackgroundImage = newBackground.FileId;
                model.ConfirmDialog();

                Assert.AreEqual(3, db.Database.FileStorage.FindAll().ToList().Count());

                games = db.GamesCollection.FindAll().ToList();
                foreach (var game in games)
                {
                    Assert.AreEqual(newIcon.FileName, game.Icon);
                    Assert.AreEqual(newImage.FileName, game.CoverImage);
                    Assert.AreEqual(newBackground.FileName, game.BackgroundImage);
                }
            }
        }
Esempio n. 18
0
        public Task DownloadMetadataAsync(
            List <Game> games,
            MetadataDownloaderSettings settings,
            Action <Game, int, int> processCallback,
            CancellationTokenSource cancelToken)
        {
            return(Task.Run(() =>
            {
                if (games == null || games.Count == 0)
                {
                    return;
                }

                for (int i = 0; i < games.Count; i++)
                {
                    Game game = null;

                    try
                    {
                        if (cancelToken?.IsCancellationRequested == true)
                        {
                            return;
                        }

                        GameMetadata storeData = null;
                        GameMetadata igdbData = null;
                        GameMetadata gameData = null;

                        // We need to get new instance from DB in case game got edited or deleted.
                        // We don't want to block game editing while metadata is downloading for other games.
                        game = database.Games[games[i].Id];
                        if (game == null)
                        {
                            logger.Warn($"Game {game.GameId} no longer in DB, skipping metadata download.");
                            processCallback?.Invoke(null, i, games.Count);
                            continue;
                        }

                        logger.Debug($"Downloading metadata for {game.Name}, {game.GameId}, {game.PluginId}");

                        // Name
                        if (!game.IsCustomGame && settings.Name.Import)
                        {
                            gameData = ProcessField(game, settings.Name, ref storeData, ref igdbData, (a) => a.GameData?.Name);
                            if (!string.IsNullOrEmpty(gameData?.GameData?.Name))
                            {
                                game.Name = StringExtensions.RemoveTrademarks(gameData.GameData.Name);
                                var sortingName = StringExtensions.ConvertToSortableName(game.Name);
                                if (sortingName != game.Name)
                                {
                                    game.SortingName = sortingName;
                                }
                            }
                        }

                        // Genre
                        if (settings.Genre.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && ListExtensions.IsNullOrEmpty(game.Genres)))
                            {
                                gameData = ProcessField(game, settings.Genre, ref storeData, ref igdbData, (a) => a.GameData?.Genres);
                                game.Genres = ListExtensions.IsNullOrEmpty(gameData?.GameData?.Genres) ? game.Genres : gameData.GameData.Genres;
                            }
                        }

                        // Release Date
                        if (settings.ReleaseDate.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && game.ReleaseDate == null))
                            {
                                gameData = ProcessField(game, settings.ReleaseDate, ref storeData, ref igdbData, (a) => a.GameData?.ReleaseDate);
                                game.ReleaseDate = gameData?.GameData?.ReleaseDate ?? game.ReleaseDate;
                            }
                        }

                        // Developer
                        if (settings.Developer.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && ListExtensions.IsNullOrEmpty(game.Developers)))
                            {
                                gameData = ProcessField(game, settings.Developer, ref storeData, ref igdbData, (a) => a.GameData?.Developers);
                                game.Developers = ListExtensions.IsNullOrEmpty(gameData?.GameData?.Developers) ? game.Developers : gameData.GameData.Developers;
                            }
                        }

                        // Publisher
                        if (settings.Publisher.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && ListExtensions.IsNullOrEmpty(game.Publishers)))
                            {
                                gameData = ProcessField(game, settings.Publisher, ref storeData, ref igdbData, (a) => a.GameData?.Publishers);
                                game.Publishers = ListExtensions.IsNullOrEmpty(gameData?.GameData?.Publishers) ? game.Publishers : gameData.GameData.Publishers;
                            }
                        }

                        // Tags / Features
                        if (settings.Tag.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && ListExtensions.IsNullOrEmpty(game.Tags)))
                            {
                                gameData = ProcessField(game, settings.Tag, ref storeData, ref igdbData, (a) => a.GameData?.Tags);
                                game.Tags = ListExtensions.IsNullOrEmpty(gameData?.GameData?.Tags) ? game.Tags : gameData.GameData.Tags;
                            }
                        }

                        // Description
                        if (settings.Description.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && string.IsNullOrEmpty(game.Description)))
                            {
                                gameData = ProcessField(game, settings.Description, ref storeData, ref igdbData, (a) => a.GameData?.Description);
                                game.Description = string.IsNullOrEmpty(gameData?.GameData?.Description) == true ? game.Description : gameData.GameData.Description;
                            }
                        }

                        // Links
                        if (settings.Links.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && game.Links == null))
                            {
                                gameData = ProcessField(game, settings.Links, ref storeData, ref igdbData, (a) => a.GameData?.Links);
                                game.Links = gameData?.GameData?.Links ?? game.Links;
                            }
                        }

                        // Critic Score
                        if (settings.CriticScore.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && game.CriticScore == null))
                            {
                                gameData = ProcessField(game, settings.CriticScore, ref storeData, ref igdbData, (a) => a.GameData?.CriticScore);
                                game.CriticScore = gameData?.GameData?.CriticScore == null ? game.CriticScore : gameData.GameData.CriticScore;
                            }
                        }

                        // Community Score
                        if (settings.CommunityScore.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && game.CommunityScore == null))
                            {
                                gameData = ProcessField(game, settings.CommunityScore, ref storeData, ref igdbData, (a) => a.GameData?.CommunityScore);
                                game.CommunityScore = gameData?.GameData?.CommunityScore == null ? game.CommunityScore : gameData.GameData.CommunityScore;
                            }
                        }

                        // BackgroundImage
                        if (settings.BackgroundImage.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && string.IsNullOrEmpty(game.BackgroundImage)))
                            {
                                gameData = ProcessField(game, settings.BackgroundImage, ref storeData, ref igdbData, (a) => a.BackgroundImage);
                                if (!string.IsNullOrEmpty(gameData?.BackgroundImage))
                                {
                                    RemoveGameMedia(game.BackgroundImage);
                                    game.BackgroundImage = gameData.BackgroundImage;
                                }
                            }
                        }

                        // Cover
                        if (settings.CoverImage.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && string.IsNullOrEmpty(game.CoverImage)))
                            {
                                gameData = ProcessField(game, settings.CoverImage, ref storeData, ref igdbData, (a) => a.Image);
                                if (gameData?.Image != null)
                                {
                                    RemoveGameMedia(game.CoverImage);
                                    game.CoverImage = database.AddFile(gameData.Image, game.Id);
                                }
                            }
                        }

                        // Icon
                        if (settings.Icon.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && string.IsNullOrEmpty(game.Icon)))
                            {
                                gameData = ProcessField(game, settings.Icon, ref storeData, ref igdbData, (a) => a.Icon);
                                if (gameData?.Icon != null)
                                {
                                    RemoveGameMedia(game.Icon);
                                    game.Icon = database.AddFile(gameData.Icon, game.Id);
                                }
                            }
                        }

                        // TODO make this configurable and re-downalodable manually
                        // Only update them if they don't exist yet
                        if (game.OtherActions?.Any() != true && storeData != null)
                        {
                            if (storeData?.GameData?.OtherActions?.Any() == true)
                            {
                                game.OtherActions = new System.Collections.ObjectModel.ObservableCollection <GameAction>();
                                foreach (var task in storeData.GameData.OtherActions)
                                {
                                    game.OtherActions.Add(task);
                                }
                            }
                        }

                        // Just to be sure check if somebody didn't remove game while downloading data
                        if (database.Games.FirstOrDefault(a => a.GameId == games[i].GameId) != null)
                        {
                            database.Games.Update(game);
                        }
                        else
                        {
                            logger.Warn($"Game {game.GameId} no longer in DB, skipping metadata update in DB.");
                        }
                    }
                    catch (Exception e) when(!PlayniteEnvironment.ThrowAllErrors)
                    {
                        logger.Error(e, $"Failed to download metadata for game {game?.Name}, {game?.GameId}");
                    }
                    finally
                    {
                        if (game != null)
                        {
                            processCallback?.Invoke(game, i, games.Count);
                        }
                    }
                }
            }));
        }
Esempio n. 19
0
        public Task DownloadMetadataAsync(
            List <Game> games,
            MetadataDownloaderSettings settings,
            PlayniteSettings playniteSettings,
            Action <Game, int, int> progressCallback,
            CancellationToken cancelToken)
        {
            return(Task.Run(() =>
            {
                if (games == null || games.Count == 0)
                {
                    return;
                }

                for (int i = 0; i < games.Count; i++)
                {
                    Game game = null;
                    var existingStoreData = new Dictionary <Guid, GameMetadata>();
                    var existingPluginData = new Dictionary <Guid, OnDemandMetadataProvider>();

                    try
                    {
                        if (cancelToken.IsCancellationRequested == true)
                        {
                            return;
                        }

                        GameMetadata gameData = null;

                        // We need to get new instance from DB in case game got edited or deleted.
                        // We don't want to block game editing while metadata is downloading for other games.
                        game = database.Games[games[i].Id]?.GetClone();
                        if (game == null)
                        {
                            logger.Warn($"Game {game.Id} no longer in DB, skipping metadata download.");
                            progressCallback?.Invoke(null, i, games.Count);
                            continue;
                        }

                        var dataModified = false;
                        game.PropertyChanged += (_, __) => dataModified = true;

                        if (game != null)
                        {
                            progressCallback?.Invoke(game, i, games.Count);
                        }

                        logger.Debug($"Downloading metadata for {game.Name}, {game.GameId}, {game.PluginId}");

                        // Name
                        if (!game.IsCustomGame && settings.Name.Import)
                        {
                            gameData = ProcessField(game, settings.Name, MetadataField.Name, (a) => a.Name, existingStoreData, existingPluginData, cancelToken);
                            if (!string.IsNullOrEmpty(gameData?.Name))
                            {
                                game.Name = StringExtensions.RemoveTrademarks(gameData.Name);
                                var sortingName = StringExtensions.ConvertToSortableName(game.Name);
                                if (sortingName != game.Name)
                                {
                                    game.SortingName = sortingName;
                                }
                            }
                        }

                        // Genre
                        if (settings.Genre.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && !game.GenreIds.HasItems()))
                            {
                                gameData = ProcessField(game, settings.Genre, MetadataField.Genres, (a) => a.Genres, existingStoreData, existingPluginData, cancelToken);
                                if (gameData?.Genres.HasItems() == true)
                                {
                                    game.GenreIds = database.Genres.Add(gameData.Genres).Select(a => a.Id).ToList();
                                }
                            }
                        }

                        // Release Date
                        if (settings.ReleaseDate.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && game.ReleaseDate == null))
                            {
                                gameData = ProcessField(game, settings.ReleaseDate, MetadataField.ReleaseDate, (a) => a.ReleaseDate, existingStoreData, existingPluginData, cancelToken);
                                game.ReleaseDate = gameData?.ReleaseDate ?? game.ReleaseDate;
                            }
                        }

                        // Developer
                        if (settings.Developer.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && !game.DeveloperIds.HasItems()))
                            {
                                gameData = ProcessField(game, settings.Developer, MetadataField.Developers, (a) => a.Developers, existingStoreData, existingPluginData, cancelToken);
                                if (gameData?.Developers.HasItems() == true)
                                {
                                    game.DeveloperIds = database.Companies.Add(gameData.Developers).Select(a => a.Id).ToList();
                                }
                            }
                        }

                        // Publisher
                        if (settings.Publisher.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && !game.PublisherIds.HasItems()))
                            {
                                gameData = ProcessField(game, settings.Publisher, MetadataField.Publishers, (a) => a.Publishers, existingStoreData, existingPluginData, cancelToken);
                                if (gameData?.Publishers.HasItems() == true)
                                {
                                    game.PublisherIds = database.Companies.Add(gameData.Publishers).Select(a => a.Id).ToList();
                                }
                            }
                        }

                        // Tags
                        if (settings.Tag.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && !game.TagIds.HasItems()))
                            {
                                gameData = ProcessField(game, settings.Tag, MetadataField.Tags, (a) => a.Tags, existingStoreData, existingPluginData, cancelToken);
                                if (gameData?.Tags.HasItems() == true)
                                {
                                    game.TagIds = database.Tags.Add(gameData.Tags).Select(a => a.Id).ToList();
                                }
                            }
                        }

                        // Features
                        if (settings.Feature.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && !game.FeatureIds.HasItems()))
                            {
                                gameData = ProcessField(game, settings.Feature, MetadataField.Features, (a) => a.Features, existingStoreData, existingPluginData, cancelToken);
                                if (gameData?.Features.HasItems() == true)
                                {
                                    game.FeatureIds = database.Features.Add(gameData.Features).Select(a => a.Id).ToList();
                                }
                            }
                        }

                        // Description
                        if (settings.Description.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && string.IsNullOrEmpty(game.Description)))
                            {
                                gameData = ProcessField(game, settings.Description, MetadataField.Description, (a) => a.Description, existingStoreData, existingPluginData, cancelToken);
                                game.Description = string.IsNullOrEmpty(gameData?.Description) == true ? game.Description : gameData.Description;
                            }
                        }

                        // Links
                        if (settings.Links.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && !game.Links.HasItems()))
                            {
                                gameData = ProcessField(game, settings.Links, MetadataField.Links, (a) => a.Links, existingStoreData, existingPluginData, cancelToken);
                                if (gameData?.Links.HasItems() == true)
                                {
                                    game.Links = gameData.Links.ToObservable();
                                }
                            }
                        }

                        // Age rating
                        if (settings.AgeRating.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && !game.AgeRatingIds.HasItems()))
                            {
                                gameData = ProcessField(game, settings.AgeRating, MetadataField.AgeRating, (a) => a.AgeRatings, existingStoreData, existingPluginData, cancelToken);
                                if (gameData?.AgeRatings.HasItems() == true)
                                {
                                    game.AgeRatingIds = database.AgeRatings.Add(gameData.AgeRatings).Select(a => a.Id).ToList();
                                }
                            }
                        }

                        // Region
                        if (settings.Region.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && !game.RegionIds.HasItems()))
                            {
                                gameData = ProcessField(game, settings.Region, MetadataField.Region, (a) => a.Regions, existingStoreData, existingPluginData, cancelToken);
                                if (gameData?.Regions.HasItems() == true)
                                {
                                    game.RegionIds = database.Regions.Add(gameData.Regions).Select(a => a.Id).ToList();
                                }
                            }
                        }

                        // Series
                        if (settings.Series.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && !game.SeriesIds.HasItems()))
                            {
                                gameData = ProcessField(game, settings.Series, MetadataField.Series, (a) => a.Series, existingStoreData, existingPluginData, cancelToken);
                                if (gameData?.Series.HasItems() == true)
                                {
                                    game.SeriesIds = database.Series.Add(gameData.Series).Select(a => a.Id).ToList();
                                }
                            }
                        }

                        // Platform
                        if (settings.Platform.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && !game.PlatformIds.HasItems()))
                            {
                                gameData = ProcessField(game, settings.Platform, MetadataField.Platform, (a) => a.Platforms, existingStoreData, existingPluginData, cancelToken);
                                if (gameData?.Platforms.HasItems() == true)
                                {
                                    game.PlatformIds = database.Platforms.Add(gameData.Platforms).Select(a => a.Id).ToList();
                                }
                            }
                        }

                        // Critic Score
                        if (settings.CriticScore.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && game.CriticScore == null))
                            {
                                gameData = ProcessField(game, settings.CriticScore, MetadataField.CriticScore, (a) => a.CriticScore, existingStoreData, existingPluginData, cancelToken);
                                game.CriticScore = gameData?.CriticScore == null ? game.CriticScore : gameData.CriticScore;
                            }
                        }

                        // Community Score
                        if (settings.CommunityScore.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && game.CommunityScore == null))
                            {
                                gameData = ProcessField(game, settings.CommunityScore, MetadataField.CommunityScore, (a) => a.CommunityScore, existingStoreData, existingPluginData, cancelToken);
                                game.CommunityScore = gameData?.CommunityScore == null ? game.CommunityScore : gameData.CommunityScore;
                            }
                        }

                        // BackgroundImage
                        if (settings.BackgroundImage.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && string.IsNullOrEmpty(game.BackgroundImage)))
                            {
                                gameData = ProcessField(game, settings.BackgroundImage, MetadataField.BackgroundImage, (a) => a.BackgroundImage, existingStoreData, existingPluginData, cancelToken);
                                if (gameData?.BackgroundImage != null)
                                {
                                    if (playniteSettings.DownloadBackgroundsImmediately && gameData.BackgroundImage.HasImageData)
                                    {
                                        game.BackgroundImage = database.AddFile(gameData.BackgroundImage, game.Id, true);
                                    }
                                    else if (!playniteSettings.DownloadBackgroundsImmediately &&
                                             !gameData.BackgroundImage.Path.IsNullOrEmpty())
                                    {
                                        game.BackgroundImage = gameData.BackgroundImage.Path;
                                    }
                                    else if (gameData.BackgroundImage.HasImageData)
                                    {
                                        game.BackgroundImage = database.AddFile(gameData.BackgroundImage, game.Id, true);
                                    }
                                }
                            }
                        }

                        // Cover
                        if (settings.CoverImage.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && string.IsNullOrEmpty(game.CoverImage)))
                            {
                                gameData = ProcessField(game, settings.CoverImage, MetadataField.CoverImage, (a) => a.CoverImage, existingStoreData, existingPluginData, cancelToken);
                                if (gameData?.CoverImage != null)
                                {
                                    game.CoverImage = database.AddFile(gameData.CoverImage, game.Id, true);
                                }
                            }
                        }

                        // Icon
                        if (settings.Icon.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && string.IsNullOrEmpty(game.Icon)))
                            {
                                gameData = ProcessField(game, settings.Icon, MetadataField.Icon, (a) => a.Icon, existingStoreData, existingPluginData, cancelToken);
                                if (gameData?.Icon != null)
                                {
                                    game.Icon = database.AddFile(gameData.Icon, game.Id, true);
                                }
                            }
                        }

                        // Just to be sure check if somebody didn't remove game while downloading data
                        if (database.Games.FirstOrDefault(a => a.Id == games[i].Id) != null && dataModified)
                        {
                            game.Modified = DateTime.Now;
                            database.Games.Update(game);
                        }
                        else
                        {
                            logger.Warn($"Game {game.Id} no longer in DB, skipping metadata update in DB.");
                        }
                    }
                    catch (Exception e) when(!PlayniteEnvironment.ThrowAllErrors)
                    {
                        logger.Error(e, $"Failed to download metadata for game {game?.Name}, {game?.Id}");
                    }
                    finally
                    {
                        foreach (var plugin in existingPluginData.Values)
                        {
                            plugin.Dispose();
                        }
                    }
                }
            }));
        }
Esempio n. 20
0
        public void ImageReplaceTest()
        {
            var path = Path.Combine(PlayniteUITests.TempPath, "imagereplace.db");

            FileSystem.DeleteFile(path);

            var db = new GameDatabase(null);

            using (db.OpenDatabase(path))
            {
                var origIcon       = PlayniteUITests.CreateFakeFile();
                var origImage      = PlayniteUITests.CreateFakeFile();
                var origBackground = PlayniteUITests.CreateFakeFile();

                db.AddFile(origIcon.FileName, origIcon.FileName, origIcon.Content);
                db.AddFile(origImage.FileName, origImage.FileName, origImage.Content);
                db.AddFile(origBackground.FileName, origBackground.FileName, origBackground.Content);

                var game = new Game()
                {
                    GameId          = "testid",
                    Name            = "Test Game",
                    CoverImage      = origImage.FileName,
                    Icon            = origIcon.FileName,
                    BackgroundImage = origBackground.FileName
                };

                db.AddGame(game);

                var newIcon       = PlayniteUITests.CreateFakeFile();
                var newImage      = PlayniteUITests.CreateFakeFile();
                var newBackground = PlayniteUITests.CreateFakeFile();

                // Images are replaced
                var model = new GameEditViewModel(game, db, new MockWindowFactory(), new MockDialogsFactory(), new MockResourceProvider(), null);
                model.EditingGame.Icon            = newIcon.FileId;
                model.EditingGame.CoverImage      = newImage.FileId;
                model.EditingGame.BackgroundImage = newBackground.FileId;
                model.ConfirmDialog();

                Assert.AreNotEqual(game.Icon, origIcon.FileName);
                Assert.AreNotEqual(game.CoverImage, origImage.FileName);
                Assert.AreNotEqual(game.BackgroundImage, origBackground.FileName);
                Assert.AreNotEqual(game.Icon, newIcon.FileId);
                Assert.AreNotEqual(game.CoverImage, newImage.FileId);
                Assert.AreNotEqual(game.BackgroundImage, newBackground.FileId);

                var dbFiles = db.Database.FileStorage.FindAll().ToList();
                Assert.AreEqual(3, dbFiles.Count());

                using (var str = db.GetFileStream(game.Icon))
                {
                    CollectionAssert.AreEqual(newIcon.Content, str.ToArray());
                }

                using (var str = db.GetFileStream(game.CoverImage))
                {
                    CollectionAssert.AreEqual(newImage.Content, str.ToArray());
                }

                using (var str = db.GetFileStream(game.BackgroundImage))
                {
                    CollectionAssert.AreEqual(newBackground.Content, str.ToArray());
                }

                // Duplicates are kept and not replaced
                var currentIcon  = game.Icon;
                var currentImage = game.CoverImage;
                var currentBack  = game.BackgroundImage;

                model = new GameEditViewModel(game, db, new MockWindowFactory(), new MockDialogsFactory(), new MockResourceProvider(), null);
                model.EditingGame.Icon            = newIcon.FileId;
                model.EditingGame.CoverImage      = newImage.FileId;
                model.EditingGame.BackgroundImage = newBackground.FileId;
                model.ConfirmDialog();

                dbFiles = db.Database.FileStorage.FindAll().ToList();
                Assert.AreEqual(3, dbFiles.Count());
                Assert.AreEqual(game.Icon, currentIcon);
                Assert.AreEqual(game.CoverImage, currentImage);
                Assert.AreEqual(game.BackgroundImage, currentBack);
            }
        }