From 74171b50af72ef4d550312fb84e7f162793a8fa9 Mon Sep 17 00:00:00 2001 From: Michael Green <84688932+michael-j-green@users.noreply.github.com> Date: Sun, 17 Nov 2024 22:04:26 +1100 Subject: [PATCH] WIP --- gaseous-server/Classes/Bios.cs | 3 +- gaseous-server/Classes/Collections.cs | 246 ++++++------ gaseous-server/Classes/Config.cs | 7 +- gaseous-server/Classes/DatabaseMigration.cs | 5 +- gaseous-server/Classes/FileSignature.cs | 2 +- gaseous-server/Classes/GameLibrary.cs | 3 +- gaseous-server/Classes/ImportGames.cs | 52 +-- gaseous-server/Classes/Metadata/AgeGroups.cs | 36 +- gaseous-server/Classes/Metadata/AgeRating.cs | 73 +--- .../Metadata/AgeRatingContentDescriptions.cs | 53 +-- .../Classes/Metadata/AlternativeNames.cs | 53 +-- gaseous-server/Classes/Metadata/Artworks.cs | 75 +--- .../Classes/Metadata/Collections.cs | 54 +-- .../Classes/Metadata/Communications.cs | 68 +++- gaseous-server/Classes/Metadata/Company.cs | 70 +--- .../Classes/Metadata/CompanyLogos.cs | 72 +--- gaseous-server/Classes/Metadata/Covers.cs | 77 +--- .../Classes/Metadata/ExternalGames.cs | 64 +-- gaseous-server/Classes/Metadata/Franchises.cs | 54 +-- gaseous-server/Classes/Metadata/GameModes.cs | 53 +-- gaseous-server/Classes/Metadata/GameVideos.cs | 53 +-- gaseous-server/Classes/Metadata/Games.cs | 374 ++---------------- gaseous-server/Classes/Metadata/Genres.cs | 57 +-- .../Classes/Metadata/InvolvedCompany.cs | 60 +-- gaseous-server/Classes/Metadata/Metadata.cs | 140 +++++++ .../Classes/Metadata/MultiplayerModes.cs | 51 +-- .../Classes/Metadata/PlatformLogos.cs | 76 +--- .../Classes/Metadata/PlatformVersions.cs | 80 +--- gaseous-server/Classes/Metadata/Platforms.cs | 168 +------- .../Classes/Metadata/PlayerPerspectives.cs | 55 +-- .../Classes/Metadata/ReleaseDates.cs | 53 +-- .../Classes/Metadata/Screenshots.cs | 74 +--- gaseous-server/Classes/Metadata/Storage.cs | 362 ++++++++--------- gaseous-server/Classes/Metadata/Themes.cs | 55 +-- gaseous-server/Classes/MetadataManagement.cs | 13 +- gaseous-server/Classes/RomMediaGroup.cs | 8 +- gaseous-server/Classes/Roms.cs | 5 +- gaseous-server/Classes/UserProfile.cs | 5 +- .../Controllers/V1.0/BiosController.cs | 2 +- .../Controllers/V1.0/GamesController.cs | 268 +++++-------- .../Controllers/V1.0/PlatformsController.cs | 22 +- .../Controllers/V1.0/RomsController.cs | 8 +- .../Controllers/V1.0/SearchController.cs | 51 +-- .../Controllers/V1.1/GamesController.cs | 12 +- .../V1.1/StateManagerController.cs | 2 +- gaseous-server/Models/GaseousGame.cs | 49 +-- gaseous-server/Models/PlatformMapping.cs | 17 +- gaseous-server/Models/UserProfile.cs | 4 +- gaseous-server/Program.cs | 6 - .../Support/Database/MySQL/gaseous-1024.sql | 150 ++++++- 50 files changed, 1010 insertions(+), 2390 deletions(-) create mode 100644 gaseous-server/Classes/Metadata/Metadata.cs diff --git a/gaseous-server/Classes/Bios.cs b/gaseous-server/Classes/Bios.cs index c23c1f0..9217f18 100644 --- a/gaseous-server/Classes/Bios.cs +++ b/gaseous-server/Classes/Bios.cs @@ -1,6 +1,7 @@ using System; using System.Runtime.InteropServices; using System.Security.Cryptography; +using HasheousClient.Models.Metadata.IGDB; namespace gaseous_server.Classes { @@ -94,7 +95,7 @@ namespace gaseous_server.Classes { if (platformMapping.Bios != null) { - IGDB.Models.Platform platform = Metadata.Platforms.GetPlatform(platformMapping.IGDBId); + Platform platform = Metadata.Platforms.GetPlatform(platformMapping.IGDBId); foreach (Models.PlatformMapping.PlatformMapItem.EmulatorBiosItem emulatorBios in platformMapping.Bios) { diff --git a/gaseous-server/Classes/Collections.cs b/gaseous-server/Classes/Collections.cs index cc34163..ec9c90d 100644 --- a/gaseous-server/Classes/Collections.cs +++ b/gaseous-server/Classes/Collections.cs @@ -9,7 +9,7 @@ using gaseous_server.Classes.Metadata; using gaseous_server.Controllers; using gaseous_server.Controllers.v1_1; using gaseous_server.Models; -using IGDB.Models; +using HasheousClient.Models.Metadata.IGDB; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc.Filters; using Newtonsoft.Json; @@ -18,9 +18,10 @@ using static gaseous_server.Classes.Metadata.Games; namespace gaseous_server.Classes { - public class Collections - { - public static List GetCollections(string userid) { + public class Collections + { + public static List GetCollections(string userid) + { Database db = new Database(Database.databaseType.MySql, Config.DatabaseConfiguration.ConnectionString); string sql = "SELECT * FROM RomCollections WHERE OwnedBy=@ownedby ORDER BY `Name`"; Dictionary dbDict = new Dictionary{ @@ -30,16 +31,18 @@ namespace gaseous_server.Classes List collectionItems = new List(); - foreach(DataRow row in data.Rows) { + foreach (DataRow row in data.Rows) + { collectionItems.Add(BuildCollectionItem(row)); } return collectionItems; } - public static CollectionItem GetCollection(long Id, string userid) { + public static CollectionItem GetCollection(long Id, string userid) + { Database db = new Database(Database.databaseType.MySql, Config.DatabaseConfiguration.ConnectionString); - string sql; + string sql; if (userid == "") { // reserved for internal operations @@ -50,24 +53,24 @@ namespace gaseous_server.Classes // instigated by a user sql = "SELECT * FROM RomCollections WHERE Id = @id AND OwnedBy = @ownedby ORDER BY `Name`"; } - Dictionary dbDict = new Dictionary + Dictionary dbDict = new Dictionary { { "id", Id }, { "ownedby", userid } }; - DataTable romDT = db.ExecuteCMD(sql, dbDict); + DataTable romDT = db.ExecuteCMD(sql, dbDict); - if (romDT.Rows.Count > 0) - { - DataRow row = romDT.Rows[0]; - CollectionItem collectionItem = BuildCollectionItem(row); + if (romDT.Rows.Count > 0) + { + DataRow row = romDT.Rows[0]; + CollectionItem collectionItem = BuildCollectionItem(row); - return collectionItem; - } - else - { - throw new Exception("Unknown Collection Id"); - } + return collectionItem; + } + else + { + throw new Exception("Unknown Collection Id"); + } } public static CollectionItem NewCollection(CollectionItem item, string userid) @@ -130,9 +133,9 @@ namespace gaseous_server.Classes { "archivetype", Common.ReturnValueIfNull(item.ArchiveType, CollectionItem.ArchiveTypes.Zip) }, { "ownedby", userid } }; - + string CollectionZipFile = Path.Combine(Config.LibraryConfiguration.LibraryCollectionsDirectory, Id + item.ArchiveExtension); - if (ForceRebuild == true) + if (ForceRebuild == true) { dbDict.Add("builtstatus", CollectionItem.CollectionBuildStatus.WaitingForBuild); if (File.Exists(CollectionZipFile)) @@ -153,7 +156,7 @@ namespace gaseous_server.Classes } } db.ExecuteCMD(sql, dbDict); - + CollectionItem collectionItem = GetCollection(Id, userid); if (collectionItem.BuildStatus == CollectionItem.CollectionBuildStatus.WaitingForBuild) @@ -208,7 +211,8 @@ namespace gaseous_server.Classes } } - public static CollectionContents GetCollectionContent(CollectionItem collectionItem, string userid) { + public static CollectionContents GetCollectionContent(CollectionItem collectionItem, string userid) + { Database db = new Database(Database.databaseType.MySql, Config.DatabaseConfiguration.ConnectionString); // get age ratings for specified user @@ -245,30 +249,35 @@ namespace gaseous_server.Classes List platforms = new List(); // add platforms with an inclusion status - foreach (CollectionItem.AlwaysIncludeItem alwaysIncludeItem in collectionItem.AlwaysInclude) + foreach (CollectionItem.AlwaysIncludeItem alwaysIncludeItem in collectionItem.AlwaysInclude) { if ( alwaysIncludeItem.InclusionState == CollectionItem.AlwaysIncludeStatus.AlwaysInclude || alwaysIncludeItem.InclusionState == CollectionItem.AlwaysIncludeStatus.AlwaysExclude ) + { + if (!platformids.Contains(alwaysIncludeItem.PlatformId)) { - if (!platformids.Contains(alwaysIncludeItem.PlatformId)) - { - platformids.Add(alwaysIncludeItem.PlatformId); - } + platformids.Add(alwaysIncludeItem.PlatformId); + } } } // add dynamic platforms - if (DynamicPlatforms.Count > 0) { - foreach (long PlatformId in platformids) { + if (DynamicPlatforms.Count > 0) + { + foreach (long PlatformId in platformids) + { platforms.Add(Platforms.GetPlatform(PlatformId)); } - } else { + } + else + { // get all platforms to pull from Dictionary> FilterDict = Filters.Filter(AgeGroups.AgeRestrictionGroupings.Adult, true); List filteredPlatforms = (List)FilterDict["platforms"]; - foreach (Filters.FilterItem filterItem in filteredPlatforms) { + foreach (Filters.FilterItem filterItem in filteredPlatforms) + { platforms.Add(Platforms.GetPlatform(filterItem.Id)); } } @@ -280,7 +289,8 @@ namespace gaseous_server.Classes // build collection List platformItems = new List(); - foreach (Platform platform in platforms) { + foreach (Platform platform in platforms) + { long TotalRomSize = 0; long TotalGameCount = 0; @@ -297,7 +307,8 @@ namespace gaseous_server.Classes Controllers.v1_1.GamesController.GameReturnPackage games = new Controllers.v1_1.GamesController.GameReturnPackage(); if (isDynamic == true) { - Controllers.v1_1.GamesController.GameSearchModel searchModel = new Controllers.v1_1.GamesController.GameSearchModel{ + Controllers.v1_1.GamesController.GameSearchModel searchModel = new Controllers.v1_1.GamesController.GameSearchModel + { Name = "", Platform = new List{ platform.Id.ToString() @@ -306,49 +317,52 @@ namespace gaseous_server.Classes GameMode = collectionItem.Players.ConvertAll(s => s.ToString()), PlayerPerspective = collectionItem.PlayerPerspectives.ConvertAll(s => s.ToString()), Theme = collectionItem.Themes.ConvertAll(s => s.ToString()), - GameRating = new Controllers.v1_1.GamesController.GameSearchModel.GameRatingItem{ + GameRating = new Controllers.v1_1.GamesController.GameSearchModel.GameRatingItem + { MinimumRating = collectionItem.MinimumRating, MaximumRating = collectionItem.MaximumRating }, - GameAgeRating = new Controllers.v1_1.GamesController.GameSearchModel.GameAgeRatingItem{ + GameAgeRating = new Controllers.v1_1.GamesController.GameSearchModel.GameAgeRatingItem + { AgeGroupings = UserAgeGroupings, IncludeUnrated = UserAgeGroupIncludeUnrated } }; games = Controllers.v1_1.GamesController.GetGames(searchModel, userid); - + } CollectionContents.CollectionPlatformItem collectionPlatformItem = new CollectionContents.CollectionPlatformItem(platform); collectionPlatformItem.Games = new List(); // add titles with an inclusion status - foreach (CollectionItem.AlwaysIncludeItem alwaysIncludeItem in collectionItem.AlwaysInclude) + foreach (CollectionItem.AlwaysIncludeItem alwaysIncludeItem in collectionItem.AlwaysInclude) { if ( ( alwaysIncludeItem.InclusionState == CollectionItem.AlwaysIncludeStatus.AlwaysInclude || alwaysIncludeItem.InclusionState == CollectionItem.AlwaysIncludeStatus.AlwaysExclude ) && alwaysIncludeItem.PlatformId == platform.Id - ) - { - MinimalGameItem AlwaysIncludeGame = new MinimalGameItem(Games.GetGame(alwaysIncludeItem.GameId, false, false, false)); - CollectionContents.CollectionPlatformItem.CollectionGameItem gameItem = new CollectionContents.CollectionPlatformItem.CollectionGameItem(AlwaysIncludeGame); - gameItem.InclusionStatus = new CollectionItem.AlwaysIncludeItem(); - gameItem.InclusionStatus.PlatformId = alwaysIncludeItem.PlatformId; - gameItem.InclusionStatus.GameId = alwaysIncludeItem.GameId; - gameItem.InclusionStatus.InclusionState = alwaysIncludeItem.InclusionState; - gameItem.Roms = Roms.GetRoms((long)gameItem.Id, (long)platform.Id).GameRomItems; + ) + { + MinimalGameItem AlwaysIncludeGame = new MinimalGameItem(Games.GetGame(Communications.MetadataSource, alwaysIncludeItem.GameId)); + CollectionContents.CollectionPlatformItem.CollectionGameItem gameItem = new CollectionContents.CollectionPlatformItem.CollectionGameItem(AlwaysIncludeGame); + gameItem.InclusionStatus = new CollectionItem.AlwaysIncludeItem(); + gameItem.InclusionStatus.PlatformId = alwaysIncludeItem.PlatformId; + gameItem.InclusionStatus.GameId = alwaysIncludeItem.GameId; + gameItem.InclusionStatus.InclusionState = alwaysIncludeItem.InclusionState; + gameItem.Roms = Roms.GetRoms((long)gameItem.Id, (long)platform.Id).GameRomItems; - collectionPlatformItem.Games.Add(gameItem); + collectionPlatformItem.Games.Add(gameItem); } } - foreach (MinimalGameItem game in games.Games) { + foreach (MinimalGameItem game in games.Games) + { bool gameAlreadyInList = false; - foreach (CollectionContents.CollectionPlatformItem.CollectionGameItem existingGame in collectionPlatformItem.Games) + foreach (CollectionContents.CollectionPlatformItem.CollectionGameItem existingGame in collectionPlatformItem.Games) { - if (existingGame.Id == game.Id) + if (existingGame.Id == game.Id) { gameAlreadyInList = true; } @@ -359,31 +373,37 @@ namespace gaseous_server.Classes CollectionContents.CollectionPlatformItem.CollectionGameItem collectionGameItem = new CollectionContents.CollectionPlatformItem.CollectionGameItem(game); List gameRoms = Roms.GetRoms((long)game.Id, (long)platform.Id).GameRomItems; - + bool AddGame = false; // calculate total rom size for the game long GameRomSize = 0; - foreach (Roms.GameRomItem gameRom in gameRoms) { + foreach (Roms.GameRomItem gameRom in gameRoms) + { GameRomSize += (long)gameRom.Size; } - if (collectionItem.MaximumBytesPerPlatform > 0) { - if ((TotalRomSize + GameRomSize) < collectionItem.MaximumBytesPerPlatform) { + if (collectionItem.MaximumBytesPerPlatform > 0) + { + if ((TotalRomSize + GameRomSize) < collectionItem.MaximumBytesPerPlatform) + { AddGame = true; } } - else + else { AddGame = true; } - if (AddGame == true) { + if (AddGame == true) + { TotalRomSize += GameRomSize; bool AddRoms = false; - if (collectionItem.MaximumRomsPerPlatform > 0) { - if (TotalGameCount < collectionItem.MaximumRomsPerPlatform) { + if (collectionItem.MaximumRomsPerPlatform > 0) + { + if (TotalGameCount < collectionItem.MaximumRomsPerPlatform) + { AddRoms = true; } } @@ -392,7 +412,8 @@ namespace gaseous_server.Classes AddRoms = true; } - if (AddRoms == true) { + if (AddRoms == true) + { TotalGameCount += 1; collectionGameItem.Roms = gameRoms; collectionPlatformItem.Games.Add(collectionGameItem); @@ -401,7 +422,8 @@ namespace gaseous_server.Classes } // handle age grouping - AgeGroups.AgeRestrictionGroupings CurrentAgeGroup = AgeGroups.GetAgeGroupFromAgeRatings(game.AgeRatings); + List gameAgeRatings = game.AgeRatings.Select(s => (AgeRating)s).ToList(); + AgeGroups.AgeRestrictionGroupings CurrentAgeGroup = AgeGroups.GetAgeGroupFromAgeRatings(gameAgeRatings); if (CurrentAgeGroup > AgeGrouping) { AgeGrouping = CurrentAgeGroup; @@ -469,14 +491,14 @@ namespace gaseous_server.Classes { "agu", collectionContents.ContainsUnclassifiedAgeGroup } }; db.ExecuteCMD(sql, dbDict); - + List collectionPlatformItems = collectionContents.Collection; string ZipFilePath = Path.Combine(Config.LibraryConfiguration.LibraryCollectionsDirectory, collectionItem.Id + collectionItem.ArchiveExtension); string ZipFileTempPath = Path.Combine(Config.LibraryConfiguration.LibraryTempDirectory, collectionItem.Id.ToString()); try { - + // clean up if needed if (File.Exists(ZipFilePath)) { @@ -500,11 +522,12 @@ namespace gaseous_server.Classes if (collectionItem.IncludeBIOSFiles == true) { List bios = Bios.GetBios(collectionPlatformItem.Id, true); - if (!Directory.Exists(ZipBiosPath)) { + if (!Directory.Exists(ZipBiosPath)) + { Directory.CreateDirectory(ZipBiosPath); } - foreach (Bios.BiosItem biosItem in bios) + foreach (Bios.BiosItem biosItem in bios) { if (File.Exists(biosItem.biosPath)) { @@ -573,8 +596,8 @@ namespace gaseous_server.Classes case CollectionItem.FolderStructures.RetroPie: ZipGamePath = ZipPlatformPath; break; - } - + } + // copy in roms foreach (Roms.GameRomItem gameRomItem in collectionGameItem.Roms) { @@ -590,7 +613,7 @@ namespace gaseous_server.Classes // compress to zip Logging.Log(Logging.LogType.Information, "Collections", "Compressing collection"); - switch(collectionItem.ArchiveType) + switch (collectionItem.ArchiveType) { case CollectionItem.ArchiveTypes.Zip: ZipFile.CreateFromDirectory(ZipFileTempPath, ZipFilePath, CompressionLevel.SmallestSize, false); @@ -601,10 +624,10 @@ namespace gaseous_server.Classes break; case CollectionItem.ArchiveTypes.SevenZip: - + break; } - + // clean up if (Directory.Exists(ZipFileTempPath)) @@ -639,7 +662,8 @@ namespace gaseous_server.Classes } } - private static CollectionItem BuildCollectionItem(DataRow row) { + private static CollectionItem BuildCollectionItem(DataRow row) + { string strPlatforms = (string)Common.ReturnValueIfNull(row["Platforms"], "[ ]"); string strGenres = (string)Common.ReturnValueIfNull(row["Genres"], "[ ]"); string strPlayers = (string)Common.ReturnValueIfNull(row["Players"], "[ ]"); @@ -704,7 +728,7 @@ namespace gaseous_server.Classes case ArchiveTypes.Zip: default: return ".zip"; - + case ArchiveTypes.RAR: return ".rar"; @@ -810,7 +834,8 @@ namespace gaseous_server.Classes } } - public class CollectionContents { + public class CollectionContents + { [JsonIgnore] public List Collection { get; set; } @@ -840,13 +865,16 @@ namespace gaseous_server.Classes public AgeGroups.AgeRestrictionGroupings AgeGroup { get; set; } public bool ContainsUnclassifiedAgeGroup { get; set; } - public class CollectionPlatformItem { - public CollectionPlatformItem(IGDB.Models.Platform platform) { + public class CollectionPlatformItem + { + public CollectionPlatformItem(Platform platform) + { string[] PropertyWhitelist = new string[] { "Id", "Name", "Slug" }; - PropertyInfo[] srcProperties = typeof(IGDB.Models.Platform).GetProperties(); + PropertyInfo[] srcProperties = typeof(Platform).GetProperties(); PropertyInfo[] dstProperties = typeof(CollectionPlatformItem).GetProperties(); - foreach (PropertyInfo srcProperty in srcProperties) { + foreach (PropertyInfo srcProperty in srcProperties) + { if (PropertyWhitelist.Contains(srcProperty.Name)) { foreach (PropertyInfo dstProperty in dstProperties) @@ -866,10 +894,13 @@ namespace gaseous_server.Classes public List Games { get; set; } - public int RomCount { - get { + public int RomCount + { + get + { int Counter = 0; - foreach (CollectionGameItem Game in Games) { + foreach (CollectionGameItem Game in Games) + { Counter += 1; } @@ -877,11 +908,15 @@ namespace gaseous_server.Classes } } - public long RomSize { - get { + public long RomSize + { + get + { long Size = 0; - foreach (CollectionGameItem Game in Games) { - foreach (Roms.GameRomItem Rom in Game.Roms) { + foreach (CollectionGameItem Game in Games) + { + foreach (Roms.GameRomItem Rom in Game.Roms) + { Size += (long)Rom.Size; } } @@ -904,29 +939,13 @@ namespace gaseous_server.Classes this.FirstReleaseDate = gameObject.FirstReleaseDate; this.AgeRatings = gameObject.AgeRatings; } - - public IGDB.Models.Cover? CoverItem + + public AgeGroups.AgeRestrictionGroupings AgeGrouping { get { - if (Cover != null) - { - IGDB.Models.Cover cover = Covers.GetCover(Cover.Id, Path.Combine(Config.LibraryConfiguration.LibraryMetadataDirectory, "Games", Slug), false); - - return cover; - } - else - { - return null; - } - } - } - - public AgeGroups.AgeRestrictionGroupings AgeGrouping - { - get - { - return AgeGroups.GetAgeGroupFromAgeRatings(this.AgeRatings); + List gameAgeRatings = this.AgeRatings.Select(s => (AgeRating)s).ToList(); + return AgeGroups.GetAgeGroupFromAgeRatings(gameAgeRatings); } } @@ -934,17 +953,20 @@ namespace gaseous_server.Classes public List Roms { get; set; } - public long RomSize { - get { - long Size = 0; - foreach (Roms.GameRomItem Rom in Roms) { - Size += (long)Rom.Size; + public long RomSize + { + get + { + long Size = 0; + foreach (Roms.GameRomItem Rom in Roms) + { + Size += (long)Rom.Size; + } + + return Size; } - - return Size; } } - } } } } diff --git a/gaseous-server/Classes/Config.cs b/gaseous-server/Classes/Config.cs index 22c0a58..88237f0 100644 --- a/gaseous-server/Classes/Config.cs +++ b/gaseous-server/Classes/Config.cs @@ -1,7 +1,6 @@ using System; using System.Data; using Newtonsoft.Json; -using IGDB.Models; using gaseous_server.Classes.Metadata; using NuGet.Common; @@ -623,21 +622,21 @@ namespace gaseous_server.Classes } } - public string LibraryMetadataDirectory_Platform(Platform platform) + public string LibraryMetadataDirectory_Platform(HasheousClient.Models.Metadata.IGDB.Platform platform) { string MetadataPath = Path.Combine(LibraryMetadataDirectory, "Platforms", platform.Slug); if (!Directory.Exists(MetadataPath)) { Directory.CreateDirectory(MetadataPath); } return MetadataPath; } - public string LibraryMetadataDirectory_Game(Game game) + public string LibraryMetadataDirectory_Game(gaseous_server.Models.Game game) { string MetadataPath = Path.Combine(LibraryMetadataDirectory, "Games", game.Slug); if (!Directory.Exists(MetadataPath)) { Directory.CreateDirectory(MetadataPath); } return MetadataPath; } - public string LibraryMetadataDirectory_Company(Company company) + public string LibraryMetadataDirectory_Company(HasheousClient.Models.Metadata.IGDB.Company company) { string MetadataPath = Path.Combine(LibraryMetadataDirectory, "Companies", company.Slug); if (!Directory.Exists(MetadataPath)) { Directory.CreateDirectory(MetadataPath); } diff --git a/gaseous-server/Classes/DatabaseMigration.cs b/gaseous-server/Classes/DatabaseMigration.cs index 0579abd..863041b 100644 --- a/gaseous-server/Classes/DatabaseMigration.cs +++ b/gaseous-server/Classes/DatabaseMigration.cs @@ -3,7 +3,6 @@ using System.Data; using System.Reflection; using gaseous_server.Classes.Metadata; using gaseous_server.Models; -using IGDB.Models; namespace gaseous_server.Classes { @@ -394,8 +393,8 @@ namespace gaseous_server.Classes (string)row["Path"] ); - Platform platform = Platforms.GetPlatform((long)row["PlatformId"], false); - Game game = Games.GetGame((long)row["GameId"], false, false, false); + HasheousClient.Models.Metadata.IGDB.Platform platform = Platforms.GetPlatform((long)row["PlatformId"]); + Game game = Games.GetGame(Communications.MetadataSource, (long)row["GameId"]); ImportGame.StoreROM(library, hash, game, platform, signature, (string)row["Path"], (long)row["Id"]); diff --git a/gaseous-server/Classes/FileSignature.cs b/gaseous-server/Classes/FileSignature.cs index 68f38b4..2869c62 100644 --- a/gaseous-server/Classes/FileSignature.cs +++ b/gaseous-server/Classes/FileSignature.cs @@ -342,7 +342,7 @@ namespace gaseous_server.Classes switch (metadataResult.Source) { case HasheousClient.Models.MetadataSources.IGDB: - signature.Flags.IGDBGameId = (long)Games.GetGame(metadataResult.Id, false, false, false).Id; + signature.Flags.IGDBGameId = (long)Games.GetGame(Communications.MetadataSource, metadataResult.Id).Id; break; } } diff --git a/gaseous-server/Classes/GameLibrary.cs b/gaseous-server/Classes/GameLibrary.cs index bc8f890..a6e389b 100644 --- a/gaseous-server/Classes/GameLibrary.cs +++ b/gaseous-server/Classes/GameLibrary.cs @@ -2,7 +2,6 @@ using System; using System.Data; using gaseous_server.Classes; using gaseous_server.Classes.Metadata; -using IGDB.Models; using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow; namespace gaseous_server @@ -237,7 +236,7 @@ namespace gaseous_server { if (_DefaultPlatformId != 0) { - Platform platform = Platforms.GetPlatform(_DefaultPlatformId); + HasheousClient.Models.Metadata.IGDB.Platform platform = Platforms.GetPlatform(_DefaultPlatformId); return platform.Name; } else diff --git a/gaseous-server/Classes/ImportGames.cs b/gaseous-server/Classes/ImportGames.cs index 8799e98..7c1db8c 100644 --- a/gaseous-server/Classes/ImportGames.cs +++ b/gaseous-server/Classes/ImportGames.cs @@ -7,12 +7,12 @@ using System.Text.RegularExpressions; using System.Threading.Tasks; using gaseous_server.Classes.Metadata; using gaseous_server.Models; -using IGDB.Models; using NuGet.Common; using NuGet.LibraryModel; using static gaseous_server.Classes.Metadata.Games; using static gaseous_server.Classes.FileSignature; using HasheousClient.Models; +using HasheousClient.Models.Metadata.IGDB; namespace gaseous_server.Classes { @@ -47,7 +47,7 @@ namespace gaseous_server.Classes } } - public Dictionary ImportGameFile(string GameFileImportPath, IGDB.Models.Platform? OverridePlatform) + public Dictionary ImportGameFile(string GameFileImportPath, Platform? OverridePlatform) { Dictionary RetVal = new Dictionary(); RetVal.Add("path", Path.GetFileName(GameFileImportPath)); @@ -110,13 +110,13 @@ namespace gaseous_server.Classes gaseous_server.Models.Signatures_Games discoveredSignature = fileSignature.GetFileSignature(GameLibrary.GetDefaultLibrary, hash, fi, GameFileImportPath); // get discovered platform - IGDB.Models.Platform? determinedPlatform = null; + Platform? determinedPlatform = null; if (OverridePlatform == null) { determinedPlatform = Metadata.Platforms.GetPlatform(discoveredSignature.Flags.IGDBPlatformId); if (determinedPlatform == null) { - determinedPlatform = new IGDB.Models.Platform(); + determinedPlatform = new Platform(); } } else @@ -126,7 +126,7 @@ namespace gaseous_server.Classes discoveredSignature.Flags.IGDBPlatformName = determinedPlatform.Name; } - IGDB.Models.Game determinedGame = SearchForGame(discoveredSignature, discoveredSignature.Flags.IGDBPlatformId, true); + gaseous_server.Models.Game determinedGame = SearchForGame(discoveredSignature, discoveredSignature.Flags.IGDBPlatformId, true); // add to database long RomId = StoreROM(GameLibrary.GetDefaultLibrary, hash, determinedGame, determinedPlatform, discoveredSignature, GameFileImportPath, 0, true); @@ -157,7 +157,7 @@ namespace gaseous_server.Classes File.Move(GameFileImportPath, biosItem.biosPath, true); RetVal.Add("name", biosItem.filename); - RetVal.Add("platform", Platforms.GetPlatform(biosItem.platformid, false, false)); + RetVal.Add("platform", Platforms.GetPlatform(biosItem.platformid)); RetVal["status"] = "imported"; return RetVal; @@ -178,7 +178,7 @@ namespace gaseous_server.Classes return RetVal; } - public static IGDB.Models.Game SearchForGame(gaseous_server.Models.Signatures_Games Signature, long PlatformId, bool FullDownload) + public static gaseous_server.Models.Game SearchForGame(gaseous_server.Models.Signatures_Games Signature, long PlatformId, bool FullDownload) { if (Signature.Flags != null) { @@ -187,7 +187,7 @@ namespace gaseous_server.Classes // game was determined elsewhere - probably a Hasheous server try { - return Games.GetGame(Signature.Flags.IGDBGameId, false, false, FullDownload); + return Games.GetGame(Communications.MetadataSource, Signature.Flags.IGDBGameId); } catch (Exception ex) { @@ -197,7 +197,7 @@ namespace gaseous_server.Classes } // search discovered game - case insensitive exact match first - IGDB.Models.Game determinedGame = new IGDB.Models.Game(); + gaseous_server.Models.Game determinedGame = new gaseous_server.Models.Game(); string GameName = Signature.Game.Name; @@ -212,13 +212,13 @@ namespace gaseous_server.Classes foreach (Metadata.Games.SearchType searchType in Enum.GetValues(typeof(Metadata.Games.SearchType))) { Logging.Log(Logging.LogType.Information, "Import Game", " Search type: " + searchType.ToString()); - IGDB.Models.Game[] games = Metadata.Games.SearchForGame(SearchCandidate, PlatformId, searchType); + gaseous_server.Models.Game[] games = Metadata.Games.SearchForGame(SearchCandidate, PlatformId, searchType); if (games != null) { if (games.Length == 1) { // exact match! - determinedGame = Metadata.Games.GetGame((long)games[0].Id, false, false, false); + determinedGame = Metadata.Games.GetGame(Communications.MetadataSource, (long)games[0].Id); Logging.Log(Logging.LogType.Information, "Import Game", " IGDB game: " + determinedGame.Name); GameFound = true; break; @@ -228,12 +228,12 @@ namespace gaseous_server.Classes Logging.Log(Logging.LogType.Information, "Import Game", " " + games.Length + " search results found"); // quite likely we've found sequels and alternate types - foreach (Game game in games) + foreach (gaseous_server.Models.Game game in games) { if (game.Name == SearchCandidate) { // found game title matches the search candidate - determinedGame = Metadata.Games.GetGame((long)games[0].Id, false, false, false); + determinedGame = Metadata.Games.GetGame(Communications.MetadataSource, (long)games[0].Id); Logging.Log(Logging.LogType.Information, "Import Game", "Found exact match!"); GameFound = true; break; @@ -254,7 +254,7 @@ namespace gaseous_server.Classes } if (determinedGame == null) { - determinedGame = new IGDB.Models.Game(); + determinedGame = new gaseous_server.Models.Game(); } string destSlug = ""; @@ -266,9 +266,9 @@ namespace gaseous_server.Classes return determinedGame; } - public static List SearchForGame_GetAll(string GameName, long PlatformId) + public static List SearchForGame_GetAll(string GameName, long PlatformId) { - List searchResults = new List(); + List searchResults = new List(); List SearchCandidates = GetSearchCandidates(GameName); @@ -278,11 +278,11 @@ namespace gaseous_server.Classes { if ((PlatformId == 0 && searchType == SearchType.searchNoPlatform) || (PlatformId != 0 && searchType != SearchType.searchNoPlatform)) { - IGDB.Models.Game[] games = Metadata.Games.SearchForGame(SearchCandidate, PlatformId, searchType); - foreach (IGDB.Models.Game foundGame in games) + gaseous_server.Models.Game[] games = Metadata.Games.SearchForGame(SearchCandidate, PlatformId, searchType); + foreach (gaseous_server.Models.Game foundGame in games) { bool gameInResults = false; - foreach (IGDB.Models.Game searchResult in searchResults) + foreach (gaseous_server.Models.Game searchResult in searchResults) { if (searchResult.Id == foundGame.Id) { @@ -333,7 +333,7 @@ namespace gaseous_server.Classes return SearchCandidates; } - public static long StoreROM(GameLibrary.LibraryItem library, Common.hashObject hash, IGDB.Models.Game determinedGame, IGDB.Models.Platform determinedPlatform, gaseous_server.Models.Signatures_Games discoveredSignature, string GameFileImportPath, long UpdateId = 0, bool SourceIsExternal = false) + public static long StoreROM(GameLibrary.LibraryItem library, Common.hashObject hash, gaseous_server.Models.Game determinedGame, Platform determinedPlatform, gaseous_server.Models.Signatures_Games discoveredSignature, string GameFileImportPath, long UpdateId = 0, bool SourceIsExternal = false) { Database db = new Database(Database.databaseType.MySql, Config.DatabaseConfiguration.ConnectionString); @@ -415,8 +415,8 @@ namespace gaseous_server.Classes Classes.Roms.GameRomItem rom = Classes.Roms.GetRom(RomId); // get metadata - IGDB.Models.Platform platform = gaseous_server.Classes.Metadata.Platforms.GetPlatform(rom.PlatformId); - IGDB.Models.Game game = gaseous_server.Classes.Metadata.Games.GetGame(rom.GameId, false, false, false); + Platform platform = gaseous_server.Classes.Metadata.Platforms.GetPlatform(rom.PlatformId); + gaseous_server.Models.Game game = gaseous_server.Classes.Metadata.Games.GetGame(Communications.MetadataSource, rom.GameId); // build path string platformSlug = "Unknown Platform"; @@ -728,7 +728,7 @@ namespace gaseous_server.Classes { // get discovered platform long PlatformId; - IGDB.Models.Platform determinedPlatform; + Platform determinedPlatform; if (sig.Flags.IGDBPlatformId == null || sig.Flags.IGDBPlatformId == 0) { @@ -742,7 +742,7 @@ namespace gaseous_server.Classes } determinedPlatform = Platforms.GetPlatform(PlatformId); - IGDB.Models.Game determinedGame = SearchForGame(sig, PlatformId, true); + gaseous_server.Models.Game determinedGame = SearchForGame(sig, PlatformId, true); StoreROM(library, hash, determinedGame, determinedPlatform, sig, LibraryFile); } @@ -854,7 +854,7 @@ namespace gaseous_server.Classes // get discovered platform long PlatformId; - IGDB.Models.Platform determinedPlatform; + Platform determinedPlatform; if (sig.Flags.IGDBPlatformId == null || sig.Flags.IGDBPlatformId == 0) { @@ -868,7 +868,7 @@ namespace gaseous_server.Classes } determinedPlatform = Platforms.GetPlatform(PlatformId); - IGDB.Models.Game determinedGame = SearchForGame(sig, PlatformId, true); + gaseous_server.Models.Game determinedGame = SearchForGame(sig, PlatformId, true); StoreROM(library, hash, determinedGame, determinedPlatform, sig, romPath, romId); diff --git a/gaseous-server/Classes/Metadata/AgeGroups.cs b/gaseous-server/Classes/Metadata/AgeGroups.cs index bc7e49d..ac92f9b 100644 --- a/gaseous-server/Classes/Metadata/AgeGroups.cs +++ b/gaseous-server/Classes/Metadata/AgeGroups.cs @@ -1,8 +1,8 @@ using System; using System.Reflection; using System.Text.Json.Serialization; -using IGDB; -using IGDB.Models; +using gaseous_server.Models; +using HasheousClient.Models.Metadata.IGDB; using Microsoft.CodeAnalysis.Classification; namespace gaseous_server.Classes.Metadata @@ -14,7 +14,7 @@ namespace gaseous_server.Classes.Metadata } - public static AgeGroup? GetAgeGroup(Game? game) + public static AgeGroup? GetAgeGroup(Models.Game? game) { if (game == null) { @@ -23,7 +23,7 @@ namespace gaseous_server.Classes.Metadata else { Storage.CacheStatus? cacheStatus = new Storage.CacheStatus(); - cacheStatus = Storage.GetCacheStatus("AgeGroup", (long)game.Id); + cacheStatus = Storage.GetCacheStatus(Communications.MetadataSource, "AgeGroup", (long)game.Id); AgeGroup? RetVal = new AgeGroup(); @@ -31,16 +31,16 @@ namespace gaseous_server.Classes.Metadata { case Storage.CacheStatus.NotPresent: RetVal = _GetAgeGroup(game); - Storage.NewCacheValue(RetVal, false); + Storage.NewCacheValue(Communications.MetadataSource, RetVal, false); break; case Storage.CacheStatus.Expired: RetVal = _GetAgeGroup(game); - Storage.NewCacheValue(RetVal, true); + Storage.NewCacheValue(Communications.MetadataSource, RetVal, true); break; case Storage.CacheStatus.Current: - RetVal = Storage.GetCacheValue(RetVal, "Id", game.Id); + RetVal = Storage.GetCacheValue(Communications.MetadataSource, RetVal, "Id", game.Id); break; default: @@ -51,20 +51,20 @@ namespace gaseous_server.Classes.Metadata } } - public static AgeGroup? _GetAgeGroup(Game game) + public static AgeGroup? _GetAgeGroup(Models.Game game) { // compile the maximum age group for the given game if (game != null) { if (game.AgeRatings != null) { - if (game.AgeRatings.Ids != null) + if (game.AgeRatings != null) { // collect ratings values from metadata List ageRatings = new List(); - foreach (long ratingId in game.AgeRatings.Ids) + foreach (long ratingId in game.AgeRatings) { - AgeRating? rating = AgeRatings.GetAgeRatings(ratingId); + AgeRating? rating = AgeRatings.GetAgeRating(game.MetadataSource, ratingId); if (rating != null) { ageRatings.Add(rating); @@ -262,13 +262,13 @@ namespace gaseous_server.Classes.Metadata public class AgeGroupItem { - public List ACB { get; set; } - public List CERO { get; set; } - public List CLASS_IND { get; set; } - public List ESRB { get; set; } - public List GRAC { get; set; } - public List PEGI { get; set; } - public List USK { get; set; } + public List ACB { get; set; } + public List CERO { get; set; } + public List CLASS_IND { get; set; } + public List ESRB { get; set; } + public List GRAC { get; set; } + public List PEGI { get; set; } + public List USK { get; set; } [JsonIgnore] [Newtonsoft.Json.JsonIgnore] diff --git a/gaseous-server/Classes/Metadata/AgeRating.cs b/gaseous-server/Classes/Metadata/AgeRating.cs index 18b88d1..597a7bc 100644 --- a/gaseous-server/Classes/Metadata/AgeRating.cs +++ b/gaseous-server/Classes/Metadata/AgeRating.cs @@ -2,8 +2,7 @@ using System.Buffers; using System.Reflection; using System.Text.Json.Serialization; -using IGDB; -using IGDB.Models; +using HasheousClient.Models.Metadata.IGDB; using Microsoft.CodeAnalysis.Classification; namespace gaseous_server.Classes.Metadata @@ -16,7 +15,7 @@ namespace gaseous_server.Classes.Metadata { } - public static AgeRating? GetAgeRatings(long? Id) + public static AgeRating? GetAgeRating(HasheousClient.Models.MetadataModel.MetadataSources SourceType, long? Id) { if ((Id == 0) || (Id == null)) { @@ -24,72 +23,16 @@ namespace gaseous_server.Classes.Metadata } else { - Task RetVal = _GetAgeRatings((long)Id); - return RetVal.Result; + AgeRating? RetVal = Metadata.GetMetadata(SourceType, (long)Id, false); + return RetVal; } } - private static async Task _GetAgeRatings(long searchValue) - { - // check database first - Storage.CacheStatus? cacheStatus = Storage.GetCacheStatus("AgeRating", (long)searchValue); - - AgeRating returnValue = new AgeRating(); - switch (cacheStatus) - { - case Storage.CacheStatus.NotPresent: - returnValue = await GetObjectFromServer(searchValue); - Storage.NewCacheValue(returnValue); - UpdateSubClasses(returnValue); - break; - case Storage.CacheStatus.Expired: - try - { - returnValue = await GetObjectFromServer(searchValue); - Storage.NewCacheValue(returnValue, true); - } - catch (Exception ex) - { - Logging.Log(Logging.LogType.Warning, "Metadata: " + returnValue.GetType().Name, "An error occurred while connecting to IGDB. Id: " + searchValue, ex); - returnValue = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - } - break; - case Storage.CacheStatus.Current: - returnValue = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - break; - default: - throw new Exception("How did you get here?"); - } - - return returnValue; - } - - private static void UpdateSubClasses(AgeRating ageRating) - { - if (ageRating.ContentDescriptions != null) - { - foreach (long AgeRatingContentDescriptionId in ageRating.ContentDescriptions.Ids) - { - AgeRatingContentDescription ageRatingContentDescription = AgeRatingContentDescriptions.GetAgeRatingContentDescriptions(AgeRatingContentDescriptionId); - } - } - } - - private static async Task GetObjectFromServer(long searchValue) - { - // get AgeRatings metadata - Communications comms = new Communications(); - var results = await comms.APIComm(Communications.MetadataEndpoint.AgeRating, searchValue); - var result = results.First(); - - return result; - } - - public static GameAgeRating GetConsolidatedAgeRating(long RatingId) + public static GameAgeRating GetConsolidatedAgeRating(HasheousClient.Models.MetadataModel.MetadataSources SourceType, long RatingId) { GameAgeRating gameAgeRating = new GameAgeRating(); - AgeRating ageRating = GetAgeRatings(RatingId); + AgeRating ageRating = GetAgeRating(SourceType, RatingId); gameAgeRating.Id = (long)ageRating.Id; gameAgeRating.RatingBoard = (AgeRatingCategory)ageRating.Category; gameAgeRating.RatingTitle = (AgeRatingTitle)ageRating.Rating; @@ -97,9 +40,9 @@ namespace gaseous_server.Classes.Metadata List descriptions = new List(); if (ageRating.ContentDescriptions != null) { - foreach (long ContentId in ageRating.ContentDescriptions.Ids) + foreach (long ContentId in ageRating.ContentDescriptions) { - AgeRatingContentDescription ageRatingContentDescription = AgeRatingContentDescriptions.GetAgeRatingContentDescriptions(ContentId); + AgeRatingContentDescription ageRatingContentDescription = AgeRatingContentDescriptions.GetAgeRatingContentDescriptions(SourceType, ContentId); descriptions.Add(ageRatingContentDescription.Description); } } diff --git a/gaseous-server/Classes/Metadata/AgeRatingContentDescriptions.cs b/gaseous-server/Classes/Metadata/AgeRatingContentDescriptions.cs index 596c70b..0be7086 100644 --- a/gaseous-server/Classes/Metadata/AgeRatingContentDescriptions.cs +++ b/gaseous-server/Classes/Metadata/AgeRatingContentDescriptions.cs @@ -1,6 +1,5 @@ using System; -using IGDB; -using IGDB.Models; +using HasheousClient.Models.Metadata.IGDB; namespace gaseous_server.Classes.Metadata @@ -13,7 +12,7 @@ namespace gaseous_server.Classes.Metadata { } - public static AgeRatingContentDescription? GetAgeRatingContentDescriptions(long? Id) + public static AgeRatingContentDescription? GetAgeRatingContentDescriptions(HasheousClient.Models.MetadataModel.MetadataSources SourceType, long? Id) { if ((Id == 0) || (Id == null)) { @@ -21,54 +20,10 @@ namespace gaseous_server.Classes.Metadata } else { - Task RetVal = _GetAgeRatingContentDescriptions((long)Id); - return RetVal.Result; + AgeRatingContentDescription? RetVal = Metadata.GetMetadata(SourceType, (long)Id, false); + return RetVal; } } - - private static async Task _GetAgeRatingContentDescriptions(long searchValue) - { - // check database first - Storage.CacheStatus? cacheStatus = Storage.GetCacheStatus("AgeRatingContentDescription", searchValue); - - AgeRatingContentDescription returnValue = new AgeRatingContentDescription(); - switch (cacheStatus) - { - case Storage.CacheStatus.NotPresent: - returnValue = await GetObjectFromServer(searchValue); - Storage.NewCacheValue(returnValue); - break; - case Storage.CacheStatus.Expired: - try - { - returnValue = await GetObjectFromServer(searchValue); - Storage.NewCacheValue(returnValue, true); - } - catch (Exception ex) - { - Logging.Log(Logging.LogType.Warning, "Metadata: " + returnValue.GetType().Name, "An error occurred while connecting to IGDB. Id: " + searchValue, ex); - returnValue = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - } - break; - case Storage.CacheStatus.Current: - returnValue = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - break; - default: - throw new Exception("How did you get here?"); - } - - return returnValue; - } - - private static async Task GetObjectFromServer(long searchValue) - { - // get AgeRatingContentDescriptionContentDescriptions metadata - Communications comms = new Communications(); - var results = await comms.APIComm(Communications.MetadataEndpoint.AgeRatingContentDescription, searchValue); - var result = results.First(); - - return result; - } } } diff --git a/gaseous-server/Classes/Metadata/AlternativeNames.cs b/gaseous-server/Classes/Metadata/AlternativeNames.cs index d8543b5..9163d46 100644 --- a/gaseous-server/Classes/Metadata/AlternativeNames.cs +++ b/gaseous-server/Classes/Metadata/AlternativeNames.cs @@ -1,6 +1,5 @@ using System; -using IGDB; -using IGDB.Models; +using HasheousClient.Models.Metadata.IGDB; namespace gaseous_server.Classes.Metadata @@ -13,7 +12,7 @@ namespace gaseous_server.Classes.Metadata { } - public static AlternativeName? GetAlternativeNames(long? Id) + public static AlternativeName? GetAlternativeNames(HasheousClient.Models.MetadataModel.MetadataSources SourceType, long? Id) { if ((Id == 0) || (Id == null)) { @@ -21,54 +20,10 @@ namespace gaseous_server.Classes.Metadata } else { - Task RetVal = _GetAlternativeNames((long)Id); - return RetVal.Result; + AlternativeName? RetVal = Metadata.GetMetadata(SourceType, (long)Id, false); + return RetVal; } } - - private static async Task _GetAlternativeNames(long searchValue) - { - // check database first - Storage.CacheStatus? cacheStatus = Storage.GetCacheStatus("AlternativeName", searchValue); - - AlternativeName returnValue = new AlternativeName(); - switch (cacheStatus) - { - case Storage.CacheStatus.NotPresent: - returnValue = await GetObjectFromServer(searchValue); - Storage.NewCacheValue(returnValue); - break; - case Storage.CacheStatus.Expired: - try - { - returnValue = await GetObjectFromServer(searchValue); - Storage.NewCacheValue(returnValue, true); - } - catch (Exception ex) - { - Logging.Log(Logging.LogType.Warning, "Metadata: " + returnValue.GetType().Name, "An error occurred while connecting to IGDB. Id: " + searchValue, ex); - returnValue = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - } - break; - case Storage.CacheStatus.Current: - returnValue = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - break; - default: - throw new Exception("How did you get here?"); - } - - return returnValue; - } - - private static async Task GetObjectFromServer(long searchValue) - { - // get AlternativeNames metadata - Communications comms = new Communications(); - var results = await comms.APIComm(Communications.MetadataEndpoint.AlternativeName, searchValue); - var result = results.First(); - - return result; - } } } diff --git a/gaseous-server/Classes/Metadata/Artworks.cs b/gaseous-server/Classes/Metadata/Artworks.cs index 982a8b4..3326cc5 100644 --- a/gaseous-server/Classes/Metadata/Artworks.cs +++ b/gaseous-server/Classes/Metadata/Artworks.cs @@ -1,7 +1,5 @@ using System; -using IGDB; -using IGDB.Models; - +using HasheousClient.Models.Metadata.IGDB; namespace gaseous_server.Classes.Metadata { @@ -13,7 +11,7 @@ namespace gaseous_server.Classes.Metadata { } - public static Artwork? GetArtwork(long? Id, string ImagePath, bool GetImages) + public static Artwork? GetArtwork(HasheousClient.Models.MetadataModel.MetadataSources SourceType, long? Id) { if ((Id == 0) || (Id == null)) { @@ -21,75 +19,10 @@ namespace gaseous_server.Classes.Metadata } else { - Task RetVal = _GetArtwork((long)Id, ImagePath, GetImages); - return RetVal.Result; + Artwork? RetVal = Metadata.GetMetadata(SourceType, (long)Id, false); + return RetVal; } } - - private static async Task _GetArtwork(long searchValue, string ImagePath, bool GetImages = true) - { - // check database first - Storage.CacheStatus? cacheStatus = Storage.GetCacheStatus("Artwork", searchValue); - - Artwork returnValue = new Artwork(); - bool forceImageDownload = false; - ImagePath = Path.Combine(ImagePath, "Artwork"); - switch (cacheStatus) - { - case Storage.CacheStatus.NotPresent: - returnValue = await GetObjectFromServer(searchValue, ImagePath); - Storage.NewCacheValue(returnValue); - forceImageDownload = true; - break; - case Storage.CacheStatus.Expired: - try - { - returnValue = await GetObjectFromServer(searchValue, ImagePath); - Storage.NewCacheValue(returnValue, true); - - // check if old value is different from the new value - only download if it's different - Artwork oldImage = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - if (oldImage.ImageId != returnValue.ImageId) - { - forceImageDownload = true; - } - } - catch (Exception ex) - { - Logging.Log(Logging.LogType.Warning, "Metadata: " + returnValue.GetType().Name, "An error occurred while connecting to IGDB. Id: " + searchValue, ex); - returnValue = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - } - break; - case Storage.CacheStatus.Current: - returnValue = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - break; - default: - throw new Exception("How did you get here?"); - } - - if (GetImages == true) - { - if (forceImageDownload == true) - { - Logging.Log(Logging.LogType.Information, "Metadata: " + returnValue.GetType().Name, "Artwork download forced."); - - Communications comms = new Communications(); - comms.GetSpecificImageFromServer(ImagePath, returnValue.ImageId, Communications.IGDBAPI_ImageSize.original, null); - } - } - - return returnValue; - } - - private static async Task GetObjectFromServer(long searchValue, string ImagePath) - { - // get Artwork metadata - Communications comms = new Communications(); - var results = await comms.APIComm(Communications.MetadataEndpoint.Artwork, searchValue); - var result = results.First(); - - return result; - } } } diff --git a/gaseous-server/Classes/Metadata/Collections.cs b/gaseous-server/Classes/Metadata/Collections.cs index 2f9682d..2adb518 100644 --- a/gaseous-server/Classes/Metadata/Collections.cs +++ b/gaseous-server/Classes/Metadata/Collections.cs @@ -1,7 +1,5 @@ using System; -using IGDB; -using IGDB.Models; - +using HasheousClient.Models.Metadata.IGDB; namespace gaseous_server.Classes.Metadata { @@ -13,7 +11,7 @@ namespace gaseous_server.Classes.Metadata { } - public static Collection? GetCollections(long? Id) + public static Collection? GetCollections(HasheousClient.Models.MetadataModel.MetadataSources SourceType, long? Id) { if ((Id == 0) || (Id == null)) { @@ -21,54 +19,10 @@ namespace gaseous_server.Classes.Metadata } else { - Task RetVal = _GetCollections((long)Id); - return RetVal.Result; + Collection? RetVal = Metadata.GetMetadata(SourceType, (long)Id, false); + return RetVal; } } - - private static async Task _GetCollections(long searchValue) - { - // check database first - Storage.CacheStatus? cacheStatus = Storage.GetCacheStatus("Collection", searchValue); - - Collection returnValue = new Collection(); - switch (cacheStatus) - { - case Storage.CacheStatus.NotPresent: - returnValue = await GetObjectFromServer(searchValue); - Storage.NewCacheValue(returnValue); - break; - case Storage.CacheStatus.Expired: - try - { - returnValue = await GetObjectFromServer(searchValue); - Storage.NewCacheValue(returnValue, true); - } - catch (Exception ex) - { - Logging.Log(Logging.LogType.Warning, "Metadata: " + returnValue.GetType().Name, "An error occurred while connecting to IGDB. Id: " + searchValue, ex); - returnValue = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - } - break; - case Storage.CacheStatus.Current: - returnValue = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - break; - default: - throw new Exception("How did you get here?"); - } - - return returnValue; - } - - private static async Task GetObjectFromServer(long searchValue) - { - // get Collections metadata - Communications comms = new Communications(); - var results = await comms.APIComm(Communications.MetadataEndpoint.Collection, searchValue); - var result = results.First(); - - return result; - } } } diff --git a/gaseous-server/Classes/Metadata/Communications.cs b/gaseous-server/Classes/Metadata/Communications.cs index d1eb14a..43ec8fa 100644 --- a/gaseous-server/Classes/Metadata/Communications.cs +++ b/gaseous-server/Classes/Metadata/Communications.cs @@ -211,7 +211,7 @@ namespace gaseous_server.Classes.Metadata } /// - /// Request data from the metadata API using a slug + /// Request data from the metadata API using a slug using the default source /// /// /// The type of object to return @@ -227,7 +227,27 @@ namespace gaseous_server.Classes.Metadata /// public async Task APIComm(MetadataEndpoint Endpoint, string Slug) { - switch (_MetadataSource) + return await APIComm(_MetadataSource, Endpoint, Slug); + } + + /// + /// Request data from the metadata API using a slug + /// + /// + /// The type of object to return + /// + /// + /// The endpoint to access - can only be either Platform or Game + /// + /// + /// The slug to query for + /// + /// + /// The object requested + /// + public async Task APIComm(HasheousClient.Models.MetadataModel.MetadataSources SourceType, MetadataEndpoint Endpoint, string Slug) + { + switch (SourceType) { case HasheousClient.Models.MetadataModel.MetadataSources.None: return null; @@ -266,7 +286,7 @@ namespace gaseous_server.Classes.Metadata } /// - /// Request data from the metadata API using an id + /// Request data from the metadata API using an id using the default source /// /// /// The type of object to return @@ -282,7 +302,30 @@ namespace gaseous_server.Classes.Metadata /// public async Task APIComm(MetadataEndpoint Endpoint, long Id) { - switch (_MetadataSource) + return await APIComm(_MetadataSource, Endpoint, Id); + } + + /// + /// Request data from the metadata API using an id + /// + /// + /// The type of object to return + /// + /// + /// The source of the metadata + /// + /// + /// The endpoint to access + /// + /// + /// The Id to query for + /// + /// + /// The object requested + /// + public async Task APIComm(HasheousClient.Models.MetadataModel.MetadataSources SourceType, MetadataEndpoint Endpoint, long Id) + { + switch (SourceType) { case HasheousClient.Models.MetadataModel.MetadataSources.None: return null; @@ -874,14 +917,17 @@ namespace gaseous_server.Classes.Metadata if (property.PropertyType.IsEnum) { // check if property is null - if (input.GetType().GetProperty(property.Name).GetValue(input) != null) + if (input.GetType().GetProperty(property.Name) != null) { - // get the enum type - Type enumType = property.PropertyType; - // get the enum value - object enumValue = Enum.Parse(enumType, input.GetType().GetProperty(property.Name).GetValue(input).ToString()); - // set the enum value - property.SetValue(output, enumValue); + if (input.GetType().GetProperty(property.Name).GetValue(input) != null) + { + // get the enum type + Type enumType = property.PropertyType; + // get the enum value + object enumValue = Enum.Parse(enumType, input.GetType().GetProperty(property.Name).GetValue(input).ToString()); + // set the enum value + property.SetValue(output, enumValue); + } } } else if (Common.IsNullableEnum(property.PropertyType)) diff --git a/gaseous-server/Classes/Metadata/Company.cs b/gaseous-server/Classes/Metadata/Company.cs index df0103c..74c68a3 100644 --- a/gaseous-server/Classes/Metadata/Company.cs +++ b/gaseous-server/Classes/Metadata/Company.cs @@ -1,6 +1,5 @@ using System; -using IGDB; -using IGDB.Models; +using HasheousClient.Models.Metadata.IGDB; namespace gaseous_server.Classes.Metadata { @@ -12,7 +11,7 @@ namespace gaseous_server.Classes.Metadata { } - public static Company? GetCompanies(long? Id) + public static Company? GetCompanies(HasheousClient.Models.MetadataModel.MetadataSources SourceType, long? Id) { if ((Id == 0) || (Id == null)) { @@ -20,71 +19,10 @@ namespace gaseous_server.Classes.Metadata } else { - Task RetVal = _GetCompanies((long)Id); - return RetVal.Result; + Company? RetVal = Metadata.GetMetadata(SourceType, (long)Id, false); + return RetVal; } } - - private static async Task _GetCompanies(long searchValue) - { - // check database first - Storage.CacheStatus? cacheStatus = Storage.GetCacheStatus("Company", searchValue); - - Company returnValue = new Company(); - switch (cacheStatus) - { - case Storage.CacheStatus.NotPresent: - returnValue = await GetObjectFromServer(searchValue); - if (returnValue != null) { Storage.NewCacheValue(returnValue); } - UpdateSubClasses(returnValue); - break; - case Storage.CacheStatus.Expired: - try - { - returnValue = await GetObjectFromServer(searchValue); - Storage.NewCacheValue(returnValue, true); - } - catch (Exception ex) - { - Logging.Log(Logging.LogType.Warning, "Metadata: " + returnValue.GetType().Name, "An error occurred while connecting to IGDB. Id: " + searchValue, ex); - returnValue = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - } - break; - case Storage.CacheStatus.Current: - returnValue = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - break; - default: - throw new Exception("How did you get here?"); - } - - return returnValue; - } - - private static void UpdateSubClasses(Company company) - { - if (company.Logo != null) - { - CompanyLogo companyLogo = CompanyLogos.GetCompanyLogo(company.Logo.Id, Config.LibraryConfiguration.LibraryMetadataDirectory_Company(company)); - } - } - - private static async Task GetObjectFromServer(long searchValue) - { - // get Companies metadata - Communications comms = new Communications(); - var results = await comms.APIComm(Communications.MetadataEndpoint.Company, searchValue); - if (results.Length > 0) - { - var result = results.First(); - - return result; - } - else - { - return null; - } - - } } } diff --git a/gaseous-server/Classes/Metadata/CompanyLogos.cs b/gaseous-server/Classes/Metadata/CompanyLogos.cs index 6de72fe..6dd91a9 100644 --- a/gaseous-server/Classes/Metadata/CompanyLogos.cs +++ b/gaseous-server/Classes/Metadata/CompanyLogos.cs @@ -1,7 +1,5 @@ using System; -using IGDB; -using IGDB.Models; - +using HasheousClient.Models.Metadata.IGDB; namespace gaseous_server.Classes.Metadata { @@ -21,74 +19,10 @@ namespace gaseous_server.Classes.Metadata } else { - Task RetVal = _GetCompanyLogo((long)Id, ImagePath); - return RetVal.Result; + CompanyLogo? RetVal = Metadata.GetMetadata((long)Id, false); + return RetVal; } } - - private static async Task _GetCompanyLogo(long searchValue, string ImagePath) - { - // check database first - Storage.CacheStatus? cacheStatus = Storage.GetCacheStatus("CompanyLogo", searchValue); - - CompanyLogo returnValue = new CompanyLogo(); - bool forceImageDownload = false; - switch (cacheStatus) - { - case Storage.CacheStatus.NotPresent: - returnValue = await GetObjectFromServer(searchValue, ImagePath); - if (returnValue != null) - { - Storage.NewCacheValue(returnValue); - forceImageDownload = true; - } - break; - case Storage.CacheStatus.Expired: - try - { - returnValue = await GetObjectFromServer(searchValue, ImagePath); - Storage.NewCacheValue(returnValue, true); - - // check if old value is different from the new value - only download if it's different - CompanyLogo oldImage = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - if (oldImage.ImageId != returnValue.ImageId) - { - forceImageDownload = true; - } - } - catch (Exception ex) - { - Logging.Log(Logging.LogType.Warning, "Metadata: " + returnValue.GetType().Name, "An error occurred while connecting to IGDB. Id: " + searchValue, ex); - returnValue = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - } - break; - case Storage.CacheStatus.Current: - returnValue = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - break; - default: - throw new Exception("How did you get here?"); - } - - if (forceImageDownload == true) - { - Logging.Log(Logging.LogType.Information, "Metadata: " + returnValue.GetType().Name, "Company logo download forced."); - - Communications comms = new Communications(); - comms.GetSpecificImageFromServer(ImagePath, returnValue.ImageId, Communications.IGDBAPI_ImageSize.original, null); - } - - return returnValue; - } - - private static async Task GetObjectFromServer(long searchValue, string ImagePath) - { - // get Artwork metadata - Communications comms = new Communications(); - var results = await comms.APIComm(Communications.MetadataEndpoint.CompanyLogo, searchValue); - var result = results.First(); - - return result; - } } } diff --git a/gaseous-server/Classes/Metadata/Covers.cs b/gaseous-server/Classes/Metadata/Covers.cs index d567374..c5da931 100644 --- a/gaseous-server/Classes/Metadata/Covers.cs +++ b/gaseous-server/Classes/Metadata/Covers.cs @@ -1,9 +1,5 @@ using System; -using System.Net; -using IGDB; -using IGDB.Models; -using Microsoft.CodeAnalysis.Elfie.Model.Strings; - +using HasheousClient.Models.Metadata.IGDB; namespace gaseous_server.Classes.Metadata { @@ -15,7 +11,7 @@ namespace gaseous_server.Classes.Metadata { } - public static Cover? GetCover(long? Id, string ImagePath, bool GetImages) + public static Cover? GetCover(HasheousClient.Models.MetadataModel.MetadataSources SourceType, long? Id) { if ((Id == 0) || (Id == null)) { @@ -23,75 +19,10 @@ namespace gaseous_server.Classes.Metadata } else { - Task RetVal = _GetCover((long)Id, ImagePath, GetImages); - return RetVal.Result; + Cover? RetVal = Metadata.GetMetadata(SourceType, (long)Id, false); + return RetVal; } } - - private static async Task _GetCover(long searchValue, string ImagePath, bool GetImages = true) - { - // check database first - Storage.CacheStatus? cacheStatus = Storage.GetCacheStatus("Cover", searchValue); - - Cover returnValue = new Cover(); - bool forceImageDownload = false; - ImagePath = Path.Combine(ImagePath, "Covers"); - switch (cacheStatus) - { - case Storage.CacheStatus.NotPresent: - returnValue = await GetObjectFromServer(searchValue, ImagePath); - Storage.NewCacheValue(returnValue); - forceImageDownload = true; - break; - case Storage.CacheStatus.Expired: - try - { - returnValue = await GetObjectFromServer(searchValue, ImagePath); - Storage.NewCacheValue(returnValue, true); - - // check if old value is different from the new value - only download if it's different - Cover oldCover = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - if (oldCover.ImageId != returnValue.ImageId) - { - forceImageDownload = true; - } - } - catch (Exception ex) - { - Logging.Log(Logging.LogType.Warning, "Metadata: " + returnValue.GetType().Name, "An error occurred while connecting to IGDB. Id: " + searchValue, ex); - returnValue = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - } - break; - case Storage.CacheStatus.Current: - returnValue = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - break; - default: - throw new Exception("How did you get here?"); - } - - if (GetImages == true) - { - if (forceImageDownload == true) - { - Logging.Log(Logging.LogType.Information, "Metadata: " + returnValue.GetType().Name, "Cover download forced."); - - Communications comms = new Communications(); - comms.GetSpecificImageFromServer(ImagePath, returnValue.ImageId, Communications.IGDBAPI_ImageSize.original, null); - } - } - - return returnValue; - } - - private static async Task GetObjectFromServer(long searchValue, string ImagePath) - { - // get Cover metadata - Communications comms = new Communications(); - var results = await comms.APIComm(Communications.MetadataEndpoint.Cover, searchValue); - var result = results.First(); - - return result; - } } } diff --git a/gaseous-server/Classes/Metadata/ExternalGames.cs b/gaseous-server/Classes/Metadata/ExternalGames.cs index 00fe00d..bddf097 100644 --- a/gaseous-server/Classes/Metadata/ExternalGames.cs +++ b/gaseous-server/Classes/Metadata/ExternalGames.cs @@ -1,7 +1,5 @@ using System; -using IGDB; -using IGDB.Models; - +using HasheousClient.Models.Metadata.IGDB; namespace gaseous_server.Classes.Metadata { @@ -13,7 +11,7 @@ namespace gaseous_server.Classes.Metadata { } - public static ExternalGame? GetExternalGames(long? Id) + public static ExternalGame? GetExternalGames(HasheousClient.Models.MetadataModel.MetadataSources SourceType, long? Id) { if ((Id == 0) || (Id == null)) { @@ -21,62 +19,8 @@ namespace gaseous_server.Classes.Metadata } else { - Task RetVal = _GetExternalGames((long)Id); - return RetVal.Result; - } - } - - private static async Task _GetExternalGames(long searchValue) - { - // check database first - Storage.CacheStatus? cacheStatus = Storage.GetCacheStatus("ExternalGame", searchValue); - - ExternalGame returnValue = new ExternalGame(); - switch (cacheStatus) - { - case Storage.CacheStatus.NotPresent: - returnValue = await GetObjectFromServer(searchValue); - if (returnValue != null) - { - Storage.NewCacheValue(returnValue); - } - break; - case Storage.CacheStatus.Expired: - try - { - returnValue = await GetObjectFromServer(searchValue); - Storage.NewCacheValue(returnValue, true); - } - catch (Exception ex) - { - Logging.Log(Logging.LogType.Warning, "Metadata: " + returnValue.GetType().Name, "An error occurred while connecting to IGDB. Id: " + searchValue, ex); - returnValue = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - } - break; - case Storage.CacheStatus.Current: - returnValue = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - break; - default: - throw new Exception("How did you get here?"); - } - - return returnValue; - } - - private static async Task GetObjectFromServer(long searchValue) - { - // get ExternalGames metadata - Communications comms = new Communications(); - var results = await comms.APIComm(Communications.MetadataEndpoint.ExternalGame, searchValue); - if (results.Length > 0) - { - var result = results.First(); - - return result; - } - else - { - return null; + ExternalGame? RetVal = Metadata.GetMetadata(SourceType, (long)Id, false); + return RetVal; } } } diff --git a/gaseous-server/Classes/Metadata/Franchises.cs b/gaseous-server/Classes/Metadata/Franchises.cs index a947455..a34c176 100644 --- a/gaseous-server/Classes/Metadata/Franchises.cs +++ b/gaseous-server/Classes/Metadata/Franchises.cs @@ -1,7 +1,5 @@ using System; -using IGDB; -using IGDB.Models; - +using HasheousClient.Models.Metadata.IGDB; namespace gaseous_server.Classes.Metadata { @@ -13,7 +11,7 @@ namespace gaseous_server.Classes.Metadata { } - public static Franchise? GetFranchises(long? Id) + public static Franchise? GetFranchises(HasheousClient.Models.MetadataModel.MetadataSources SourceType, long? Id) { if ((Id == 0) || (Id == null)) { @@ -21,54 +19,10 @@ namespace gaseous_server.Classes.Metadata } else { - Task RetVal = _GetFranchises((long)Id); - return RetVal.Result; + Franchise? RetVal = Metadata.GetMetadata(SourceType, (long)Id, false); + return RetVal; } } - - private static async Task _GetFranchises(long searchValue) - { - // check database first - Storage.CacheStatus? cacheStatus = Storage.GetCacheStatus("Franchise", searchValue); - - Franchise returnValue = new Franchise(); - switch (cacheStatus) - { - case Storage.CacheStatus.NotPresent: - returnValue = await GetObjectFromServer(searchValue); - Storage.NewCacheValue(returnValue); - break; - case Storage.CacheStatus.Expired: - try - { - returnValue = await GetObjectFromServer(searchValue); - Storage.NewCacheValue(returnValue, true); - } - catch (Exception ex) - { - Logging.Log(Logging.LogType.Warning, "Metadata: " + returnValue.GetType().Name, "An error occurred while connecting to IGDB. Id: " + searchValue, ex); - returnValue = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - } - break; - case Storage.CacheStatus.Current: - returnValue = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - break; - default: - throw new Exception("How did you get here?"); - } - - return returnValue; - } - - private static async Task GetObjectFromServer(long searchValue) - { - // get FranchiseContentDescriptions metadata - Communications comms = new Communications(); - var results = await comms.APIComm(Communications.MetadataEndpoint.Franchise, searchValue); - var result = results.First(); - - return result; - } } } diff --git a/gaseous-server/Classes/Metadata/GameModes.cs b/gaseous-server/Classes/Metadata/GameModes.cs index 947f4e6..002160a 100644 --- a/gaseous-server/Classes/Metadata/GameModes.cs +++ b/gaseous-server/Classes/Metadata/GameModes.cs @@ -1,6 +1,5 @@ using System; -using IGDB; -using IGDB.Models; +using HasheousClient.Models.Metadata.IGDB; namespace gaseous_server.Classes.Metadata @@ -13,7 +12,7 @@ namespace gaseous_server.Classes.Metadata { } - public static GameMode? GetGame_Modes(long? Id) + public static GameMode? GetGame_Modes(HasheousClient.Models.MetadataModel.MetadataSources SourceType, long? Id) { if ((Id == 0) || (Id == null)) { @@ -21,54 +20,10 @@ namespace gaseous_server.Classes.Metadata } else { - Task RetVal = _GetGame_Modes((long)Id); - return RetVal.Result; + GameMode? RetVal = Metadata.GetMetadata(SourceType, (long)Id, false); + return RetVal; } } - - private static async Task _GetGame_Modes(long searchValue) - { - // check database first - Storage.CacheStatus? cacheStatus = Storage.GetCacheStatus("GameMode", searchValue); - - GameMode returnValue = new GameMode(); - switch (cacheStatus) - { - case Storage.CacheStatus.NotPresent: - returnValue = await GetObjectFromServer(searchValue); - Storage.NewCacheValue(returnValue); - break; - case Storage.CacheStatus.Expired: - try - { - returnValue = await GetObjectFromServer(searchValue); - Storage.NewCacheValue(returnValue, true); - } - catch (Exception ex) - { - Logging.Log(Logging.LogType.Warning, "Metadata: " + returnValue.GetType().Name, "An error occurred while connecting to IGDB. Id: " + searchValue, ex); - returnValue = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - } - break; - case Storage.CacheStatus.Current: - returnValue = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - break; - default: - throw new Exception("How did you get here?"); - } - - return returnValue; - } - - private static async Task GetObjectFromServer(long searchValue) - { - // get Game_Modes metadata - Communications comms = new Communications(); - var results = await comms.APIComm(Communications.MetadataEndpoint.GameMode, searchValue); - var result = results.First(); - - return result; - } } } diff --git a/gaseous-server/Classes/Metadata/GameVideos.cs b/gaseous-server/Classes/Metadata/GameVideos.cs index 0155818..33ef710 100644 --- a/gaseous-server/Classes/Metadata/GameVideos.cs +++ b/gaseous-server/Classes/Metadata/GameVideos.cs @@ -1,6 +1,5 @@ using System; -using IGDB; -using IGDB.Models; +using HasheousClient.Models.Metadata.IGDB; namespace gaseous_server.Classes.Metadata @@ -13,7 +12,7 @@ namespace gaseous_server.Classes.Metadata { } - public static GameVideo? GetGame_Videos(long? Id) + public static GameVideo? GetGame_Videos(HasheousClient.Models.MetadataModel.MetadataSources SourceType, long? Id) { if ((Id == 0) || (Id == null)) { @@ -21,54 +20,10 @@ namespace gaseous_server.Classes.Metadata } else { - Task RetVal = _GetGame_Videos((long)Id); - return RetVal.Result; + GameVideo? RetVal = Metadata.GetMetadata(SourceType, (long)Id, false); + return RetVal; } } - - private static async Task _GetGame_Videos(long searchValue) - { - // check database first - Storage.CacheStatus? cacheStatus = Storage.GetCacheStatus("GameVideo", searchValue); - - GameVideo returnValue = new GameVideo(); - switch (cacheStatus) - { - case Storage.CacheStatus.NotPresent: - returnValue = await GetObjectFromServer(searchValue); - Storage.NewCacheValue(returnValue); - break; - case Storage.CacheStatus.Expired: - try - { - returnValue = await GetObjectFromServer(searchValue); - Storage.NewCacheValue(returnValue, true); - } - catch (Exception ex) - { - Logging.Log(Logging.LogType.Warning, "Metadata: " + returnValue.GetType().Name, "An error occurred while connecting to IGDB. Id: " + searchValue, ex); - returnValue = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - } - break; - case Storage.CacheStatus.Current: - returnValue = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - break; - default: - throw new Exception("How did you get here?"); - } - - return returnValue; - } - - private static async Task GetObjectFromServer(long searchValue) - { - // get Game_Videos metadata - Communications comms = new Communications(); - var results = await comms.APIComm(Communications.MetadataEndpoint.GameVideo, searchValue); - var result = results.First(); - - return result; - } } } diff --git a/gaseous-server/Classes/Metadata/Games.cs b/gaseous-server/Classes/Metadata/Games.cs index d41af72..2a99270 100644 --- a/gaseous-server/Classes/Metadata/Games.cs +++ b/gaseous-server/Classes/Metadata/Games.cs @@ -2,8 +2,6 @@ using System.Data; using System.Security.Cryptography.X509Certificates; using gaseous_server.Models; -using IGDB; -using IGDB.Models; namespace gaseous_server.Classes.Metadata { @@ -22,39 +20,24 @@ namespace gaseous_server.Classes.Metadata { } } - public static Game? GetGame(long Id, bool getAllMetadata, bool followSubGames, bool forceRefresh) + public static Game? GetGame(HasheousClient.Models.MetadataModel.MetadataSources SourceType, long? Id) { - if (Id == 0) + if ((Id == 0) || (Id == null)) { - Game returnValue = new Game(); - if (Storage.GetCacheStatus("Game", 0) == Storage.CacheStatus.NotPresent) - { - returnValue = new Game - { - Id = 0, - Name = "Unknown Title", - Slug = "Unknown" - }; - Storage.NewCacheValue(returnValue); - - return returnValue; - } - else - { - return Storage.GetCacheValue(returnValue, "id", 0); - } + return null; } else { - Task RetVal = _GetGame(SearchUsing.Id, Id, getAllMetadata, followSubGames, forceRefresh); - return RetVal.Result; + Game? RetVal = Metadata.GetMetadata(SourceType, (long)Id, false); + RetVal.MetadataSource = SourceType; + RetVal = MassageResult(RetVal); + return RetVal; } } - public static Game GetGame(string Slug, bool getAllMetadata, bool followSubGames, bool forceRefresh) + public static Game? GetGame(HasheousClient.Models.MetadataModel.MetadataSources SourceType, string? Slug) { - Task RetVal = _GetGame(SearchUsing.Slug, Slug, getAllMetadata, followSubGames, forceRefresh); - return RetVal.Result; + throw new NotImplementedException(); } public static Game GetGame(DataRow dataRow) @@ -62,323 +45,30 @@ namespace gaseous_server.Classes.Metadata return Storage.BuildCacheObject(new Game(), dataRow); } - private static async Task _GetGame(SearchUsing searchUsing, object searchValue, bool getAllMetadata = true, bool followSubGames = false, bool forceRefresh = false) - { - // check database first - Storage.CacheStatus? cacheStatus = new Storage.CacheStatus(); - if (searchUsing == SearchUsing.Id) - { - cacheStatus = Storage.GetCacheStatus("Game", (long)searchValue); - } - else - { - cacheStatus = Storage.GetCacheStatus("Game", (string)searchValue); - } - - if (forceRefresh == true) - { - if (cacheStatus == Storage.CacheStatus.Current) { cacheStatus = Storage.CacheStatus.Expired; } - } - - Game returnValue = new Game(); - switch (cacheStatus) - { - case Storage.CacheStatus.NotPresent: - if (searchUsing == SearchUsing.Id) - { - returnValue = await GetObjectFromServer((long)searchValue); - } - else - { - returnValue = await GetObjectFromServer((string)searchValue); - } - Storage.NewCacheValue(returnValue); - UpdateSubClasses(returnValue, getAllMetadata, followSubGames, forceRefresh); - return returnValue; - case Storage.CacheStatus.Expired: - try - { - if (searchUsing == SearchUsing.Id) - { - returnValue = await GetObjectFromServer((long)searchValue); - } - else - { - returnValue = await GetObjectFromServer((string)searchValue); - } - Storage.NewCacheValue(returnValue, true); - UpdateSubClasses(returnValue, getAllMetadata, followSubGames, forceRefresh); - } - catch (Exception ex) - { - Logging.Log(Logging.LogType.Warning, "Metadata: " + returnValue.GetType().Name, "An error occurred while connecting to IGDB. Id/Slug: " + searchValue, ex); - returnValue = Storage.GetCacheValue(returnValue, searchUsing.ToString(), searchValue); - } - return returnValue; - case Storage.CacheStatus.Current: - returnValue = Storage.GetCacheValue(returnValue, searchUsing.ToString(), searchValue); - UpdateSubClasses(returnValue, false, false, false); - return returnValue; - default: - throw new Exception("How did you get here?"); - } - } - - private static void UpdateSubClasses(Game Game, bool getAllMetadata, bool followSubGames, bool forceRefresh) - { - // required metadata - // if (Game.Cover != null) - // { - // try - // { - // Cover GameCover = Covers.GetCover(Game.Cover.Id, Config.LibraryConfiguration.LibraryMetadataDirectory_Game(Game), forceRefresh); - // } - // catch (Exception ex) - // { - // Logging.Log(Logging.LogType.Critical, "Game Metadata", "Unable to fetch cover artwork.", ex); - // } - // } - - if (Game.Genres != null) - { - foreach (long GenreId in Game.Genres.Ids) - { - Genre GameGenre = Genres.GetGenres(GenreId); - } - } - - if (Game.GameModes != null) - { - foreach (long gameModeId in Game.GameModes.Ids) - { - GameMode gameMode = GameModes.GetGame_Modes(gameModeId); - } - } - - if (Game.MultiplayerModes != null) - { - foreach (long multiplayerModeId in Game.MultiplayerModes.Ids) - { - MultiplayerMode multiplayerMode = MultiplayerModes.GetGame_MultiplayerModes(multiplayerModeId); - } - } - - if (Game.PlayerPerspectives != null) - { - foreach (long PerspectiveId in Game.PlayerPerspectives.Ids) - { - PlayerPerspective GamePlayPerspective = PlayerPerspectives.GetGame_PlayerPerspectives(PerspectiveId); - } - } - - if (Game.Themes != null) - { - foreach (long ThemeId in Game.Themes.Ids) - { - Theme GameTheme = Themes.GetGame_Themes(ThemeId); - } - } - - if (Game.AgeRatings != null) - { - foreach (long AgeRatingId in Game.AgeRatings.Ids) - { - AgeRating GameAgeRating = AgeRatings.GetAgeRatings(AgeRatingId); - } - } - AgeGroups.GetAgeGroup(Game); - - if (Game.ReleaseDates != null) - { - foreach (long ReleaseDateId in Game.ReleaseDates.Ids) - { - ReleaseDate GameReleaseDate = ReleaseDates.GetReleaseDates(ReleaseDateId); - } - } - - // optional metadata - usually downloaded as needed - if (getAllMetadata == true) - { - if (Game.AlternativeNames != null) - { - foreach (long AlternativeNameId in Game.AlternativeNames.Ids) - { - AlternativeName GameAlternativeName = AlternativeNames.GetAlternativeNames(AlternativeNameId); - } - } - - if (Game.Artworks != null) - { - foreach (long ArtworkId in Game.Artworks.Ids) - { - try - { - Artwork GameArtwork = Artworks.GetArtwork(ArtworkId, Config.LibraryConfiguration.LibraryMetadataDirectory_Game(Game), forceRefresh); - } - catch (Exception ex) - { - Logging.Log(Logging.LogType.Critical, "Game Metadata", "Unable to fetch artwork id: " + ArtworkId, ex); - } - } - } - - if (followSubGames) - { - List gamesToFetch = new List(); - if (Game.Bundles != null) { gamesToFetch.AddRange(Game.Bundles.Ids); } - if (Game.Dlcs != null) { gamesToFetch.AddRange(Game.Dlcs.Ids); } - if (Game.Expansions != null) { gamesToFetch.AddRange(Game.Expansions.Ids); } - if (Game.ParentGame != null) { gamesToFetch.Add((long)Game.ParentGame.Id); } - //if (Game.SimilarGames != null) { gamesToFetch.AddRange(Game.SimilarGames.Ids); } - if (Game.StandaloneExpansions != null) { gamesToFetch.AddRange(Game.StandaloneExpansions.Ids); } - if (Game.VersionParent != null) { gamesToFetch.Add((long)Game.VersionParent.Id); } - - foreach (long gameId in gamesToFetch) - { - Game relatedGame = GetGame(gameId, false, true, false); - } - } - - if (Game.Collection != null) - { - Collection GameCollection = Collections.GetCollections(Game.Collection.Id); - } - - // if (Game.ExternalGames != null) - // { - // foreach (long ExternalGameId in Game.ExternalGames.Ids) - // { - // ExternalGame GameExternalGame = ExternalGames.GetExternalGames(ExternalGameId); - // } - // } - - if (Game.Franchise != null) - { - Franchise GameFranchise = Franchises.GetFranchises(Game.Franchise.Id); - } - - if (Game.Franchises != null) - { - foreach (long FranchiseId in Game.Franchises.Ids) - { - Franchise GameFranchise = Franchises.GetFranchises(FranchiseId); - } - } - - if (Game.InvolvedCompanies != null) - { - foreach (long involvedCompanyId in Game.InvolvedCompanies.Ids) - { - InvolvedCompany involvedCompany = InvolvedCompanies.GetInvolvedCompanies(involvedCompanyId); - } - } - - if (Game.Platforms != null) - { - foreach (long PlatformId in Game.Platforms.Ids) - { - Platform GamePlatform = Platforms.GetPlatform(PlatformId); - } - } - - if (Game.Screenshots != null) - { - foreach (long ScreenshotId in Game.Screenshots.Ids) - { - try - { - Screenshot GameScreenshot = Screenshots.GetScreenshot(ScreenshotId, Config.LibraryConfiguration.LibraryMetadataDirectory_Game(Game), forceRefresh); - } - catch (Exception ex) - { - Logging.Log(Logging.LogType.Critical, "Game Metadata", "Unable to fetch screenshot id: " + ScreenshotId, ex); - } - } - } - - if (Game.Videos != null) - { - foreach (long GameVideoId in Game.Videos.Ids) - { - GameVideo gameVideo = GamesVideos.GetGame_Videos(GameVideoId); - } - } - } - } - - private enum SearchUsing - { - Id, - Slug - } - - private static async Task GetObjectFromServer(string Slug) - { - // get Game metadata - Communications comms = new Communications(); - var results = await comms.APIComm(Communications.MetadataEndpoint.Game, Slug); - var result = results.First(); - - result = MassageResult(result); - - return result; - } - - private static async Task GetObjectFromServer(long Id) - { - // get Game metadata - Communications comms = new Communications(); - var results = await comms.APIComm(Communications.MetadataEndpoint.Game, Id); - var result = results.First(); - - result = MassageResult(result); - - return result; - } - private static Game MassageResult(Game result) { - // add artificial unknown platform mapping - List platformIds = new List(); - platformIds.Add(0); - if (result.Platforms != null) - { - if (result.Platforms.Ids != null) - { - platformIds.AddRange(result.Platforms.Ids.ToList()); - } - } - result.Platforms = new IdentitiesOrValues( - ids: platformIds.ToArray() - ); + Game? parentGame = null; // get cover art from parent if this has no cover if (result.Cover == null) { if (result.ParentGame != null) { - if (result.ParentGame.Id != null) - { - Logging.Log(Logging.LogType.Information, "Game Metadata", "Game has no cover art, fetching cover art from parent game"); - Game parentGame = GetGame((long)result.ParentGame.Id, false, false, false); - result.Cover = parentGame.Cover; - } + Logging.Log(Logging.LogType.Information, "Game Metadata", "Game has no cover art, fetching cover art from parent game"); + parentGame = GetGame(result.MetadataSource, (long)result.ParentGame); + result.Cover = parentGame.Cover; } } // get missing metadata from parent if this is a port - if (result.Category == Category.Port) + if (result.Category == HasheousClient.Models.Metadata.IGDB.Category.Port) { if (result.Summary == null) { if (result.ParentGame != null) { - if (result.ParentGame.Id != null) - { - Logging.Log(Logging.LogType.Information, "Game Metadata", "Game has no summary, fetching summary from parent game"); - Game parentGame = GetGame((long)result.ParentGame.Id, false, false, false); - result.Summary = parentGame.Summary; - } + Logging.Log(Logging.LogType.Information, "Game Metadata", "Game has no summary, fetching summary from parent game"); + result.Summary = parentGame.Summary; } } } @@ -386,20 +76,6 @@ namespace gaseous_server.Classes.Metadata return result; } - public static void AssignAllGamesToPlatformIdZero() - { - Database db = new Database(Database.databaseType.MySql, Config.DatabaseConfiguration.ConnectionString); - string sql = "SELECT * FROM Game;"; - DataTable gamesTable = db.ExecuteCMD(sql); - foreach (DataRow gameRow in gamesTable.Rows) - { - sql = "DELETE FROM Relation_Game_Platforms WHERE PlatformsId = 0 AND GameId = @Id; INSERT INTO Relation_Game_Platforms (GameId, PlatformsId) VALUES (@Id, 0);"; - Dictionary dbDict = new Dictionary(); - dbDict.Add("Id", (long)gameRow["Id"]); - db.ExecuteCMD(sql, dbDict); - } - } - private static bool AllowNoPlatformSearch = false; public static Game[] SearchForGame(string SearchString, long PlatformId, SearchType searchType) @@ -515,7 +191,7 @@ namespace gaseous_server.Classes.Metadata Game[]? results = new Game[0]; if (allowSearch == true) { - results = await comms.APIComm(IGDBClient.Endpoints.Games, searchFields, searchBody); + results = await comms.APIComm(IGDB.IGDBClient.Endpoints.Games, searchFields, searchBody); Communications.SetSearchCache(searchFields, searchBody, results); } @@ -598,7 +274,7 @@ ORDER BY Platform.`Name`;"; List platforms = new List(); foreach (DataRow row in data.Rows) { - IGDB.Models.Platform platform = Platforms.GetPlatform((long)row["PlatformId"]); + HasheousClient.Models.Metadata.IGDB.Platform platform = Platforms.GetPlatform((long)row["PlatformId"]); PlatformMapping.UserEmulatorConfiguration? emulatorConfiguration = platformMapping.GetUserEmulator(UserId, GameId, (long)platform.Id); if (emulatorConfiguration == null) @@ -688,7 +364,7 @@ ORDER BY Platform.`Name`;"; db.ExecuteCMD(sql, dbDict); } - public class AvailablePlatformItem : IGDB.Models.Platform + public class AvailablePlatformItem : HasheousClient.Models.Metadata.IGDB.Platform { public PlatformMapping.UserEmulatorConfiguration emulatorConfiguration { get; set; } public long? LastPlayedRomId { get; set; } @@ -727,12 +403,12 @@ ORDER BY Platform.`Name`;"; this.FirstReleaseDate = gameObject.FirstReleaseDate; // compile age ratings - this.AgeRatings = new List(); + this.AgeRatings = new List(); if (gameObject.AgeRatings != null) { - foreach (long ageRatingId in gameObject.AgeRatings.Ids) + foreach (long ageRatingId in gameObject.AgeRatings) { - AgeRating? rating = Classes.Metadata.AgeRatings.GetAgeRatings(ageRatingId); + HasheousClient.Models.Metadata.IGDB.AgeRating? rating = Classes.Metadata.AgeRatings.GetAgeRating(gameObject.MetadataSource, ageRatingId); if (rating != null) { this.AgeRatings.Add(rating); @@ -751,9 +427,9 @@ ORDER BY Platform.`Name`;"; public bool HasSavedGame { get; set; } = false; public bool IsFavourite { get; set; } = false; public DateTimeOffset? FirstReleaseDate { get; set; } - public IGDB.IdentityOrValue Cover { get; set; } - public IGDB.IdentitiesOrValues Artworks { get; set; } - public List AgeRatings { get; set; } + public object Cover { get; set; } + public List Artworks { get; set; } + public List AgeRatings { get; set; } } } } \ No newline at end of file diff --git a/gaseous-server/Classes/Metadata/Genres.cs b/gaseous-server/Classes/Metadata/Genres.cs index f65560c..fbc5201 100644 --- a/gaseous-server/Classes/Metadata/Genres.cs +++ b/gaseous-server/Classes/Metadata/Genres.cs @@ -1,11 +1,10 @@ using System; -using IGDB; -using IGDB.Models; +using HasheousClient.Models.Metadata.IGDB; namespace gaseous_server.Classes.Metadata { - public class Genres + public class Genres { public const string fieldList = "fields checksum,created_at,name,slug,updated_at,url;"; @@ -13,7 +12,7 @@ namespace gaseous_server.Classes.Metadata { } - public static Genre? GetGenres(long? Id) + public static Genre? GetGenres(HasheousClient.Models.MetadataModel.MetadataSources SourceType, long? Id) { if ((Id == 0) || (Id == null)) { @@ -21,54 +20,10 @@ namespace gaseous_server.Classes.Metadata } else { - Task RetVal = _GetGenres((long)Id); - return RetVal.Result; + Genre? RetVal = Metadata.GetMetadata(SourceType, (long)Id, false); + return RetVal; } } - - private static async Task _GetGenres(long searchValue) - { - // check database first - Storage.CacheStatus? cacheStatus = Storage.GetCacheStatus("Genre", searchValue); - - Genre returnValue = new Genre(); - switch (cacheStatus) - { - case Storage.CacheStatus.NotPresent: - returnValue = await GetObjectFromServer(searchValue); - Storage.NewCacheValue(returnValue); - break; - case Storage.CacheStatus.Expired: - try - { - returnValue = await GetObjectFromServer(searchValue); - Storage.NewCacheValue(returnValue, true); - } - catch (Exception ex) - { - Logging.Log(Logging.LogType.Warning, "Metadata: " + returnValue.GetType().Name, "An error occurred while connecting to IGDB. Id: " + searchValue, ex); - returnValue = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - } - break; - case Storage.CacheStatus.Current: - returnValue = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - break; - default: - throw new Exception("How did you get here?"); - } - - return returnValue; - } - - private static async Task GetObjectFromServer(long searchValue) - { - // get Genres metadata - Communications comms = new Communications(); - var results = await comms.APIComm(Communications.MetadataEndpoint.Genre, searchValue); - var result = results.First(); - - return result; - } - } + } } diff --git a/gaseous-server/Classes/Metadata/InvolvedCompany.cs b/gaseous-server/Classes/Metadata/InvolvedCompany.cs index f43feba..e77671d 100644 --- a/gaseous-server/Classes/Metadata/InvolvedCompany.cs +++ b/gaseous-server/Classes/Metadata/InvolvedCompany.cs @@ -1,6 +1,5 @@ using System; -using IGDB; -using IGDB.Models; +using HasheousClient.Models.Metadata.IGDB; namespace gaseous_server.Classes.Metadata { @@ -20,63 +19,10 @@ namespace gaseous_server.Classes.Metadata } else { - Task RetVal = _GetInvolvedCompanies((long)Id); - return RetVal.Result; + InvolvedCompany? RetVal = Metadata.GetMetadata(Communications.MetadataSource, (long)Id, false); + return RetVal; } } - - private static async Task _GetInvolvedCompanies(long searchValue) - { - // check database first - Storage.CacheStatus? cacheStatus = Storage.GetCacheStatus("InvolvedCompany", searchValue); - - InvolvedCompany returnValue = new InvolvedCompany(); - switch (cacheStatus) - { - case Storage.CacheStatus.NotPresent: - returnValue = await GetObjectFromServer(searchValue); - Storage.NewCacheValue(returnValue); - UpdateSubClasses(returnValue); - break; - case Storage.CacheStatus.Expired: - try - { - returnValue = await GetObjectFromServer(searchValue); - Storage.NewCacheValue(returnValue, true); - } - catch (Exception ex) - { - Logging.Log(Logging.LogType.Warning, "Metadata: " + returnValue.GetType().Name, "An error occurred while connecting to IGDB. Id: " + searchValue, ex); - returnValue = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - } - break; - case Storage.CacheStatus.Current: - returnValue = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - break; - default: - throw new Exception("How did you get here?"); - } - - return returnValue; - } - - private static void UpdateSubClasses(InvolvedCompany involvedCompany) - { - if (involvedCompany.Company != null) - { - Company company = Companies.GetCompanies(involvedCompany.Company.Id); - } - } - - private static async Task GetObjectFromServer(long searchValue) - { - // get Genres metadata - Communications comms = new Communications(); - var results = await comms.APIComm(Communications.MetadataEndpoint.InvolvedCompany, searchValue); - var result = results.First(); - - return result; - } } } diff --git a/gaseous-server/Classes/Metadata/Metadata.cs b/gaseous-server/Classes/Metadata/Metadata.cs new file mode 100644 index 0000000..2d9318c --- /dev/null +++ b/gaseous-server/Classes/Metadata/Metadata.cs @@ -0,0 +1,140 @@ +namespace gaseous_server.Classes.Metadata +{ + public class Metadata + { + #region Exception Handling + public class InvalidMetadataId : Exception + { + public InvalidMetadataId(long Id) : base("Invalid Metadata id: " + Id + " from source: " + Communications.MetadataSource + " (default)") + { + } + + public InvalidMetadataId(HasheousClient.Models.MetadataModel.MetadataSources SourceType, long Id) : base("Invalid Metadata id: " + Id + " from source: " + SourceType) + { + } + + public InvalidMetadataId(string Id) : base("Invalid Metadata id: " + Id + " from source: " + Communications.MetadataSource + " (default)") + { + } + + public InvalidMetadataId(string SourceType, string Id) : base("Invalid Metadata id: " + Id + " from source: " + SourceType) + { + } + } + #endregion + + #region Get Metadata + /// + /// Get metadata from the default source + /// + /// + /// The type of metadata to get + /// + /// + /// The id of the metadata to get + /// + /// + /// The metadata object + /// + /// + /// Thrown when the id is invalid + /// + public static T? GetMetadata(long Id, Boolean ForceRefresh = false) where T : class + { + if (Id < 0) + { + throw new InvalidMetadataId(Id); + } + + return _GetMetadata(Communications.MetadataSource, Id, ForceRefresh); + } + + /// + /// Get metadata from the specified source + /// + /// + /// The type of metadata to get + /// + /// + /// The source of the metadata + /// + /// + /// The id of the metadata to get + /// + /// + /// The metadata object + /// + /// + /// Thrown when the id is invalid + /// + public static T? GetMetadata(HasheousClient.Models.MetadataModel.MetadataSources SourceType, long Id, Boolean ForceRefresh = false) where T : class + { + if (Id < 0) + { + throw new InvalidMetadataId(SourceType, Id); + } + + return _GetMetadata(SourceType, Id, ForceRefresh); + } + + private static T? _GetMetadata(HasheousClient.Models.MetadataModel.MetadataSources SourceType, long Id, Boolean ForceRefresh) where T : class + { + // get T type as string + string type = typeof(T).Name; + + // check cached metadata status + // if metadata is not cached or expired, get it from the source. Otherwise, return the cached metadata + Storage.CacheStatus? cacheStatus = Storage.GetCacheStatus(SourceType, type, Id); + + // if ForceRefresh is true, set cache status to expired if it is current + if (ForceRefresh == true) + { + if (cacheStatus == Storage.CacheStatus.Current) + { + cacheStatus = Storage.CacheStatus.Expired; + } + } + + T? metadata = (T)Activator.CreateInstance(typeof(T)); + + switch (cacheStatus) + { + case Storage.CacheStatus.Current: + metadata = Storage.GetCacheValue(SourceType, metadata, "Id", Id); + break; + + case Storage.CacheStatus.Expired: + metadata = GetMetadataFromServer(SourceType, Id).Result; + Storage.NewCacheValue(SourceType, metadata, true); + break; + + case Storage.CacheStatus.NotPresent: + metadata = GetMetadataFromServer(SourceType, Id).Result; + Storage.NewCacheValue(SourceType, metadata, false); + break; + } + + return metadata; + } + + private static async Task GetMetadataFromServer(HasheousClient.Models.MetadataModel.MetadataSources SourceType, long Id) where T : class + { + // get T type as string + string type = typeof(T).Name; + + // get metadata from the server + Communications comms = new Communications(); + var results = await comms.APIComm(SourceType, (Communications.MetadataEndpoint)Enum.Parse(typeof(Communications.MetadataEndpoint), type, true), Id); + + // check for errors + if (results == null) + { + throw new InvalidMetadataId(SourceType, Id); + } + + return results.FirstOrDefault(); + } + + #endregion + } +} \ No newline at end of file diff --git a/gaseous-server/Classes/Metadata/MultiplayerModes.cs b/gaseous-server/Classes/Metadata/MultiplayerModes.cs index a35fc3e..66d7598 100644 --- a/gaseous-server/Classes/Metadata/MultiplayerModes.cs +++ b/gaseous-server/Classes/Metadata/MultiplayerModes.cs @@ -1,6 +1,5 @@ using System; -using IGDB; -using IGDB.Models; +using HasheousClient.Models.Metadata.IGDB; namespace gaseous_server.Classes.Metadata @@ -21,54 +20,10 @@ namespace gaseous_server.Classes.Metadata } else { - Task RetVal = _GetGame_MultiplayerModes((long)Id); - return RetVal.Result; + MultiplayerMode? RetVal = Metadata.GetMetadata(Communications.MetadataSource, (long)Id, false); + return RetVal; } } - - private static async Task _GetGame_MultiplayerModes(long searchValue) - { - // check database first - Storage.CacheStatus? cacheStatus = Storage.GetCacheStatus("MultiplayerMode", searchValue); - - MultiplayerMode returnValue = new MultiplayerMode(); - switch (cacheStatus) - { - case Storage.CacheStatus.NotPresent: - returnValue = await GetObjectFromServer(searchValue); - Storage.NewCacheValue(returnValue); - break; - case Storage.CacheStatus.Expired: - try - { - returnValue = await GetObjectFromServer(searchValue); - Storage.NewCacheValue(returnValue, true); - } - catch (Exception ex) - { - Logging.Log(Logging.LogType.Warning, "Metadata: " + returnValue.GetType().Name, "An error occurred while connecting to IGDB. Id: " + searchValue, ex); - returnValue = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - } - break; - case Storage.CacheStatus.Current: - returnValue = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - break; - default: - throw new Exception("How did you get here?"); - } - - return returnValue; - } - - private static async Task GetObjectFromServer(long searchValue) - { - // get Game_MultiplayerModes metadata - Communications comms = new Communications(); - var results = await comms.APIComm(Communications.MetadataEndpoint.MultiplayerMode, searchValue); - var result = results.First(); - - return result; - } } } diff --git a/gaseous-server/Classes/Metadata/PlatformLogos.cs b/gaseous-server/Classes/Metadata/PlatformLogos.cs index f5ae9f7..07771ef 100644 --- a/gaseous-server/Classes/Metadata/PlatformLogos.cs +++ b/gaseous-server/Classes/Metadata/PlatformLogos.cs @@ -1,6 +1,5 @@ using System; -using IGDB; -using IGDB.Models; +using HasheousClient.Models.Metadata.IGDB; namespace gaseous_server.Classes.Metadata @@ -13,7 +12,7 @@ namespace gaseous_server.Classes.Metadata { } - public static PlatformLogo? GetPlatformLogo(long? Id, string ImagePath) + public static PlatformLogo? GetPlatformLogo(long? Id) { if ((Id == 0) || (Id == null)) { @@ -21,77 +20,10 @@ namespace gaseous_server.Classes.Metadata } else { - Task RetVal = _GetPlatformLogo((long)Id, ImagePath); - return RetVal.Result; + PlatformLogo? RetVal = Metadata.GetMetadata(Communications.MetadataSource, (long)Id, false); + return RetVal; } } - - private static async Task _GetPlatformLogo(long searchValue, string ImagePath) - { - // check database first - Storage.CacheStatus? cacheStatus = Storage.GetCacheStatus("PlatformLogo", searchValue); - - PlatformLogo returnValue = new PlatformLogo(); - bool forceImageDownload = false; - switch (cacheStatus) - { - case Storage.CacheStatus.NotPresent: - returnValue = await GetObjectFromServer(searchValue, ImagePath); - if (returnValue != null) - { - Storage.NewCacheValue(returnValue); - forceImageDownload = true; - } - break; - case Storage.CacheStatus.Expired: - try - { - returnValue = await GetObjectFromServer(searchValue, ImagePath); - Storage.NewCacheValue(returnValue, true); - - // check if old value is different from the new value - only download if it's different - PlatformLogo oldImage = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - if (oldImage.ImageId != returnValue.ImageId) - { - forceImageDownload = true; - } - } - catch (Exception ex) - { - Logging.Log(Logging.LogType.Warning, "Metadata: " + returnValue.GetType().Name, "An error occurred while connecting to IGDB. Id: " + searchValue, ex); - returnValue = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - } - break; - case Storage.CacheStatus.Current: - returnValue = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - break; - default: - throw new Exception("How did you get here?"); - } - - if (returnValue != null) - { - if (forceImageDownload == true) - { - Logging.Log(Logging.LogType.Information, "Metadata: " + returnValue.GetType().Name, "Platform logo download forced."); - - Communications comms = new Communications(); - comms.GetSpecificImageFromServer(ImagePath, returnValue.ImageId, Communications.IGDBAPI_ImageSize.original, null); - } - } - - return returnValue; - } - - private static async Task GetObjectFromServer(long searchValue, string ImagePath) - { - // get Artwork metadata - Communications comms = new Communications(); - var results = await comms.APIComm(Communications.MetadataEndpoint.PlatformLogo, searchValue); - var result = results.First(); - - return result; - } } } diff --git a/gaseous-server/Classes/Metadata/PlatformVersions.cs b/gaseous-server/Classes/Metadata/PlatformVersions.cs index 8ad1ced..1e26d3f 100644 --- a/gaseous-server/Classes/Metadata/PlatformVersions.cs +++ b/gaseous-server/Classes/Metadata/PlatformVersions.cs @@ -1,7 +1,6 @@ using System; using System.Data; -using IGDB; -using IGDB.Models; +using HasheousClient.Models.Metadata.IGDB; namespace gaseous_server.Classes.Metadata { @@ -13,7 +12,7 @@ namespace gaseous_server.Classes.Metadata { } - public static PlatformVersion? GetPlatformVersion(long Id, Platform ParentPlatform, bool GetImages = false) + public static PlatformVersion? GetPlatformVersion(HasheousClient.Models.MetadataModel.MetadataSources SourceType, long Id) { if (Id == 0) { @@ -21,79 +20,8 @@ namespace gaseous_server.Classes.Metadata } else { - Task RetVal = _GetPlatformVersion((long)Id, ParentPlatform, GetImages); - return RetVal.Result; - } - } - - private static async Task _GetPlatformVersion(long searchValue, Platform ParentPlatform, bool GetImages) - { - // check database first - Storage.CacheStatus? cacheStatus = Storage.GetCacheStatus("PlatformVersion", searchValue); - - PlatformVersion returnValue = new PlatformVersion(); - switch (cacheStatus) - { - case Storage.CacheStatus.NotPresent: - returnValue = await GetObjectFromServer(searchValue); - if (returnValue != null) - { - Storage.NewCacheValue(returnValue); - UpdateSubClasses(ParentPlatform, returnValue, GetImages); - } - return returnValue; - case Storage.CacheStatus.Expired: - try - { - returnValue = await GetObjectFromServer(searchValue); - Storage.NewCacheValue(returnValue, true); - UpdateSubClasses(ParentPlatform, returnValue, GetImages); - } - catch (Exception ex) - { - Logging.Log(Logging.LogType.Warning, "Metadata: " + returnValue.GetType().Name, "An error occurred while connecting to IGDB. Id: " + searchValue, ex); - returnValue = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - } - return returnValue; - case Storage.CacheStatus.Current: - return Storage.GetCacheValue(returnValue, "id", (long)searchValue); - default: - throw new Exception("How did you get here?"); - } - } - - private static void UpdateSubClasses(Platform ParentPlatform, PlatformVersion platformVersion, bool GetImages) - { - if (GetImages == true) - { - if (platformVersion.PlatformLogo != null) - { - try - { - PlatformLogo platformLogo = PlatformLogos.GetPlatformLogo(platformVersion.PlatformLogo.Id, Path.Combine(Config.LibraryConfiguration.LibraryMetadataDirectory_Platform(ParentPlatform), "Versions", platformVersion.Slug)); - } - catch (Exception ex) - { - Logging.Log(Logging.LogType.Warning, "Platform Update", "Unable to fetch platform logo", ex); - } - } - } - } - - private static async Task GetObjectFromServer(long searchValue) - { - // get PlatformVersion metadata - Communications comms = new Communications(); - var results = await comms.APIComm(Communications.MetadataEndpoint.PlatformVersion, searchValue); - if (results.Length > 0) - { - var result = results.First(); - - return result; - } - else - { - return null; + PlatformVersion? RetVal = Metadata.GetMetadata(SourceType, Id, false); + return RetVal; } } } diff --git a/gaseous-server/Classes/Metadata/Platforms.cs b/gaseous-server/Classes/Metadata/Platforms.cs index 60efb17..484430b 100644 --- a/gaseous-server/Classes/Metadata/Platforms.cs +++ b/gaseous-server/Classes/Metadata/Platforms.cs @@ -1,8 +1,7 @@ using System; using System.Data; using System.Net; -using IGDB; -using IGDB.Models; +using HasheousClient.Models.Metadata.IGDB; namespace gaseous_server.Classes.Metadata { @@ -15,135 +14,22 @@ namespace gaseous_server.Classes.Metadata } - public static Platform? GetPlatform(long Id, bool forceRefresh = false, bool GetImages = false) + public static Platform? GetPlatform(long Id) { - if (Id == 0) + if ((Id == 0) || (Id == null)) { - Platform returnValue = new Platform(); - if (Storage.GetCacheStatus("Platform", 0) == Storage.CacheStatus.NotPresent) - { - returnValue = new Platform - { - Id = 0, - Name = "Unknown Platform", - Slug = "Unknown" - }; - Storage.NewCacheValue(returnValue); - - return returnValue; - } - else - { - return Storage.GetCacheValue(returnValue, "id", 0); - } + return null; } else { - try - { - Task RetVal = _GetPlatform(SearchUsing.Id, Id, forceRefresh, GetImages); - return RetVal.Result; - } - catch (Exception ex) - { - Logging.Log(Logging.LogType.Warning, "Metadata", "An error occurred fetching Platform Id " + Id, ex); - return null; - } + Platform? RetVal = Metadata.GetMetadata(Communications.MetadataSource, (long)Id, false); + return RetVal; } } public static Platform GetPlatform(string Slug, bool forceRefresh = false, bool GetImages = false) { - Task RetVal = _GetPlatform(SearchUsing.Slug, Slug, forceRefresh, GetImages); - return RetVal.Result; - } - - private static async Task _GetPlatform(SearchUsing searchUsing, object searchValue, bool forceRefresh, bool GetImages) - { - // check database first - Storage.CacheStatus? cacheStatus = new Storage.CacheStatus(); - if (searchUsing == SearchUsing.Id) - { - cacheStatus = Storage.GetCacheStatus("Platform", (long)searchValue); - } - else - { - cacheStatus = Storage.GetCacheStatus("Platform", (string)searchValue); - } - - if (forceRefresh == true) - { - if (cacheStatus == Storage.CacheStatus.Current) { cacheStatus = Storage.CacheStatus.Expired; } - } - - Platform returnValue = new Platform(); - switch (cacheStatus) - { - case Storage.CacheStatus.NotPresent: - if (searchUsing == SearchUsing.Id) - { - returnValue = await GetObjectFromServer((long)searchValue); - } - else - { - returnValue = await GetObjectFromServer((string)searchValue); - } - Storage.NewCacheValue(returnValue); - UpdateSubClasses(returnValue, GetImages); - AddPlatformMapping(returnValue); - return returnValue; - case Storage.CacheStatus.Expired: - try - { - if (searchUsing == SearchUsing.Id) - { - returnValue = await GetObjectFromServer((long)searchValue); - } - else - { - returnValue = await GetObjectFromServer((string)searchValue); - } - Storage.NewCacheValue(returnValue, true); - UpdateSubClasses(returnValue, GetImages); - AddPlatformMapping(returnValue); - return returnValue; - } - catch (Exception ex) - { - Logging.Log(Logging.LogType.Warning, "Metadata: " + returnValue.GetType().Name, "An error occurred while connecting to IGDB. Id/Slug: " + searchValue, ex); - return Storage.GetCacheValue(returnValue, searchUsing.ToString(), searchValue); - } - case Storage.CacheStatus.Current: - return Storage.GetCacheValue(returnValue, searchUsing.ToString(), searchValue); - default: - throw new Exception("How did you get here?"); - } - } - - private static void UpdateSubClasses(Platform platform, bool GetImages) - { - if (platform.Versions != null) - { - foreach (long PlatformVersionId in platform.Versions.Ids) - { - PlatformVersion platformVersion = PlatformVersions.GetPlatformVersion(PlatformVersionId, platform); - } - } - - if (GetImages == true) - { - if (platform.PlatformLogo != null) - { - try - { - PlatformLogo platformLogo = PlatformLogos.GetPlatformLogo(platform.PlatformLogo.Id, Config.LibraryConfiguration.LibraryMetadataDirectory_Platform(platform)); - } - catch (Exception ex) - { - Logging.Log(Logging.LogType.Warning, "Platform Update", "Unable to fetch platform logo", ex); - } - } - } + throw new NotImplementedException(); } private static void AddPlatformMapping(Platform platform) @@ -171,46 +57,6 @@ namespace gaseous_server.Classes.Metadata Models.PlatformMapping.WritePlatformMap(item, false, true); } } - - private enum SearchUsing - { - Id, - Slug - } - - private static async Task GetObjectFromServer(string Slug) - { - // get platform metadata - Communications comms = new Communications(); - var results = await comms.APIComm(Communications.MetadataEndpoint.Platform, Slug); - var result = results.First(); - - return result; - } - - private static async Task GetObjectFromServer(long Id) - { - // get platform metadata - Communications comms = new Communications(); - var results = await comms.APIComm(Communications.MetadataEndpoint.Platform, Id); - var result = results.First(); - - return result; - } - - public static void AssignAllPlatformsToGameIdZero() - { - Database db = new Database(Database.databaseType.MySql, Config.DatabaseConfiguration.ConnectionString); - string sql = "SELECT * FROM Platform;"; - DataTable platformsTable = db.ExecuteCMD(sql); - foreach (DataRow platformRow in platformsTable.Rows) - { - sql = "DELETE FROM Relation_Game_Platforms WHERE GameId = 0 AND PlatformsId = @Id; INSERT INTO Relation_Game_Platforms (GameId, PlatformsId) VALUES (0, @Id);"; - Dictionary dbDict = new Dictionary(); - dbDict.Add("Id", (long)platformRow["Id"]); - db.ExecuteCMD(sql, dbDict); - } - } } } diff --git a/gaseous-server/Classes/Metadata/PlayerPerspectives.cs b/gaseous-server/Classes/Metadata/PlayerPerspectives.cs index b3eb23d..74a076e 100644 --- a/gaseous-server/Classes/Metadata/PlayerPerspectives.cs +++ b/gaseous-server/Classes/Metadata/PlayerPerspectives.cs @@ -1,6 +1,5 @@ using System; -using IGDB; -using IGDB.Models; +using HasheousClient.Models.Metadata.IGDB; namespace gaseous_server.Classes.Metadata @@ -13,7 +12,7 @@ namespace gaseous_server.Classes.Metadata { } - public static PlayerPerspective? GetGame_PlayerPerspectives(long? Id) + public static PlayerPerspective? GetGame_PlayerPerspectives(HasheousClient.Models.MetadataModel.MetadataSources SourceType, long? Id) { if ((Id == 0) || (Id == null)) { @@ -21,56 +20,10 @@ namespace gaseous_server.Classes.Metadata } else { - Task RetVal = _GetGame_PlayerPerspectives((long)Id); - return RetVal.Result; + PlayerPerspective? RetVal = Metadata.GetMetadata(SourceType, (long)Id, false); + return RetVal; } } - - private static async Task _GetGame_PlayerPerspectives(long searchValue) - { - // check database first - Storage.CacheStatus? cacheStatus = Storage.GetCacheStatus("PlayerPerspective", searchValue); - - PlayerPerspective returnValue = new PlayerPerspective(); - bool forceImageDownload = false; - switch (cacheStatus) - { - case Storage.CacheStatus.NotPresent: - returnValue = await GetObjectFromServer(searchValue); - Storage.NewCacheValue(returnValue); - forceImageDownload = true; - break; - case Storage.CacheStatus.Expired: - try - { - returnValue = await GetObjectFromServer(searchValue); - Storage.NewCacheValue(returnValue, true); - } - catch (Exception ex) - { - Logging.Log(Logging.LogType.Warning, "Metadata: " + returnValue.GetType().Name, "An error occurred while connecting to IGDB. Id: " + searchValue, ex); - returnValue = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - } - break; - case Storage.CacheStatus.Current: - returnValue = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - break; - default: - throw new Exception("How did you get here?"); - } - - return returnValue; - } - - private static async Task GetObjectFromServer(long searchValue) - { - // get Game_PlayerPerspectives metadata - Communications comms = new Communications(); - var results = await comms.APIComm(Communications.MetadataEndpoint.PlayerPerspective, searchValue); - var result = results.First(); - - return result; - } } } diff --git a/gaseous-server/Classes/Metadata/ReleaseDates.cs b/gaseous-server/Classes/Metadata/ReleaseDates.cs index 3ff922a..d08f9c9 100644 --- a/gaseous-server/Classes/Metadata/ReleaseDates.cs +++ b/gaseous-server/Classes/Metadata/ReleaseDates.cs @@ -1,6 +1,5 @@ using System; -using IGDB; -using IGDB.Models; +using HasheousClient.Models.Metadata.IGDB; namespace gaseous_server.Classes.Metadata @@ -13,7 +12,7 @@ namespace gaseous_server.Classes.Metadata { } - public static ReleaseDate? GetReleaseDates(long? Id) + public static ReleaseDate? GetReleaseDates(HasheousClient.Models.MetadataModel.MetadataSources SourceType, long? Id) { if ((Id == 0) || (Id == null)) { @@ -21,54 +20,10 @@ namespace gaseous_server.Classes.Metadata } else { - Task RetVal = _GetReleaseDates((long)Id); - return RetVal.Result; + ReleaseDate? RetVal = Metadata.GetMetadata(SourceType, (long)Id, false); + return RetVal; } } - - private static async Task _GetReleaseDates(long searchValue) - { - // check database first - Storage.CacheStatus? cacheStatus = Storage.GetCacheStatus("ReleaseDate", searchValue); - - ReleaseDate returnValue = new ReleaseDate(); - switch (cacheStatus) - { - case Storage.CacheStatus.NotPresent: - returnValue = await GetObjectFromServer(searchValue); - Storage.NewCacheValue(returnValue); - break; - case Storage.CacheStatus.Expired: - try - { - returnValue = await GetObjectFromServer(searchValue); - Storage.NewCacheValue(returnValue, true); - } - catch (Exception ex) - { - Logging.Log(Logging.LogType.Warning, "Metadata: " + returnValue.GetType().Name, "An error occurred while connecting to IGDB. Id: " + searchValue, ex); - returnValue = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - } - break; - case Storage.CacheStatus.Current: - returnValue = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - break; - default: - throw new Exception("How did you get here?"); - } - - return returnValue; - } - - private static async Task GetObjectFromServer(long searchValue) - { - // get ReleaseDates metadata - Communications comms = new Communications(); - var results = await comms.APIComm(Communications.MetadataEndpoint.ReleaseDate, searchValue); - var result = results.First(); - - return result; - } } } diff --git a/gaseous-server/Classes/Metadata/Screenshots.cs b/gaseous-server/Classes/Metadata/Screenshots.cs index 4dac114..f8f57c4 100644 --- a/gaseous-server/Classes/Metadata/Screenshots.cs +++ b/gaseous-server/Classes/Metadata/Screenshots.cs @@ -1,6 +1,5 @@ using System; -using IGDB; -using IGDB.Models; +using HasheousClient.Models.Metadata.IGDB; namespace gaseous_server.Classes.Metadata @@ -13,7 +12,7 @@ namespace gaseous_server.Classes.Metadata { } - public static Screenshot? GetScreenshot(long? Id, string ImagePath, bool GetImages) + public static Screenshot? GetScreenshot(HasheousClient.Models.MetadataModel.MetadataSources SourceType, long? Id) { if ((Id == 0) || (Id == null)) { @@ -21,75 +20,10 @@ namespace gaseous_server.Classes.Metadata } else { - Task RetVal = _GetScreenshot((long)Id, ImagePath, GetImages); - return RetVal.Result; + Screenshot? RetVal = Metadata.GetMetadata(SourceType, (long)Id, false); + return RetVal; } } - - private static async Task _GetScreenshot(long searchValue, string ImagePath, bool GetImages = true) - { - // check database first - Storage.CacheStatus? cacheStatus = Storage.GetCacheStatus("Screenshot", searchValue); - - Screenshot returnValue = new Screenshot(); - bool forceImageDownload = false; - ImagePath = Path.Combine(ImagePath, "Screenshots"); - switch (cacheStatus) - { - case Storage.CacheStatus.NotPresent: - returnValue = await GetObjectFromServer(searchValue, ImagePath); - Storage.NewCacheValue(returnValue); - forceImageDownload = true; - break; - case Storage.CacheStatus.Expired: - try - { - returnValue = await GetObjectFromServer(searchValue, ImagePath); - Storage.NewCacheValue(returnValue, true); - - // check if old value is different from the new value - only download if it's different - Screenshot oldImage = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - if (oldImage.ImageId != returnValue.ImageId) - { - forceImageDownload = true; - } - } - catch (Exception ex) - { - Logging.Log(Logging.LogType.Warning, "Metadata: " + returnValue.GetType().Name, "An error occurred while connecting to IGDB. Id: " + searchValue, ex); - returnValue = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - } - break; - case Storage.CacheStatus.Current: - returnValue = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - break; - default: - throw new Exception("How did you get here?"); - } - - if (GetImages == true) - { - if (forceImageDownload == true) - { - Logging.Log(Logging.LogType.Information, "Metadata: " + returnValue.GetType().Name, "Screenshot download forced."); - - Communications comms = new Communications(); - comms.GetSpecificImageFromServer(ImagePath, returnValue.ImageId, Communications.IGDBAPI_ImageSize.original, null); - } - } - - return returnValue; - } - - private static async Task GetObjectFromServer(long searchValue, string ImagePath) - { - // get Screenshot metadata - Communications comms = new Communications(); - var results = await comms.APIComm(Communications.MetadataEndpoint.Screenshot, searchValue); - var result = results.First(); - - return result; - } } } diff --git a/gaseous-server/Classes/Metadata/Storage.cs b/gaseous-server/Classes/Metadata/Storage.cs index 03fdc68..cc8ecc9 100644 --- a/gaseous-server/Classes/Metadata/Storage.cs +++ b/gaseous-server/Classes/Metadata/Storage.cs @@ -9,23 +9,79 @@ namespace gaseous_server.Classes.Metadata { public class Storage { + /// + /// Cache status of a record + /// public enum CacheStatus { + /// + /// The record is not present in the database + /// NotPresent, + + /// + /// The record is present in the database and is current + /// Current, + + /// + /// The record is present in the database but is expired + /// Expired } - public static CacheStatus GetCacheStatus(string Endpoint, string Slug) + /// + /// Get the cache status of a record in the database + /// + /// + /// The source of the metadata (IGDB, RAWG, etc.) + /// + /// + /// The endpoint of the metadata (games, companies, etc.) + /// + /// + /// The slug of the metadata record + /// + /// + /// The cache status of the record + /// + public static CacheStatus GetCacheStatus(HasheousClient.Models.MetadataModel.MetadataSources SourceType, string Endpoint, string Slug) { - return _GetCacheStatus(Endpoint, "slug", Slug); + return _GetCacheStatus(SourceType, Endpoint, "slug", Slug); } - public static CacheStatus GetCacheStatus(string Endpoint, long Id) + /// + /// Get the cache status of a record in the database + /// + /// + /// The source of the metadata (IGDB, RAWG, etc.) + /// + /// + /// The endpoint of the metadata (games, companies, etc.) + /// + /// + /// The ID of the metadata record + /// + /// + /// The cache status of the record + /// + public static CacheStatus GetCacheStatus(HasheousClient.Models.MetadataModel.MetadataSources SourceType, string Endpoint, long Id) { - return _GetCacheStatus(Endpoint, "id", Id); + return _GetCacheStatus(SourceType, Endpoint, "id", Id); } + /// + /// Get the cache status of a record in the database + /// + /// + /// The DataRow object to check + /// + /// + /// The cache status of the record + /// + /// + /// Thrown when the DataRow object does not contain a "lastUpdated" column + /// public static CacheStatus GetCacheStatus(DataRow Row) { if (Row.Table.Columns.Contains("lastUpdated")) @@ -46,13 +102,14 @@ namespace gaseous_server.Classes.Metadata } } - private static CacheStatus _GetCacheStatus(string Endpoint, string SearchField, object SearchValue) + private static CacheStatus _GetCacheStatus(HasheousClient.Models.MetadataModel.MetadataSources SourceType, string Endpoint, string SearchField, object SearchValue) { Database db = new Database(Database.databaseType.MySql, Config.DatabaseConfiguration.ConnectionString); - string sql = "SELECT lastUpdated FROM " + Endpoint + " WHERE " + SearchField + " = @" + SearchField; + string sql = "SELECT lastUpdated FROM " + Endpoint + " WHERE SourceId = @SourceType AND " + SearchField + " = @" + SearchField; Dictionary dbDict = new Dictionary(); + dbDict.Add("SourceType", SourceType); dbDict.Add("Endpoint", Endpoint); dbDict.Add(SearchField, SearchValue); @@ -76,16 +133,41 @@ namespace gaseous_server.Classes.Metadata } } - public static void NewCacheValue(object ObjectToCache, bool UpdateRecord = false) + /// + /// Add a new record to the cache + /// + /// + /// The source of the metadata (IGDB, RAWG, etc.) + /// + /// + /// The object to cache + /// + /// + /// Whether to update the record if it already exists + /// + public static void NewCacheValue(HasheousClient.Models.MetadataModel.MetadataSources SourceType, T ObjectToCache, bool UpdateRecord = false) { // get the object type name string ObjectTypeName = ObjectToCache.GetType().Name; // build dictionary - string objectJson = Newtonsoft.Json.JsonConvert.SerializeObject(ObjectToCache); - Dictionary objectDict = Newtonsoft.Json.JsonConvert.DeserializeObject>(objectJson); - objectDict.Add("dateAdded", DateTime.UtcNow); - objectDict.Add("lastUpdated", DateTime.UtcNow); + Dictionary objectDict = new Dictionary + { + { "SourceId", SourceType }, + { "dateAdded", DateTime.UtcNow }, + { "lastUpdated", DateTime.UtcNow } + }; + foreach (PropertyInfo property in ObjectToCache.GetType().GetProperties()) + { + if (property.GetCustomAttribute() == null) + { + object? propertyValue = property.GetValue(ObjectToCache); + if (propertyValue != null) + { + objectDict.Add(property.Name, propertyValue); + } + } + } // generate sql string fieldList = ""; @@ -135,6 +217,12 @@ namespace gaseous_server.Classes.Metadata newObjectValue = Newtonsoft.Json.JsonConvert.SerializeObject(newDict["Ids"]); objectDict[key.Key] = newObjectValue; + StoreRelations(ObjectTypeName, key.Key, (long)objectDict["Id"], newObjectValue); + break; + case "list": + newObjectValue = Newtonsoft.Json.JsonConvert.SerializeObject(objectValue); + objectDict[key.Key] = newObjectValue; + StoreRelations(ObjectTypeName, key.Key, (long)objectDict["Id"], newObjectValue); break; @@ -163,15 +251,40 @@ namespace gaseous_server.Classes.Metadata db.ExecuteCMD(sql, objectDict); } - public static T GetCacheValue(T EndpointType, string SearchField, object SearchValue) + /// + /// Get a record from the cache + /// + /// + /// The type of the object to return + /// + /// + /// The source of the metadata (IGDB, RAWG, etc.) + /// + /// + /// The type of the endpoint (games, companies, etc.) + /// + /// + /// The field to search for the record by + /// + /// + /// The value to search for + /// + /// + /// The object from the cache + /// + /// + /// Thrown when no record is found that matches the search criteria + /// + public static T GetCacheValue(HasheousClient.Models.MetadataModel.MetadataSources SourceType, T? EndpointType, string SearchField, object SearchValue) { string Endpoint = EndpointType.GetType().Name; Database db = new Database(Database.databaseType.MySql, Config.DatabaseConfiguration.ConnectionString); - string sql = "SELECT * FROM " + Endpoint + " WHERE " + SearchField + " = @" + SearchField; + string sql = "SELECT * FROM " + Endpoint + " WHERE SourceId = @SourceType AND " + SearchField + " = @" + SearchField; Dictionary dbDict = new Dictionary(); + dbDict.Add("SourceType", SourceType); dbDict.Add("Endpoint", Endpoint); dbDict.Add(SearchField, SearchValue); @@ -192,202 +305,63 @@ namespace gaseous_server.Classes.Metadata public static T BuildCacheObject(T EndpointType, DataRow dataRow) { + // copy the DataRow to EndpointType foreach (PropertyInfo property in EndpointType.GetType().GetProperties()) { - if (dataRow.Table.Columns.Contains(property.Name)) + if (property.GetCustomAttribute() == null) { - if (dataRow[property.Name] != DBNull.Value) + // get the value from the DataRow with the same name as the property + object? value = dataRow[property.Name]; + + if (value != null && value != DBNull.Value) { - string objectTypeName = property.PropertyType.Name.ToLower().Split("`")[0]; - string subObjectTypeName = ""; - object? objectToStore = null; - if (objectTypeName == "nullable") + // check the property type - if it's a list or array, deserialize it. Otherwise, just set the value + Type objectType = EndpointType.GetType(); + if (objectType != null) { - objectTypeName = property.PropertyType.UnderlyingSystemType.ToString().Split("`1")[1].Replace("[System.", "").Replace("]", "").ToLower(); - } - try - { - switch (objectTypeName) + // fullname = System.Nullable`1[[System.DateTimeOffset, + string propertyTypeName = property.PropertyType.FullName.Split(",")[0]; + bool isNullable = false; + if (propertyTypeName.StartsWith("System.Nullable")) { - //case "boolean": - // Boolean storedBool = Convert.ToBoolean((int)dataRow[property.Name]); - // property.SetValue(EndpointType, storedBool); - // break; - case "datetimeoffset": - DateTimeOffset? storedDate = (DateTime?)dataRow[property.Name]; - property.SetValue(EndpointType, storedDate); - break; - //case "nullable": - // Console.WriteLine("Nullable: " + property.PropertyType.UnderlyingSystemType); - // break; - case "identityorvalue": - subObjectTypeName = property.PropertyType.UnderlyingSystemType.ToString().Split("`1")[1].Replace("[IGDB.Models.", "").Replace("]", "").ToLower(); + isNullable = true; + propertyTypeName = propertyTypeName.Split("[[")[1]; + } + propertyTypeName = propertyTypeName.Split("`")[0]; - switch (subObjectTypeName) - { - case "collection": - objectToStore = new IdentityOrValue(id: (long)dataRow[property.Name]); - break; - case "company": - objectToStore = new IdentityOrValue(id: (long)dataRow[property.Name]); - break; - case "cover": - objectToStore = new IdentityOrValue(id: (long)dataRow[property.Name]); - break; - case "franchise": - objectToStore = new IdentityOrValue(id: (long)dataRow[property.Name]); - break; - case "game": - objectToStore = new IdentityOrValue(id: (long)dataRow[property.Name]); - break; - case "platformfamily": - objectToStore = new IdentityOrValue(id: (long)dataRow[property.Name]); - break; - case "platformlogo": - objectToStore = new IdentityOrValue(id: (long)dataRow[property.Name]); - break; - case "platformversioncompany": - objectToStore = new IdentityOrValue(id: (long)dataRow[property.Name]); - break; - } + switch (propertyTypeName.ToLower()) + { + case "system.collections.generic.list": + var listArray = Newtonsoft.Json.JsonConvert.DeserializeObject>(value.ToString()); + property.SetValue(EndpointType, listArray); + break; - if (objectToStore != null) - { - property.SetValue(EndpointType, objectToStore); - } + case "system.int32[]": + var int32array = Newtonsoft.Json.JsonConvert.DeserializeObject(value.ToString()); + property.SetValue(EndpointType, int32array); + break; + case "system.datetimeoffset": + property.SetValue(EndpointType, (DateTimeOffset)(DateTime?)value); break; - case "identitiesorvalues": - subObjectTypeName = property.PropertyType.UnderlyingSystemType.ToString().Split("`1")[1].Replace("[IGDB.Models.", "").Replace("]", "").ToLower(); - long[] fromJsonObject = Newtonsoft.Json.JsonConvert.DeserializeObject((string)dataRow[property.Name]); - - switch (subObjectTypeName) - { - case "agerating": - objectToStore = new IdentitiesOrValues(ids: fromJsonObject); - break; - case "alternativename": - objectToStore = new IdentitiesOrValues(ids: fromJsonObject); - break; - case "artwork": - objectToStore = new IdentitiesOrValues(ids: fromJsonObject); - break; - case "ageratingcontentdescription": - objectToStore = new IdentitiesOrValues(ids: fromJsonObject); - break; - case "game": - objectToStore = new IdentitiesOrValues(ids: fromJsonObject); - break; - case "externalgame": - objectToStore = new IdentitiesOrValues(ids: fromJsonObject); - break; - case "franchise": - objectToStore = new IdentitiesOrValues(ids: fromJsonObject); - break; - case "gameengine": - objectToStore = new IdentitiesOrValues(ids: fromJsonObject); - break; - case "gamemode": - objectToStore = new IdentitiesOrValues(ids: fromJsonObject); - break; - case "gamevideo": - objectToStore = new IdentitiesOrValues(ids: fromJsonObject); - break; - case "genre": - objectToStore = new IdentitiesOrValues(ids: fromJsonObject); - break; - case "involvedcompany": - objectToStore = new IdentitiesOrValues(ids: fromJsonObject); - break; - case "multiplayermode": - objectToStore = new IdentitiesOrValues(ids: fromJsonObject); - break; - case "platform": - objectToStore = new IdentitiesOrValues(ids: fromJsonObject); - break; - case "platformversion": - objectToStore = new IdentitiesOrValues(ids: fromJsonObject); - break; - case "platformwebsite": - objectToStore = new IdentitiesOrValues(ids: fromJsonObject); - break; - case "platformversioncompany": - objectToStore = new IdentitiesOrValues(ids: fromJsonObject); - break; - case "platformversionreleasedate": - objectToStore = new IdentitiesOrValues(ids: fromJsonObject); - break; - case "playerperspective": - objectToStore = new IdentitiesOrValues(ids: fromJsonObject); - break; - case "releasedate": - objectToStore = new IdentitiesOrValues(ids: fromJsonObject); - break; - case "screenshot": - objectToStore = new IdentitiesOrValues(ids: fromJsonObject); - break; - case "theme": - objectToStore = new IdentitiesOrValues(ids: fromJsonObject); - break; - case "website": - objectToStore = new IdentitiesOrValues(ids: fromJsonObject); - break; - } - - if (objectToStore != null) - { - property.SetValue(EndpointType, objectToStore); - } - - break; - case "int32[]": - Int32[] fromJsonObject_int32Array = Newtonsoft.Json.JsonConvert.DeserializeObject((string)dataRow[property.Name]); - if (fromJsonObject_int32Array != null) - { - property.SetValue(EndpointType, fromJsonObject_int32Array); - } - break; - case "[igdb.models.category": - property.SetValue(EndpointType, (Category)dataRow[property.Name]); - break; - case "[igdb.models.gamestatus": - property.SetValue(EndpointType, (GameStatus)dataRow[property.Name]); - break; - case "[igdb.models.ageratingcategory": - property.SetValue(EndpointType, (AgeRatingCategory)dataRow[property.Name]); - break; - case "[igdb.models.ageratingcontentdescriptioncategory": - property.SetValue(EndpointType, (AgeRatingContentDescriptionCategory)dataRow[property.Name]); - break; - case "[igdb.models.ageratingtitle": - property.SetValue(EndpointType, (AgeRatingTitle)dataRow[property.Name]); - break; - case "[igdb.models.externalcategory": - property.SetValue(EndpointType, (ExternalCategory)dataRow[property.Name]); - break; - case "[igdb.models.startdatecategory": - property.SetValue(EndpointType, (StartDateCategory)dataRow[property.Name]); - break; - case "[igdb.models.releasedateregion": - property.SetValue(EndpointType, (ReleaseDateRegion)dataRow[property.Name]); - break; - case "[igdb.models.releasedatecategory": - property.SetValue(EndpointType, (ReleaseDateCategory)dataRow[property.Name]); - break; - case "[gaseous_server.classes.metadata.agegroups+agerestrictiongroupings": - property.SetValue(EndpointType, (AgeGroups.AgeRestrictionGroupings)dataRow[property.Name]); - break; default: - property.SetValue(EndpointType, dataRow[property.Name]); + // check if property is an enum + if (property.PropertyType.IsEnum) + { + property.SetValue(EndpointType, Enum.Parse(property.PropertyType, value.ToString())); + } + else if (Common.IsNullableEnum(property.PropertyType)) + { + property.SetValue(EndpointType, Enum.Parse(Nullable.GetUnderlyingType(property.PropertyType), value.ToString())); + } + else + { + property.SetValue(EndpointType, value); + } break; } } - catch (Exception ex) - { - Console.WriteLine("Error occurred in column " + property.Name); - Console.WriteLine(ex.ToString()); - } } } } diff --git a/gaseous-server/Classes/Metadata/Themes.cs b/gaseous-server/Classes/Metadata/Themes.cs index fe3c5c6..1cf881e 100644 --- a/gaseous-server/Classes/Metadata/Themes.cs +++ b/gaseous-server/Classes/Metadata/Themes.cs @@ -1,6 +1,5 @@ using System; -using IGDB; -using IGDB.Models; +using HasheousClient.Models.Metadata.IGDB; namespace gaseous_server.Classes.Metadata @@ -13,7 +12,7 @@ namespace gaseous_server.Classes.Metadata { } - public static Theme? GetGame_Themes(long? Id) + public static Theme? GetGame_Themes(HasheousClient.Models.MetadataModel.MetadataSources SourceType, long? Id) { if ((Id == 0) || (Id == null)) { @@ -21,56 +20,10 @@ namespace gaseous_server.Classes.Metadata } else { - Task RetVal = _GetGame_Themes((long)Id); - return RetVal.Result; + Theme? RetVal = Metadata.GetMetadata(SourceType, (long)Id, false); + return RetVal; } } - - private static async Task _GetGame_Themes(long searchValue) - { - // check database first - Storage.CacheStatus? cacheStatus = Storage.GetCacheStatus("Theme", searchValue); - - Theme returnValue = new Theme(); - bool forceImageDownload = false; - switch (cacheStatus) - { - case Storage.CacheStatus.NotPresent: - returnValue = await GetObjectFromServer(searchValue); - Storage.NewCacheValue(returnValue); - forceImageDownload = true; - break; - case Storage.CacheStatus.Expired: - try - { - returnValue = await GetObjectFromServer(searchValue); - Storage.NewCacheValue(returnValue, true); - return returnValue; - } - catch (Exception ex) - { - Logging.Log(Logging.LogType.Warning, "Metadata: " + returnValue.GetType().Name, "An error occurred while connecting to IGDB. Id: " + searchValue, ex); - return Storage.GetCacheValue(returnValue, "id", (long)searchValue); - } - case Storage.CacheStatus.Current: - returnValue = Storage.GetCacheValue(returnValue, "id", (long)searchValue); - break; - default: - throw new Exception("How did you get here?"); - } - - return returnValue; - } - - private static async Task GetObjectFromServer(long searchValue) - { - // get Game_Themes metadata - Communications comms = new Communications(); - var results = await comms.APIComm(Communications.MetadataEndpoint.Theme, searchValue); - var result = results.First(); - - return result; - } } } diff --git a/gaseous-server/Classes/MetadataManagement.cs b/gaseous-server/Classes/MetadataManagement.cs index 281133f..bdd4ae2 100644 --- a/gaseous-server/Classes/MetadataManagement.cs +++ b/gaseous-server/Classes/MetadataManagement.cs @@ -1,5 +1,6 @@ using System; using System.Data; +using gaseous_server.Classes.Metadata; using gaseous_server.Models; namespace gaseous_server.Classes @@ -8,10 +9,10 @@ namespace gaseous_server.Classes { public void RefreshMetadata(bool forceRefresh = false) { - Database db = new Database(Database.databaseType.MySql, Config.DatabaseConfiguration.ConnectionString); - string sql = ""; + Database db = new Database(Database.databaseType.MySql, Config.DatabaseConfiguration.ConnectionString); + string sql = ""; DataTable dt = new DataTable(); - + // disabling forceRefresh forceRefresh = false; @@ -27,7 +28,7 @@ namespace gaseous_server.Classes try { Logging.Log(Logging.LogType.Information, "Metadata Refresh", "(" + StatusCounter + "/" + dt.Rows.Count + "): Refreshing metadata for platform " + dr["name"] + " (" + dr["id"] + ")"); - Metadata.Platforms.GetPlatform((long)dr["id"], true); + Metadata.Platforms.GetPlatform((long)dr["id"]); } catch (Exception ex) { @@ -59,7 +60,7 @@ namespace gaseous_server.Classes try { Logging.Log(Logging.LogType.Information, "Metadata Refresh", "(" + StatusCounter + "/" + dt.Rows.Count + "): Refreshing metadata for game " + dr["name"] + " (" + dr["id"] + ")"); - Metadata.Games.GetGame((long)dr["id"], true, false, true); + Metadata.Games.GetGame(Communications.MetadataSource, (long)dr["id"]); } catch (Exception ex) { @@ -69,7 +70,7 @@ namespace gaseous_server.Classes StatusCounter += 1; } ClearStatus(); - } + } } } diff --git a/gaseous-server/Classes/RomMediaGroup.cs b/gaseous-server/Classes/RomMediaGroup.cs index be65c69..7c9f3b0 100644 --- a/gaseous-server/Classes/RomMediaGroup.cs +++ b/gaseous-server/Classes/RomMediaGroup.cs @@ -2,12 +2,12 @@ using System; using System.Data; using gaseous_signature_parser.models.RomSignatureObject; using Microsoft.VisualBasic; -using IGDB.Models; using gaseous_server.Classes.Metadata; using System.IO.Compression; using SharpCompress.Archives; using SharpCompress.Common; using gaseous_server.Models; +using HasheousClient.Models.Metadata.IGDB; namespace gaseous_server.Classes { @@ -296,8 +296,8 @@ namespace gaseous_server.Classes GameRomMediaGroupItem mediaGroupItem = GetMediaGroup(Id); if (mediaGroupItem.Status == GameRomMediaGroupItem.GroupBuildStatus.WaitingForBuild) { - Game GameObject = Games.GetGame(mediaGroupItem.GameId, false, false, false); - Platform PlatformObject = Platforms.GetPlatform(mediaGroupItem.PlatformId, false); + Models.Game GameObject = Games.GetGame(Communications.MetadataSource, mediaGroupItem.GameId); + Platform PlatformObject = Platforms.GetPlatform(mediaGroupItem.PlatformId); PlatformMapping.PlatformMapItem platformMapItem = PlatformMapping.GetPlatformMap(mediaGroupItem.PlatformId); Logging.Log(Logging.LogType.Information, "Media Group", "Beginning build of media group: " + GameObject.Name + " for platform " + PlatformObject.Name); @@ -557,7 +557,7 @@ namespace gaseous_server.Classes { try { - return Platforms.GetPlatform(PlatformId, false).Name; + return Platforms.GetPlatform(PlatformId).Name; } catch { diff --git a/gaseous-server/Classes/Roms.cs b/gaseous-server/Classes/Roms.cs index 76b99d0..94b3494 100644 --- a/gaseous-server/Classes/Roms.cs +++ b/gaseous-server/Classes/Roms.cs @@ -3,7 +3,6 @@ using System.Data; using gaseous_signature_parser.models.RomSignatureObject; using static gaseous_server.Classes.RomMediaGroup; using gaseous_server.Classes.Metadata; -using IGDB.Models; using static HasheousClient.Models.FixMatchModel; using NuGet.Protocol.Core.Types; using static gaseous_server.Classes.FileSignature; @@ -154,10 +153,10 @@ namespace gaseous_server.Classes public static GameRomItem UpdateRom(long RomId, long PlatformId, long GameId) { // ensure metadata for platformid is present - IGDB.Models.Platform platform = Classes.Metadata.Platforms.GetPlatform(PlatformId); + HasheousClient.Models.Metadata.IGDB.Platform platform = Classes.Metadata.Platforms.GetPlatform(PlatformId); // ensure metadata for gameid is present - IGDB.Models.Game game = Classes.Metadata.Games.GetGame(GameId, false, false, false); + Models.Game game = Classes.Metadata.Games.GetGame(Communications.MetadataSource, GameId); Database db = new Database(Database.databaseType.MySql, Config.DatabaseConfiguration.ConnectionString); string sql = "UPDATE Games_Roms SET PlatformId=@platformid, GameId=@gameid WHERE Id = @id"; diff --git a/gaseous-server/Classes/UserProfile.cs b/gaseous-server/Classes/UserProfile.cs index db662e1..bdc78c6 100644 --- a/gaseous-server/Classes/UserProfile.cs +++ b/gaseous-server/Classes/UserProfile.cs @@ -1,6 +1,5 @@ using System.Data; using gaseous_server.Classes.Metadata; -using IGDB.Models; namespace gaseous_server.Classes { @@ -62,8 +61,8 @@ namespace gaseous_server.Classes { NowPlaying = new Models.UserProfile.NowPlayingItem { - Game = Games.GetGame((long)nowPlayingData.Rows[0]["GameId"], false, false, false), - Platform = Platforms.GetPlatform((long)nowPlayingData.Rows[0]["PlatformId"], false, false), + Game = Games.GetGame(Communications.MetadataSource, (long)nowPlayingData.Rows[0]["GameId"]), + Platform = Platforms.GetPlatform((long)nowPlayingData.Rows[0]["PlatformId"]), Duration = Convert.ToInt64(nowPlayingData.Rows[0]["SessionLength"]) }; } diff --git a/gaseous-server/Controllers/V1.0/BiosController.cs b/gaseous-server/Controllers/V1.0/BiosController.cs index c2cfc2b..303e95d 100644 --- a/gaseous-server/Controllers/V1.0/BiosController.cs +++ b/gaseous-server/Controllers/V1.0/BiosController.cs @@ -10,8 +10,8 @@ using Asp.Versioning; using Authentication; using Microsoft.AspNetCore.Identity; using gaseous_server.Models; -using IGDB.Models; using gaseous_server.Classes.Metadata; +using HasheousClient.Models.Metadata.IGDB; namespace gaseous_server.Controllers { diff --git a/gaseous-server/Controllers/V1.0/GamesController.cs b/gaseous-server/Controllers/V1.0/GamesController.cs index 55dc3e9..3f0a313 100644 --- a/gaseous-server/Controllers/V1.0/GamesController.cs +++ b/gaseous-server/Controllers/V1.0/GamesController.cs @@ -10,7 +10,6 @@ using Authentication; using gaseous_server.Classes; using gaseous_server.Classes.Metadata; using gaseous_server.Models; -using IGDB.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; @@ -19,6 +18,7 @@ using Microsoft.CodeAnalysis.Scripting; using static gaseous_server.Classes.Metadata.AgeRatings; using Asp.Versioning; using static gaseous_server.Models.PlatformMapping; +using HasheousClient.Models.Metadata.IGDB; namespace gaseous_server.Controllers { @@ -43,7 +43,7 @@ namespace gaseous_server.Controllers [MapToApiVersion("1.0")] [HttpGet] - [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] public async Task Game( string name = "", string platform = "", @@ -59,7 +59,7 @@ namespace gaseous_server.Controllers return Ok(GetGames(name, platform, genre, gamemode, playerperspective, theme, minrating, maxrating, "Adult", true, true, sortdescending)); } - public static List GetGames( + public static List GetGames( string name = "", string platform = "", string genre = "", @@ -283,7 +283,7 @@ namespace gaseous_server.Controllers Database db = new Database(Database.databaseType.MySql, Config.DatabaseConfiguration.ConnectionString); string sql = "SELECT DISTINCT view_Games_Roms.GameId AS ROMGameId, Game.*, case when Game.`Name` like 'The %' then CONCAT(trim(substr(Game.`Name` from 4)), ', The') else Game.`Name` end as NameThe FROM view_Games_Roms LEFT JOIN Game ON Game.Id = view_Games_Roms.GameId LEFT JOIN Relation_Game_Genres ON Game.Id = Relation_Game_Genres.GameId LEFT JOIN Relation_Game_GameModes ON Game.Id = Relation_Game_GameModes.GameId LEFT JOIN Relation_Game_PlayerPerspectives ON Game.Id = Relation_Game_PlayerPerspectives.GameId LEFT JOIN Relation_Game_Themes ON Game.Id = Relation_Game_Themes.GameId LEFT JOIN (SELECT Relation_Game_AgeRatings.GameId, AgeRating.* FROM Relation_Game_AgeRatings JOIN AgeRating ON Relation_Game_AgeRatings.AgeRatingsId = AgeRating.Id) view_AgeRatings ON Game.Id = view_AgeRatings.GameId " + whereClause + " " + havingClause + " " + orderByClause; - List RetVal = new List(); + List RetVal = new List(); DataTable dbResponse = db.ExecuteCMD(sql, whereParams); foreach (DataRow dr in dbResponse.Rows) @@ -299,14 +299,14 @@ namespace gaseous_server.Controllers [MapToApiVersion("1.1")] [HttpGet] [Route("{GameId}")] - [ProducesResponseType(typeof(Game), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(gaseous_server.Models.Game), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ResponseCache(CacheProfileName = "5Minute")] public async Task Game(long GameId) { try { - Game game = Classes.Metadata.Games.GetGame(GameId, false, false, false); + gaseous_server.Models.Game game = Classes.Metadata.Games.GetGame(Communications.MetadataSource, GameId); if (game != null) { @@ -334,14 +334,14 @@ namespace gaseous_server.Controllers { try { - Game gameObject = Classes.Metadata.Games.GetGame(GameId, false, false, false); + gaseous_server.Models.Game game = Classes.Metadata.Games.GetGame(Communications.MetadataSource, GameId); - if (gameObject.AlternativeNames != null) + if (game.AlternativeNames != null) { List altNames = new List(); - foreach (long altNameId in gameObject.AlternativeNames.Ids) + foreach (long altNameId in game.AlternativeNames) { - altNames.Add(AlternativeNames.GetAlternativeNames(altNameId)); + altNames.Add(AlternativeNames.GetAlternativeNames(game.MetadataSource, altNameId)); } return Ok(altNames); } @@ -367,14 +367,14 @@ namespace gaseous_server.Controllers { try { - Game gameObject = Classes.Metadata.Games.GetGame(GameId, false, false, false); + gaseous_server.Models.Game game = Classes.Metadata.Games.GetGame(Communications.MetadataSource, GameId); - if (gameObject.AgeRatings != null) + if (game.AgeRatings != null) { List ageRatings = new List(); - foreach (long ageRatingId in gameObject.AgeRatings.Ids) + foreach (long ageRatingId in game.AgeRatings) { - ageRatings.Add(AgeRatings.GetConsolidatedAgeRating(ageRatingId)); + ageRatings.Add(AgeRatings.GetConsolidatedAgeRating(game.MetadataSource, ageRatingId)); } return Ok(ageRatings); } @@ -400,14 +400,14 @@ namespace gaseous_server.Controllers { try { - Game gameObject = Classes.Metadata.Games.GetGame(GameId, false, false, false); + gaseous_server.Models.Game game = Classes.Metadata.Games.GetGame(Communications.MetadataSource, GameId); List artworks = new List(); - if (gameObject.Artworks != null) + if (game.Artworks != null) { - foreach (long ArtworkId in gameObject.Artworks.Ids) + foreach (long ArtworkId in game.Artworks) { - Artwork GameArtwork = Artworks.GetArtwork(ArtworkId, Config.LibraryConfiguration.LibraryMetadataDirectory_Game(gameObject), false); + Artwork GameArtwork = Artworks.GetArtwork(game.MetadataSource, ArtworkId); artworks.Add(GameArtwork); } } @@ -431,11 +431,11 @@ namespace gaseous_server.Controllers { try { - IGDB.Models.Game gameObject = Classes.Metadata.Games.GetGame(GameId, false, false, false); + gaseous_server.Models.Game game = Classes.Metadata.Games.GetGame(Communications.MetadataSource, GameId); try { - IGDB.Models.Artwork artworkObject = Artworks.GetArtwork(ArtworkId, Config.LibraryConfiguration.LibraryMetadataDirectory_Game(gameObject), false); + Artwork artworkObject = Artworks.GetArtwork(game.MetadataSource, ArtworkId); if (artworkObject != null) { return Ok(artworkObject); @@ -467,10 +467,10 @@ namespace gaseous_server.Controllers { try { - IGDB.Models.Game gameObject = Classes.Metadata.Games.GetGame(GameId, false, false, false); - if (gameObject != null) + gaseous_server.Models.Game game = Classes.Metadata.Games.GetGame(Communications.MetadataSource, GameId); + if (game != null) { - IGDB.Models.Cover coverObject = Covers.GetCover(gameObject.Cover.Id, Config.LibraryConfiguration.LibraryMetadataDirectory_Game(gameObject), false); + Cover coverObject = Covers.GetCover(game.MetadataSource, (long?)game.Cover); if (coverObject != null) { return Ok(coverObject); @@ -502,7 +502,7 @@ namespace gaseous_server.Controllers { try { - IGDB.Models.Game gameObject = Classes.Metadata.Games.GetGame(GameId, false, false, false); + gaseous_server.Models.Game game = Classes.Metadata.Games.GetGame(Communications.MetadataSource, GameId); string? imageId = null; string? imageTypePath = null; @@ -510,14 +510,11 @@ namespace gaseous_server.Controllers switch (imageType) { case MetadataImageType.cover: - if (gameObject.Cover != null) + if (game.Cover != null) { - if (gameObject.Cover.Id != null) - { - IGDB.Models.Cover cover = Classes.Metadata.Covers.GetCover(gameObject.Cover.Id, Config.LibraryConfiguration.LibraryMetadataDirectory_Game(gameObject), false); - imageId = cover.ImageId; - imageTypePath = "Covers"; - } + Cover cover = Classes.Metadata.Covers.GetCover(game.MetadataSource, (long?)game.Cover); + imageId = cover.ImageId; + imageTypePath = "Covers"; } else { @@ -526,11 +523,11 @@ namespace gaseous_server.Controllers break; case MetadataImageType.screenshots: - if (gameObject.Screenshots != null) + if (game.Screenshots != null) { - if (gameObject.Screenshots.Ids.Contains(ImageId)) + if (game.Screenshots.Contains(ImageId)) { - IGDB.Models.Screenshot imageObject = Screenshots.GetScreenshot(ImageId, Config.LibraryConfiguration.LibraryMetadataDirectory_Game(gameObject), true); + Screenshot imageObject = Screenshots.GetScreenshot(game.MetadataSource, ImageId); imageId = imageObject.ImageId; imageTypePath = "Screenshots"; @@ -543,11 +540,11 @@ namespace gaseous_server.Controllers break; case MetadataImageType.artwork: - if (gameObject.Artworks != null) + if (game.Artworks != null) { - if (gameObject.Artworks.Ids.Contains(ImageId)) + if (game.Artworks.Contains(ImageId)) { - IGDB.Models.Artwork imageObject = Artworks.GetArtwork(ImageId, Config.LibraryConfiguration.LibraryMetadataDirectory_Game(gameObject), true); + Artwork imageObject = Artworks.GetArtwork(game.MetadataSource, ImageId); imageId = imageObject.ImageId; imageTypePath = "Artwork"; @@ -568,13 +565,13 @@ namespace gaseous_server.Controllers return NotFound(); } - string basePath = Path.Combine(Config.LibraryConfiguration.LibraryMetadataDirectory_Game(gameObject), imageTypePath); - string imagePath = Path.Combine(Config.LibraryConfiguration.LibraryMetadataDirectory_Game(gameObject), imageTypePath, size.ToString(), imageId + ".jpg"); + string basePath = Path.Combine(Config.LibraryConfiguration.LibraryMetadataDirectory_Game(game), imageTypePath); + string imagePath = Path.Combine(Config.LibraryConfiguration.LibraryMetadataDirectory_Game(game), imageTypePath, size.ToString(), imageId + ".jpg"); if (!System.IO.File.Exists(imagePath)) { Communications comms = new Communications(); - Task ImgFetch = comms.GetSpecificImageFromServer(Path.Combine(Config.LibraryConfiguration.LibraryMetadataDirectory_Game(gameObject), imageTypePath), imageId, size, new List { Communications.IGDBAPI_ImageSize.cover_big, Communications.IGDBAPI_ImageSize.original }); + Task ImgFetch = comms.GetSpecificImageFromServer(Path.Combine(Config.LibraryConfiguration.LibraryMetadataDirectory_Game(game), imageTypePath), imageId, size, new List { Communications.IGDBAPI_ImageSize.cover_big, Communications.IGDBAPI_ImageSize.original }); imagePath = ImgFetch.Result; } @@ -640,9 +637,9 @@ namespace gaseous_server.Controllers { try { - IGDB.Models.Game gameObject = Classes.Metadata.Games.GetGame(GameId, false, false, false); + gaseous_server.Models.Game game = Classes.Metadata.Games.GetGame(Communications.MetadataSource, GameId); - if (gameObject != null) + if (game != null) { var user = await _userManager.GetUserAsync(User); @@ -677,9 +674,9 @@ namespace gaseous_server.Controllers { try { - IGDB.Models.Game gameObject = Classes.Metadata.Games.GetGame(GameId, false, false, false); + gaseous_server.Models.Game game = Classes.Metadata.Games.GetGame(Communications.MetadataSource, GameId); - if (gameObject != null) + if (game != null) { var user = await _userManager.GetUserAsync(User); @@ -715,15 +712,15 @@ namespace gaseous_server.Controllers { try { - IGDB.Models.Game gameObject = Classes.Metadata.Games.GetGame(GameId, false, false, false); - if (gameObject != null) + gaseous_server.Models.Game game = Classes.Metadata.Games.GetGame(Communications.MetadataSource, GameId); + if (game != null) { - List gameModeObjects = new List(); - if (gameObject.GameModes != null) + List gameModeObjects = new List(); + if (game.GameModes != null) { - foreach (long gameModeId in gameObject.GameModes.Ids) + foreach (long gameModeId in game.GameModes) { - gameModeObjects.Add(Classes.Metadata.GameModes.GetGame_Modes(gameModeId)); + gameModeObjects.Add(Classes.Metadata.GameModes.GetGame_Modes(game.MetadataSource, gameModeId)); } } @@ -751,19 +748,19 @@ namespace gaseous_server.Controllers { try { - IGDB.Models.Game gameObject = Classes.Metadata.Games.GetGame(GameId, false, false, false); - if (gameObject != null) + gaseous_server.Models.Game game = Classes.Metadata.Games.GetGame(Communications.MetadataSource, GameId); + if (game != null) { - List genreObjects = new List(); - if (gameObject.Genres != null) + List genreObjects = new List(); + if (game.Genres != null) { - foreach (long genreId in gameObject.Genres.Ids) + foreach (long genreId in game.Genres) { - genreObjects.Add(Classes.Metadata.Genres.GetGenres(genreId)); + genreObjects.Add(Classes.Metadata.Genres.GetGenres(game.MetadataSource, genreId)); } } - List sortedGenreObjects = genreObjects.OrderBy(o => o.Name).ToList(); + List sortedGenreObjects = genreObjects.OrderBy(o => o.Name).ToList(); return Ok(sortedGenreObjects); } @@ -789,16 +786,16 @@ namespace gaseous_server.Controllers { try { - IGDB.Models.Game gameObject = Classes.Metadata.Games.GetGame(GameId, false, false, false); - if (gameObject != null) + gaseous_server.Models.Game game = Classes.Metadata.Games.GetGame(Communications.MetadataSource, GameId); + if (game != null) { List> icObjects = new List>(); - if (gameObject.InvolvedCompanies != null) + if (game.InvolvedCompanies != null) { - foreach (long icId in gameObject.InvolvedCompanies.Ids) + foreach (long icId in game.InvolvedCompanies) { InvolvedCompany involvedCompany = Classes.Metadata.InvolvedCompanies.GetInvolvedCompanies(icId); - Company company = Classes.Metadata.Companies.GetCompanies(involvedCompany.Company.Id); + Company company = Classes.Metadata.Companies.GetCompanies(game.MetadataSource, (long?)involvedCompany.Company); company.Developed = null; company.Published = null; @@ -834,14 +831,14 @@ namespace gaseous_server.Controllers { try { - IGDB.Models.Game gameObject = Classes.Metadata.Games.GetGame(GameId, false, false, false); - if (gameObject != null) + gaseous_server.Models.Game game = Classes.Metadata.Games.GetGame(Communications.MetadataSource, GameId); + if (game != null) { List> icObjects = new List>(); - if (gameObject.InvolvedCompanies != null) + if (game.InvolvedCompanies != null) { InvolvedCompany involvedCompany = Classes.Metadata.InvolvedCompanies.GetInvolvedCompanies(CompanyId); - Company company = Classes.Metadata.Companies.GetCompanies(involvedCompany.Company.Id); + Company company = Classes.Metadata.Companies.GetCompanies(game.MetadataSource, (long?)involvedCompany.Company); company.Developed = null; company.Published = null; @@ -877,10 +874,10 @@ namespace gaseous_server.Controllers { try { - IGDB.Models.Game gameObject = Classes.Metadata.Games.GetGame(GameId, false, false, false); + gaseous_server.Models.Game game = Classes.Metadata.Games.GetGame(Communications.MetadataSource, GameId); InvolvedCompany involvedCompany = Classes.Metadata.InvolvedCompanies.GetInvolvedCompanies(CompanyId); - Company company = Classes.Metadata.Companies.GetCompanies(involvedCompany.Company.Id); + Company company = Classes.Metadata.Companies.GetCompanies(game.MetadataSource, (long?)involvedCompany.Company); string coverFilePath = Path.Combine(Config.LibraryConfiguration.LibraryMetadataDirectory_Company(company), "Logo_Medium.png"); if (System.IO.File.Exists(coverFilePath)) @@ -923,11 +920,11 @@ namespace gaseous_server.Controllers { try { - IGDB.Models.Game gameObject = Classes.Metadata.Games.GetGame(GameId, false, false, false); + gaseous_server.Models.Game game = Classes.Metadata.Games.GetGame(Communications.MetadataSource, GameId); - if (gameObject != null) + if (game != null) { - IGDB.Models.Platform platformObject = Classes.Metadata.Platforms.GetPlatform(PlatformId); + Platform platformObject = Classes.Metadata.Platforms.GetPlatform(PlatformId); if (platformObject != null) { @@ -965,11 +962,11 @@ namespace gaseous_server.Controllers { try { - IGDB.Models.Game gameObject = Classes.Metadata.Games.GetGame(GameId, false, false, false); + gaseous_server.Models.Game game = Classes.Metadata.Games.GetGame(Communications.MetadataSource, GameId); - if (gameObject != null) + if (game != null) { - IGDB.Models.Platform platformObject = Classes.Metadata.Platforms.GetPlatform(PlatformId); + Platform platformObject = Classes.Metadata.Platforms.GetPlatform(PlatformId); if (platformObject != null) { @@ -1004,11 +1001,11 @@ namespace gaseous_server.Controllers { try { - IGDB.Models.Game gameObject = Classes.Metadata.Games.GetGame(GameId, false, false, false); + gaseous_server.Models.Game game = Classes.Metadata.Games.GetGame(Communications.MetadataSource, GameId); - if (gameObject != null) + if (game != null) { - IGDB.Models.Platform platformObject = Classes.Metadata.Platforms.GetPlatform(PlatformId); + Platform platformObject = Classes.Metadata.Platforms.GetPlatform(PlatformId); if (platformObject != null) { @@ -1070,15 +1067,15 @@ namespace gaseous_server.Controllers { try { - IGDB.Models.Game gameObject = Classes.Metadata.Games.GetGame(GameId, false, false, false); - if (gameObject != null) + gaseous_server.Models.Game game = Classes.Metadata.Games.GetGame(Communications.MetadataSource, GameId); + if (game != null) { List rdObjects = new List(); - if (gameObject.ReleaseDates != null) + if (game.ReleaseDates != null) { - foreach (long icId in gameObject.ReleaseDates.Ids) + foreach (long icId in game.ReleaseDates) { - ReleaseDate releaseDate = Classes.Metadata.ReleaseDates.GetReleaseDates(icId); + ReleaseDate releaseDate = Classes.Metadata.ReleaseDates.GetReleaseDates(game.MetadataSource, icId); rdObjects.Add(releaseDate); } @@ -1110,7 +1107,7 @@ namespace gaseous_server.Controllers try { - Game gameObject = Classes.Metadata.Games.GetGame(GameId, false, false, false); + gaseous_server.Models.Game game = Classes.Metadata.Games.GetGame(Communications.MetadataSource, GameId); return Ok(Classes.Roms.GetRoms(GameId, PlatformId, NameSearch, pageNumber, pageSize, user.Id)); } @@ -1131,7 +1128,7 @@ namespace gaseous_server.Controllers { try { - Game gameObject = Classes.Metadata.Games.GetGame(GameId, false, false, false); + gaseous_server.Models.Game game = Classes.Metadata.Games.GetGame(Communications.MetadataSource, GameId); Classes.Roms.GameRomItem rom = Classes.Roms.GetRom(RomId); if (rom.GameId == GameId) @@ -1160,7 +1157,7 @@ namespace gaseous_server.Controllers { try { - Game gameObject = Classes.Metadata.Games.GetGame(GameId, false, false, false); + gaseous_server.Models.Game game = Classes.Metadata.Games.GetGame(Communications.MetadataSource, GameId); Classes.Roms.GameRomItem rom = Classes.Roms.GetRom(RomId); if (rom.GameId == GameId) @@ -1190,7 +1187,7 @@ namespace gaseous_server.Controllers { try { - Game gameObject = Classes.Metadata.Games.GetGame(GameId, false, false, false); + gaseous_server.Models.Game game = Classes.Metadata.Games.GetGame(Communications.MetadataSource, GameId); Classes.Roms.GameRomItem rom = Classes.Roms.GetRom(RomId); if (rom.GameId == GameId) @@ -1221,7 +1218,7 @@ namespace gaseous_server.Controllers { ApplicationUser? user = await _userManager.GetUserAsync(User); - Game gameObject = Classes.Metadata.Games.GetGame(GameId, false, false, false); + gaseous_server.Models.Game game = Classes.Metadata.Games.GetGame(Communications.MetadataSource, GameId); if (IsMediaGroup == false) { @@ -1283,7 +1280,7 @@ namespace gaseous_server.Controllers { try { - IGDB.Models.Game gameObject = Classes.Metadata.Games.GetGame(GameId, false, false, false); + gaseous_server.Models.Game game = Classes.Metadata.Games.GetGame(Communications.MetadataSource, GameId); Classes.Roms.GameRomItem rom = Classes.Roms.GetRom(RomId); if (rom.GameId != GameId) @@ -1322,7 +1319,7 @@ namespace gaseous_server.Controllers { try { - IGDB.Models.Game gameObject = Classes.Metadata.Games.GetGame(GameId, false, false, false); + gaseous_server.Models.Game game = Classes.Metadata.Games.GetGame(Communications.MetadataSource, GameId); Classes.Roms.GameRomItem rom = Classes.Roms.GetRom(RomId); if (rom.GameId != GameId || rom.Name != FileName) @@ -1361,7 +1358,7 @@ namespace gaseous_server.Controllers try { - Game gameObject = Classes.Metadata.Games.GetGame(GameId, false, false, false); + gaseous_server.Models.Game game = Classes.Metadata.Games.GetGame(Communications.MetadataSource, GameId); Classes.RomMediaGroup.GameRomMediaGroupItem rom = Classes.RomMediaGroup.GetMediaGroup(RomGroupId, user.Id); if (rom.GameId == GameId) @@ -1391,7 +1388,7 @@ namespace gaseous_server.Controllers try { - Game gameObject = Classes.Metadata.Games.GetGame(GameId, false, false, false); + gaseous_server.Models.Game game = Classes.Metadata.Games.GetGame(Communications.MetadataSource, GameId); try { @@ -1420,7 +1417,7 @@ namespace gaseous_server.Controllers { try { - Game gameObject = Classes.Metadata.Games.GetGame(GameId, false, false, false); + gaseous_server.Models.Game game = Classes.Metadata.Games.GetGame(Communications.MetadataSource, GameId); try { @@ -1451,7 +1448,7 @@ namespace gaseous_server.Controllers try { - Game gameObject = Classes.Metadata.Games.GetGame(GameId, false, false, false); + gaseous_server.Models.Game game = Classes.Metadata.Games.GetGame(Communications.MetadataSource, GameId); Classes.RomMediaGroup.GameRomMediaGroupItem rom = Classes.RomMediaGroup.GetMediaGroup(RomGroupId, user.Id); if (rom.GameId == GameId) @@ -1481,7 +1478,7 @@ namespace gaseous_server.Controllers { try { - Game gameObject = Classes.Metadata.Games.GetGame(GameId, false, false, false); + gaseous_server.Models.Game game = Classes.Metadata.Games.GetGame(Communications.MetadataSource, GameId); Classes.RomMediaGroup.GameRomMediaGroupItem rom = Classes.RomMediaGroup.GetMediaGroup(RomGroupId); if (rom.GameId == GameId) @@ -1514,7 +1511,7 @@ namespace gaseous_server.Controllers { try { - IGDB.Models.Game gameObject = Classes.Metadata.Games.GetGame(GameId, false, false, false); + gaseous_server.Models.Game game = Classes.Metadata.Games.GetGame(Communications.MetadataSource, GameId); Classes.RomMediaGroup.GameRomMediaGroupItem rom = Classes.RomMediaGroup.GetMediaGroup(RomGroupId); if (rom.GameId != GameId) @@ -1529,7 +1526,7 @@ namespace gaseous_server.Controllers string returnFileName = ""; if (filename == "") { - returnFileName = gameObject.Name + ".zip"; + returnFileName = game.Name + ".zip"; } else { @@ -1553,7 +1550,7 @@ namespace gaseous_server.Controllers [MapToApiVersion("1.1")] [HttpGet] [Route("search")] - [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] public async Task GameSearch(long RomId = 0, string SearchString = "") { @@ -1565,7 +1562,7 @@ namespace gaseous_server.Controllers Common.hashObject hash = new Common.hashObject(romItem.Path); FileSignature fileSignature = new FileSignature(); gaseous_server.Models.Signatures_Games romSig = fileSignature.GetFileSignature(romItem.Library, hash, new FileInfo(romItem.Path), romItem.Path); - List searchResults = Classes.ImportGame.SearchForGame_GetAll(romSig.Game.Name, romSig.Flags.IGDBPlatformId); + List searchResults = Classes.ImportGame.SearchForGame_GetAll(romSig.Game.Name, romSig.Flags.IGDBPlatformId); return Ok(searchResults); } @@ -1573,7 +1570,7 @@ namespace gaseous_server.Controllers { if (SearchString.Length > 0) { - List searchResults = Classes.ImportGame.SearchForGame_GetAll(SearchString, 0); + List searchResults = Classes.ImportGame.SearchForGame_GetAll(SearchString, 0); return Ok(searchResults); } @@ -1600,14 +1597,14 @@ namespace gaseous_server.Controllers { try { - Game gameObject = Classes.Metadata.Games.GetGame(GameId, false, false, false); + gaseous_server.Models.Game game = Classes.Metadata.Games.GetGame(Communications.MetadataSource, GameId); List screenshots = new List(); - if (gameObject.Screenshots != null) + if (game.Screenshots != null) { - foreach (long ScreenshotId in gameObject.Screenshots.Ids) + foreach (long ScreenshotId in game.Screenshots) { - Screenshot GameScreenshot = Screenshots.GetScreenshot(ScreenshotId, Config.LibraryConfiguration.LibraryMetadataDirectory_Game(gameObject), false); + Screenshot GameScreenshot = Screenshots.GetScreenshot(game.MetadataSource, ScreenshotId); screenshots.Add(GameScreenshot); } } @@ -1631,10 +1628,10 @@ namespace gaseous_server.Controllers { try { - IGDB.Models.Game gameObject = Classes.Metadata.Games.GetGame(GameId, false, false, false); - if (gameObject != null) + gaseous_server.Models.Game game = Classes.Metadata.Games.GetGame(Communications.MetadataSource, GameId); + if (game != null) { - IGDB.Models.Screenshot screenshotObject = Screenshots.GetScreenshot(ScreenshotId, Config.LibraryConfiguration.LibraryMetadataDirectory_Game(gameObject), false); + Screenshot screenshotObject = Screenshots.GetScreenshot(game.MetadataSource, ScreenshotId); if (screenshotObject != null) { return Ok(screenshotObject); @@ -1655,57 +1652,6 @@ namespace gaseous_server.Controllers } } - // [MapToApiVersion("1.0")] - // [MapToApiVersion("1.1")] - // [HttpGet] - // [Route("{GameId}/screenshots/{ScreenshotId}/image/{size}")] - // [Route("{GameId}/screenshots/{ScreenshotId}/image/{size}/{ImageName}")] - // [ProducesResponseType(typeof(FileStreamResult), StatusCodes.Status200OK)] - // [ProducesResponseType(StatusCodes.Status404NotFound)] - // public async Task GameScreenshotImage(long GameId, long ScreenshotId, Communications.IGDBAPI_ImageSize Size, string ImageName) - // { - // try - // { - // IGDB.Models.Game gameObject = Classes.Metadata.Games.GetGame(GameId, false, false, false); - - // IGDB.Models.Screenshot screenshotObject = Screenshots.GetScreenshot(ScreenshotId, Config.LibraryConfiguration.LibraryMetadataDirectory_Game(gameObject), true); - - // string basePath = Path.Combine(Config.LibraryConfiguration.LibraryMetadataDirectory_Game(gameObject), "Screenshots"); - - // Communications comms = new Communications(); - // Task ImgFetch = comms.GetSpecificImageFromServer(basePath, screenshotObject.ImageId, Size, new List { Communications.IGDBAPI_ImageSize.original }); - - // string coverFilePath = ImgFetch.Result; - - // if (System.IO.File.Exists(coverFilePath)) - // { - // string filename = screenshotObject.ImageId + ".jpg"; - // string filepath = coverFilePath; - // byte[] filedata = System.IO.File.ReadAllBytes(filepath); - // string contentType = "image/jpg"; - - // var cd = new System.Net.Mime.ContentDisposition - // { - // FileName = filename, - // Inline = true, - // }; - - // Response.Headers.Add("Content-Disposition", cd.ToString()); - // Response.Headers.Add("Cache-Control", "public, max-age=604800"); - - // return File(filedata, contentType); - // } - // else - // { - // return NotFound(); - // } - // } - // catch - // { - // return NotFound(); - // } - // } - [MapToApiVersion("1.0")] [MapToApiVersion("1.1")] [HttpGet] @@ -1717,14 +1663,14 @@ namespace gaseous_server.Controllers { try { - Game gameObject = Classes.Metadata.Games.GetGame(GameId, false, false, false); + gaseous_server.Models.Game game = Classes.Metadata.Games.GetGame(Communications.MetadataSource, GameId); List videos = new List(); - if (gameObject.Videos != null) + if (game.Videos != null) { - foreach (long VideoId in gameObject.Videos.Ids) + foreach (long VideoId in game.Videos) { - GameVideo gameVideo = GamesVideos.GetGame_Videos(VideoId); + GameVideo gameVideo = GamesVideos.GetGame_Videos(game.MetadataSource, VideoId); videos.Add(gameVideo); } } diff --git a/gaseous-server/Controllers/V1.0/PlatformsController.cs b/gaseous-server/Controllers/V1.0/PlatformsController.cs index 6ddda49..ffacb69 100644 --- a/gaseous-server/Controllers/V1.0/PlatformsController.cs +++ b/gaseous-server/Controllers/V1.0/PlatformsController.cs @@ -8,12 +8,12 @@ using System.Threading.Tasks; using gaseous_server.Classes; using gaseous_server.Classes.Metadata; using gaseous_server.Models; -using IGDB.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.CodeAnalysis.Scripting; using Asp.Versioning; +using HasheousClient.Models.Metadata.IGDB; namespace gaseous_server.Controllers { @@ -60,7 +60,7 @@ namespace gaseous_server.Controllers { try { - IGDB.Models.Platform platformObject = Classes.Metadata.Platforms.GetPlatform(PlatformId); + Platform platformObject = Classes.Metadata.Platforms.GetPlatform(PlatformId); if (platformObject != null) { @@ -87,10 +87,11 @@ namespace gaseous_server.Controllers { try { - IGDB.Models.Platform platformObject = Classes.Metadata.Platforms.GetPlatform(PlatformId); + Platform platformObject = Classes.Metadata.Platforms.GetPlatform(PlatformId); if (platformObject != null) { - IGDB.Models.PlatformLogo logoObject = PlatformLogos.GetPlatformLogo(platformObject.PlatformLogo.Id, Config.LibraryConfiguration.LibraryMetadataDirectory_Platform(platformObject)); + PlatformLogo logoObjectParent = (PlatformLogo)platformObject.PlatformLogo; + PlatformLogo logoObject = PlatformLogos.GetPlatformLogo(logoObjectParent.Id); if (logoObject != null) { return Ok(logoObject); @@ -121,21 +122,22 @@ namespace gaseous_server.Controllers { try { - IGDB.Models.Platform platformObject = Classes.Metadata.Platforms.GetPlatform(PlatformId); - IGDB.Models.PlatformLogo? logoObject = null; + Platform platformObject = Classes.Metadata.Platforms.GetPlatform(PlatformId); + PlatformLogo? logoObject = null; try { - logoObject = PlatformLogos.GetPlatformLogo(platformObject.PlatformLogo.Id, Config.LibraryConfiguration.LibraryMetadataDirectory_Platform(platformObject)); + + logoObject = PlatformLogos.GetPlatformLogo((long)platformObject.PlatformLogo); } catch { // getting the logo failed, so we'll try a platform variant if available if (platformObject.Versions != null) { - if (platformObject.Versions.Ids.Length > 0) + if (platformObject.Versions.Count > 0) { - IGDB.Models.PlatformVersion platformVersion = Classes.Metadata.PlatformVersions.GetPlatformVersion(platformObject.Versions.Ids[0], platformObject); - logoObject = PlatformLogos.GetPlatformLogo(platformVersion.PlatformLogo.Id, Config.LibraryConfiguration.LibraryMetadataDirectory_Platform(platformObject)); + PlatformVersion platformVersion = Classes.Metadata.PlatformVersions.GetPlatformVersion(Communications.MetadataSource, (long)platformObject.Versions[0]); + logoObject = PlatformLogos.GetPlatformLogo((long)platformVersion.PlatformLogo); } else { diff --git a/gaseous-server/Controllers/V1.0/RomsController.cs b/gaseous-server/Controllers/V1.0/RomsController.cs index 7b5d9be..d7da89b 100644 --- a/gaseous-server/Controllers/V1.0/RomsController.cs +++ b/gaseous-server/Controllers/V1.0/RomsController.cs @@ -8,13 +8,13 @@ using System.Reflection; using System.Threading.Tasks; using gaseous_server.Classes; using gaseous_server.Classes.Metadata; -using IGDB.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.CodeAnalysis.Scripting; using static gaseous_server.Classes.Metadata.AgeRatings; using Asp.Versioning; +using HasheousClient.Models.Metadata.IGDB; namespace gaseous_server.Controllers { @@ -62,7 +62,7 @@ namespace gaseous_server.Controllers } // get override platform if specified - IGDB.Models.Platform? OverridePlatform = null; + Platform? OverridePlatform = null; if (OverridePlatformId != null) { OverridePlatform = Platforms.GetPlatform((long)OverridePlatformId); @@ -76,10 +76,10 @@ namespace gaseous_server.Controllers case "rom": if (RetVal["status"] == "imported") { - IGDB.Models.Game? game = (IGDB.Models.Game)RetVal["game"]; + gaseous_server.Models.Game? game = (gaseous_server.Models.Game)RetVal["game"]; if (game.Id == null) { - RetVal["game"] = Games.GetGame(0, false, false, false); + RetVal["game"] = Games.GetGame(Communications.MetadataSource, 0); } } break; diff --git a/gaseous-server/Controllers/V1.0/SearchController.cs b/gaseous-server/Controllers/V1.0/SearchController.cs index e08f529..4650591 100644 --- a/gaseous-server/Controllers/V1.0/SearchController.cs +++ b/gaseous-server/Controllers/V1.0/SearchController.cs @@ -6,8 +6,7 @@ using System.Threading.Tasks; using gaseous_server.Classes; using gaseous_server.Classes.Metadata; using gaseous_server.Models; -using IGDB; -using IGDB.Models; +using HasheousClient.Models.Metadata.IGDB; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using NuGet.Common; @@ -44,7 +43,7 @@ namespace gaseous_server.Controllers List platforms = new List(); foreach (DataRow row in data.Rows) { - Platform platform = Platforms.GetPlatform((long)row["Id"], false, false); + Platform platform = Platforms.GetPlatform((long)row["Id"]); platforms.Add(platform); } @@ -56,14 +55,14 @@ namespace gaseous_server.Controllers [MapToApiVersion("1.1")] [HttpGet] [Route("Game")] - [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] public async Task SearchGame(long PlatformId, string SearchString) { - List RetVal = await _SearchForGame(PlatformId, SearchString); + List RetVal = await _SearchForGame(PlatformId, SearchString); return Ok(RetVal); } - private static async Task> _SearchForGame(long PlatformId, string SearchString) + private static async Task> _SearchForGame(long PlatformId, string SearchString) { switch (Communications.MetadataSource) { @@ -74,35 +73,35 @@ namespace gaseous_server.Controllers searchBody += "where platforms = (" + PlatformId + ");"; searchBody += "limit 100;"; - List? searchCache = Communications.GetSearchCache>(searchFields, searchBody); + List? searchCache = Communications.GetSearchCache>(searchFields, searchBody); if (searchCache == null) { // cache miss // get Game metadata from data source Communications comms = new Communications(); - var results = await comms.APIComm(IGDBClient.Endpoints.Games, searchFields, searchBody); + var results = await comms.APIComm("Game", searchFields, searchBody); - List games = new List(); - foreach (Game game in results.ToList()) + List games = new List(); + foreach (gaseous_server.Models.Game game in results.ToList()) { - Storage.CacheStatus cacheStatus = Storage.GetCacheStatus("Game", (long)game.Id); + Storage.CacheStatus cacheStatus = Storage.GetCacheStatus(Communications.MetadataSource, "Game", (long)game.Id); switch (cacheStatus) { case Storage.CacheStatus.NotPresent: - Storage.NewCacheValue(game, false); + Storage.NewCacheValue(Communications.MetadataSource, game, false); break; case Storage.CacheStatus.Expired: - Storage.NewCacheValue(game, true); + Storage.NewCacheValue(Communications.MetadataSource, game, true); break; } - games.Add(new GaseousGame(game)); + games.Add(game); } - Communications.SetSearchCache>(searchFields, searchBody, games); + Communications.SetSearchCache>(searchFields, searchBody, games); return games; } @@ -110,11 +109,14 @@ namespace gaseous_server.Controllers { // get full version of results from database // this is a hacky workaround due to the readonly nature of IGDB.Model.Game IdentityOrValue fields - List gamesToReturn = new List(); - foreach (GaseousGame game in searchCache) + List gamesToReturn = new List(); + foreach (gaseous_server.Models.Game game in searchCache) { - Game tempGame = Games.GetGame((long)game.Id, false, false, false); - gamesToReturn.Add(new GaseousGame(tempGame)); + gaseous_server.Models.Game? tempGame = Games.GetGame(Communications.MetadataSource, (long)game.Id); + if (tempGame != null) + { + gamesToReturn.Add(tempGame); + } } return gamesToReturn; @@ -123,19 +125,18 @@ namespace gaseous_server.Controllers case HasheousClient.Models.MetadataModel.MetadataSources.Hasheous: HasheousClient.Hasheous hasheous = new HasheousClient.Hasheous(); Communications.ConfigureHasheousClient(ref hasheous); - List hSearch = hasheous.GetMetadataProxy_SearchGame(HasheousClient.Hasheous.MetadataProvider.IGDB, PlatformId.ToString(), SearchString).ToList(); + List hSearch = hasheous.GetMetadataProxy_SearchGame(HasheousClient.Hasheous.MetadataProvider.IGDB, PlatformId.ToString(), SearchString).ToList(); - List hGamesToReturn = new List(); - foreach (HasheousClient.Models.Metadata.IGDB.Game game in hSearch) + List hGamesToReturn = new List(); + foreach (gaseous_server.Models.Game game in hSearch) { - IGDB.Models.Game tempGame = Communications.ConvertToIGDBModel(game); - hGamesToReturn.Add(new GaseousGame(tempGame)); + hGamesToReturn.Add(game); } return hGamesToReturn; default: - return new List(); + return new List(); } } } diff --git a/gaseous-server/Controllers/V1.1/GamesController.cs b/gaseous-server/Controllers/V1.1/GamesController.cs index 16f726b..9f7edf5 100644 --- a/gaseous-server/Controllers/V1.1/GamesController.cs +++ b/gaseous-server/Controllers/V1.1/GamesController.cs @@ -9,7 +9,6 @@ using System.Threading.Tasks; using Authentication; using gaseous_server.Classes; using gaseous_server.Classes.Metadata; -using IGDB.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; @@ -19,6 +18,7 @@ using Microsoft.CodeAnalysis.Scripting; using static gaseous_server.Classes.Metadata.AgeRatings; using Asp.Versioning; using Humanizer; +using HasheousClient.Models.Metadata.IGDB; namespace gaseous_server.Controllers.v1_1 { @@ -117,13 +117,13 @@ namespace gaseous_server.Controllers.v1_1 dbDict.Add("id", GameId); dbDict.Add("agegroupid", (int)user.SecurityProfile.AgeRestrictionPolicy.MaximumAgeRestriction); - List RetVal = new List(); + List RetVal = new List(); DataTable dbResponse = db.ExecuteCMD(sql, dbDict); foreach (DataRow dr in dbResponse.Rows) { - RetVal.Add(Classes.Metadata.Games.GetGame((long)dr["SimilarGamesId"], false, false, false)); + RetVal.Add(Classes.Metadata.Games.GetGame(Communications.MetadataSource, (long)dr["SimilarGamesId"])); } GameReturnPackage gameReturn = new GameReturnPackage(RetVal.Count, RetVal); @@ -571,7 +571,7 @@ FROM } } - Game retGame = Storage.BuildCacheObject(new Game(), dbResponse.Rows[i]); + Models.Game retGame = Storage.BuildCacheObject(new Models.Game(), dbResponse.Rows[i]); Games.MinimalGameItem retMinGame = new Games.MinimalGameItem(retGame); retMinGame.Index = i; if (dbResponse.Rows[i]["RomSaveCount"] != DBNull.Value || dbResponse.Rows[i]["MediaGroupSaveCount"] != DBNull.Value) @@ -654,12 +654,12 @@ FROM } - public GameReturnPackage(int Count, List Games) + public GameReturnPackage(int Count, List Games) { this.Count = Count; List minimalGames = new List(); - foreach (Game game in Games) + foreach (Models.Game game in Games) { minimalGames.Add(new Classes.Metadata.Games.MinimalGameItem(game)); } diff --git a/gaseous-server/Controllers/V1.1/StateManagerController.cs b/gaseous-server/Controllers/V1.1/StateManagerController.cs index 85e51e3..6dfcc1a 100644 --- a/gaseous-server/Controllers/V1.1/StateManagerController.cs +++ b/gaseous-server/Controllers/V1.1/StateManagerController.cs @@ -270,7 +270,7 @@ namespace gaseous_server.Controllers.v1_1 else { RomMediaGroup.GameRomMediaGroupItem mediaGroupItem = RomMediaGroup.GetMediaGroup(RomId); - IGDB.Models.Game game = Games.GetGame(mediaGroupItem.GameId, false, false, false); + Models.Game game = Games.GetGame(Communications.MetadataSource, mediaGroupItem.GameId); Classes.Common.hashObject hashObject = new Classes.Common.hashObject(Path.Combine(Config.LibraryConfiguration.LibraryMediaGroupDirectory, mediaGroupItem.Id.ToString() + ".zip")); romName = game.Name; romMd5 = hashObject.md5hash; diff --git a/gaseous-server/Models/GaseousGame.cs b/gaseous-server/Models/GaseousGame.cs index 284430b..0a4ff99 100644 --- a/gaseous-server/Models/GaseousGame.cs +++ b/gaseous-server/Models/GaseousGame.cs @@ -5,50 +5,19 @@ using Swashbuckle.AspNetCore.SwaggerGen; namespace gaseous_server.Models { - public class GaseousGame : IGDB.Models.Game + public class Game : HasheousClient.Models.Metadata.IGDB.Game { - public GaseousGame() - { - - } - - public GaseousGame(IGDB.Models.Game game) - { - var targetType = this.GetType(); - var sourceType = game.GetType(); - foreach (var prop in targetType.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty)) - { - // check whether source object has the the property - var sp = sourceType.GetProperty(prop.Name); - if (sp != null) - { - // if yes, copy the value to the matching property - var value = sp.GetValue(game, null); - prop.SetValue(this, value, null); - } - } - } + [NoDatabase] + public bool IsFavourite { get; set; } = false; + [NoDatabase] public bool HasSavedGame { get; set; } = false; - public IGDB.Models.Cover? CoverItem - { - get - { - if (this.Cover != null) - { - if (this.Cover.Id != null) - { - // IGDB.Models.Cover cover = Covers.GetCover(Cover.Id, Config.LibraryConfiguration.LibraryMetadataDirectory_Game(this), false); - IGDB.Models.Cover cover = new IGDB.Models.Cover() - { - Id = this.Cover.Id - }; - } - } + [NoDatabase] + public HasheousClient.Models.MetadataModel.MetadataSources MetadataSource { get; set; } + } - return null; - } - } + internal class NoDatabaseAttribute : Attribute + { } } \ No newline at end of file diff --git a/gaseous-server/Models/PlatformMapping.cs b/gaseous-server/Models/PlatformMapping.cs index ef80916..9ba579a 100644 --- a/gaseous-server/Models/PlatformMapping.cs +++ b/gaseous-server/Models/PlatformMapping.cs @@ -8,7 +8,7 @@ using System.Web; using gaseous_server.Classes; using gaseous_server.Classes.Metadata; using gaseous_server.Controllers; -using IGDB.Models; +using HasheousClient.Models.Metadata.IGDB; using Newtonsoft.Json; namespace gaseous_server.Models @@ -92,9 +92,9 @@ namespace gaseous_server.Models } } - private static IGDB.Models.Platform CreateDummyPlatform(PlatformMapItem mapItem) + private static Platform CreateDummyPlatform(PlatformMapItem mapItem) { - IGDB.Models.Platform platform = new IGDB.Models.Platform + Platform platform = new Platform { Id = mapItem.IGDBId, Name = mapItem.IGDBName, @@ -102,9 +102,9 @@ namespace gaseous_server.Models AlternativeName = mapItem.AlternateNames.FirstOrDefault() }; - if (Storage.GetCacheStatus("Platform", mapItem.IGDBId) == Storage.CacheStatus.NotPresent) + if (Storage.GetCacheStatus(Communications.MetadataSource, "Platform", mapItem.IGDBId) == Storage.CacheStatus.NotPresent) { - Storage.NewCacheValue(platform); + Storage.NewCacheValue(Communications.MetadataSource, platform); } return platform; @@ -310,15 +310,14 @@ namespace gaseous_server.Models string sql = ""; // get platform data - // IGDB.Models.Platform? platform = Platforms.GetPlatform(IGDBId, false); - IGDB.Models.Platform? platform = null; - if (Storage.GetCacheStatus("Platform", IGDBId) == Storage.CacheStatus.NotPresent) + Platform? platform = null; + if (Storage.GetCacheStatus(Communications.MetadataSource, "Platform", IGDBId) == Storage.CacheStatus.NotPresent) { //platform = Platforms.GetPlatform(IGDBId, false); } else { - platform = (IGDB.Models.Platform)Storage.GetCacheValue(new Platform(), "id", IGDBId); + platform = (Platform)Storage.GetCacheValue(Communications.MetadataSource, new Platform(), "id", IGDBId); } if (platform != null) diff --git a/gaseous-server/Models/UserProfile.cs b/gaseous-server/Models/UserProfile.cs index 625a896..bc14c8f 100644 --- a/gaseous-server/Models/UserProfile.cs +++ b/gaseous-server/Models/UserProfile.cs @@ -1,5 +1,3 @@ -using IGDB.Models; - namespace gaseous_server.Models { public class UserProfile @@ -11,7 +9,7 @@ namespace gaseous_server.Models public class NowPlayingItem { public Game Game { get; set; } - public Platform Platform { get; set; } + public HasheousClient.Models.Metadata.IGDB.Platform Platform { get; set; } public long Duration { get; set; } } public ProfileImageItem? Avatar { get; set; } diff --git a/gaseous-server/Program.cs b/gaseous-server/Program.cs index 3bb21fa..168d48b 100644 --- a/gaseous-server/Program.cs +++ b/gaseous-server/Program.cs @@ -329,12 +329,6 @@ app.Use(async (context, next) => // setup library directories Config.LibraryConfiguration.InitLibrary(); -// insert unknown platform and game if not present -gaseous_server.Classes.Metadata.Games.GetGame(0, false, false, false); -gaseous_server.Classes.Metadata.Games.AssignAllGamesToPlatformIdZero(); -gaseous_server.Classes.Metadata.Platforms.GetPlatform(0); -gaseous_server.Classes.Metadata.Platforms.AssignAllPlatformsToGameIdZero(); - // extract platform map if not present PlatformMapping.ExtractPlatformMap(); diff --git a/gaseous-server/Support/Database/MySQL/gaseous-1024.sql b/gaseous-server/Support/Database/MySQL/gaseous-1024.sql index ac0a24a..eafa23d 100644 --- a/gaseous-server/Support/Database/MySQL/gaseous-1024.sql +++ b/gaseous-server/Support/Database/MySQL/gaseous-1024.sql @@ -99,9 +99,157 @@ SELECT *, DATE_ADD( FROM UserTimeTracking; CREATE INDEX idx_game_name ON Game (`Name`); + CREATE INDEX idx_game_totalratingcount ON Game (TotalRatingCount); + CREATE INDEX idx_alternativename_game ON AlternativeName (Game); + CREATE INDEX idx_gamestate_romid ON GameState (RomId); + CREATE INDEX idx_gamestate_ismediagroup_userid ON GameState (IsMediaGroup, UserId); + CREATE INDEX idx_rommediagroup_gameid ON RomMediaGroup (GameId); -CREATE INDEX idx_favourites_userid_gameid ON Favourites (UserId, GameId); \ No newline at end of file + +CREATE INDEX idx_favourites_userid_gameid ON Favourites (UserId, GameId); + +CREATE TABLE `MetadataMap` ( + `Id` bigint(20) NOT NULL AUTO_INCREMENT, + `PlatformId` bigint(20) NOT NULL, + PRIMARY KEY (`id`) +); + +CREATE TABLE `MetadataMapBridge` ( + `ParentMapId` bigint(20) NOT NULL, + `MetadataSourceType` int(11) NOT NULL DEFAULT 0, + `MetadataSourceId` bigint(20) NOT NULL `Preferred` BOOLEAN NOT NULL DEFAULT 0, + PRIMARY KEY ( + `ParentMapId`, + `MetadataSourceType`, + `MetadataSourceId` + ) +); + +ALTER TABLE `Games_Roms` +ADD COLUMN `MetadataMapId` BIGINT NOT NULL DEFAULT 0; + +ALTER TABLE `AgeGroup` +ADD COLUMN `SourceId` INT NOT NULL DEFAULT 1 AFTER `Id`, +DROP PRIMARY KEY, +ADD PRIMARY KEY (`Id`, `SourceId`); + +ALTER TABLE `AgeRating` +ADD COLUMN `SourceId` INT NOT NULL DEFAULT 1 AFTER `Id`, +DROP PRIMARY KEY, +ADD PRIMARY KEY (`Id`, `SourceId`); + +ALTER TABLE `AgeRatingContentDescription` +ADD COLUMN `SourceId` INT NOT NULL DEFAULT 1 AFTER `Id`, +DROP PRIMARY KEY, +ADD PRIMARY KEY (`Id`, `SourceId`); + +ALTER TABLE `AlternativeName` +ADD COLUMN `SourceId` INT NOT NULL DEFAULT 1 AFTER `Id`, +DROP PRIMARY KEY, +ADD PRIMARY KEY (`Id`, `SourceId`); + +ALTER TABLE `Artwork` +ADD COLUMN `SourceId` INT NOT NULL DEFAULT 1 AFTER `Id`, +DROP PRIMARY KEY, +ADD PRIMARY KEY (`Id`, `SourceId`); + +ALTER TABLE `Collection` +ADD COLUMN `SourceId` INT NOT NULL DEFAULT 1 AFTER `Id`, +DROP PRIMARY KEY, +ADD PRIMARY KEY (`Id`, `SourceId`); + +ALTER TABLE `Company` +ADD COLUMN `SourceId` INT NOT NULL DEFAULT 1 AFTER `Id`, +DROP PRIMARY KEY, +ADD PRIMARY KEY (`Id`, `SourceId`); + +ALTER TABLE `CompanyLogo` +ADD COLUMN `SourceId` INT NOT NULL DEFAULT 1 AFTER `Id`, +DROP PRIMARY KEY, +ADD PRIMARY KEY (`Id`, `SourceId`); + +ALTER TABLE `Cover` +ADD COLUMN `SourceId` INT NOT NULL DEFAULT 1 AFTER `Id`, +DROP PRIMARY KEY, +ADD PRIMARY KEY (`Id`, `SourceId`); + +ALTER TABLE `ExternalGame` +ADD COLUMN `SourceId` INT NOT NULL DEFAULT 1 AFTER `Id`, +DROP PRIMARY KEY, +ADD PRIMARY KEY (`Id`, `SourceId`); + +ALTER TABLE `Franchise` +ADD COLUMN `SourceId` INT NOT NULL DEFAULT 1 AFTER `Id`, +DROP PRIMARY KEY, +ADD PRIMARY KEY (`Id`, `SourceId`); + +ALTER TABLE `Game` +ADD COLUMN `SourceId` INT NOT NULL DEFAULT 1 AFTER `Id`, +DROP INDEX IF EXISTS `Id_UNIQUE`, +DROP INDEX IF EXISTS `PRIMARY`, +ADD PRIMARY KEY (`Id`, `SourceId`); + +ALTER TABLE `GameMode` +ADD COLUMN `SourceId` INT NOT NULL DEFAULT 1 AFTER `Id`, +DROP PRIMARY KEY, +ADD PRIMARY KEY (`Id`, `SourceId`); + +ALTER TABLE `GameVideo` +ADD COLUMN `SourceId` INT NOT NULL DEFAULT 1 AFTER `Id`, +DROP PRIMARY KEY, +ADD PRIMARY KEY (`Id`, `SourceId`); + +ALTER TABLE `Genre` +ADD COLUMN `SourceId` INT NOT NULL DEFAULT 1 AFTER `Id`, +DROP PRIMARY KEY, +ADD PRIMARY KEY (`Id`, `SourceId`); + +ALTER TABLE `InvolvedCompany` +ADD COLUMN `SourceId` INT NOT NULL DEFAULT 1 AFTER `Id`, +DROP PRIMARY KEY, +ADD PRIMARY KEY (`Id`, `SourceId`); + +ALTER TABLE `MultiplayerMode` +ADD COLUMN `SourceId` INT NOT NULL DEFAULT 1 AFTER `Id`, +DROP PRIMARY KEY, +ADD PRIMARY KEY (`Id`, `SourceId`); + +ALTER TABLE `Platform` +ADD COLUMN `SourceId` INT NOT NULL DEFAULT 1 AFTER `Id`, +DROP INDEX IF EXISTS `Id_UNIQUE`, +DROP INDEX IF EXISTS `PRIMARY`, +ADD PRIMARY KEY (`Id`, `SourceId`); + +ALTER TABLE `PlatformLogo` +ADD COLUMN `SourceId` INT NOT NULL DEFAULT 1 AFTER `Id`, +DROP PRIMARY KEY, +ADD PRIMARY KEY (`Id`, `SourceId`); + +ALTER TABLE `PlatformVersion` +ADD COLUMN `SourceId` INT NOT NULL DEFAULT 1 AFTER `Id`, +DROP PRIMARY KEY, +ADD PRIMARY KEY (`Id`, `SourceId`); + +ALTER TABLE `PlayerPerspective` +ADD COLUMN `SourceId` INT NOT NULL DEFAULT 1 AFTER `Id`, +DROP PRIMARY KEY, +ADD PRIMARY KEY (`Id`, `SourceId`); + +ALTER TABLE `ReleaseDate` +ADD COLUMN `SourceId` INT NOT NULL DEFAULT 1 AFTER `Id`, +DROP PRIMARY KEY, +ADD PRIMARY KEY (`Id`, `SourceId`); + +ALTER TABLE `Screenshot` +ADD COLUMN `SourceId` INT NOT NULL DEFAULT 1 AFTER `Id`, +DROP PRIMARY KEY, +ADD PRIMARY KEY (`Id`, `SourceId`); + +ALTER TABLE `Theme` +ADD COLUMN `SourceId` INT NOT NULL DEFAULT 1 AFTER `Id`, +DROP PRIMARY KEY, +ADD PRIMARY KEY (`Id`, `SourceId`); \ No newline at end of file