This commit is contained in:
Michael Green
2024-11-17 22:04:26 +11:00
parent b1fcfec14f
commit 74171b50af
50 changed files with 1010 additions and 2390 deletions

View File

@@ -1,6 +1,7 @@
using System; using System;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Security.Cryptography; using System.Security.Cryptography;
using HasheousClient.Models.Metadata.IGDB;
namespace gaseous_server.Classes namespace gaseous_server.Classes
{ {
@@ -94,7 +95,7 @@ namespace gaseous_server.Classes
{ {
if (platformMapping.Bios != null) 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) foreach (Models.PlatformMapping.PlatformMapItem.EmulatorBiosItem emulatorBios in platformMapping.Bios)
{ {

View File

@@ -9,7 +9,7 @@ using gaseous_server.Classes.Metadata;
using gaseous_server.Controllers; using gaseous_server.Controllers;
using gaseous_server.Controllers.v1_1; using gaseous_server.Controllers.v1_1;
using gaseous_server.Models; using gaseous_server.Models;
using IGDB.Models; using HasheousClient.Models.Metadata.IGDB;
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json; using Newtonsoft.Json;
@@ -18,9 +18,10 @@ using static gaseous_server.Classes.Metadata.Games;
namespace gaseous_server.Classes namespace gaseous_server.Classes
{ {
public class Collections public class Collections
{ {
public static List<CollectionItem> GetCollections(string userid) { public static List<CollectionItem> GetCollections(string userid)
{
Database db = new Database(Database.databaseType.MySql, Config.DatabaseConfiguration.ConnectionString); Database db = new Database(Database.databaseType.MySql, Config.DatabaseConfiguration.ConnectionString);
string sql = "SELECT * FROM RomCollections WHERE OwnedBy=@ownedby ORDER BY `Name`"; string sql = "SELECT * FROM RomCollections WHERE OwnedBy=@ownedby ORDER BY `Name`";
Dictionary<string, object> dbDict = new Dictionary<string, object>{ Dictionary<string, object> dbDict = new Dictionary<string, object>{
@@ -30,16 +31,18 @@ namespace gaseous_server.Classes
List<CollectionItem> collectionItems = new List<CollectionItem>(); List<CollectionItem> collectionItems = new List<CollectionItem>();
foreach(DataRow row in data.Rows) { foreach (DataRow row in data.Rows)
{
collectionItems.Add(BuildCollectionItem(row)); collectionItems.Add(BuildCollectionItem(row));
} }
return collectionItems; 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); Database db = new Database(Database.databaseType.MySql, Config.DatabaseConfiguration.ConnectionString);
string sql; string sql;
if (userid == "") if (userid == "")
{ {
// reserved for internal operations // reserved for internal operations
@@ -50,24 +53,24 @@ namespace gaseous_server.Classes
// instigated by a user // instigated by a user
sql = "SELECT * FROM RomCollections WHERE Id = @id AND OwnedBy = @ownedby ORDER BY `Name`"; sql = "SELECT * FROM RomCollections WHERE Id = @id AND OwnedBy = @ownedby ORDER BY `Name`";
} }
Dictionary<string, object> dbDict = new Dictionary<string, object> Dictionary<string, object> dbDict = new Dictionary<string, object>
{ {
{ "id", Id }, { "id", Id },
{ "ownedby", userid } { "ownedby", userid }
}; };
DataTable romDT = db.ExecuteCMD(sql, dbDict); DataTable romDT = db.ExecuteCMD(sql, dbDict);
if (romDT.Rows.Count > 0) if (romDT.Rows.Count > 0)
{ {
DataRow row = romDT.Rows[0]; DataRow row = romDT.Rows[0];
CollectionItem collectionItem = BuildCollectionItem(row); CollectionItem collectionItem = BuildCollectionItem(row);
return collectionItem; return collectionItem;
} }
else else
{ {
throw new Exception("Unknown Collection Id"); throw new Exception("Unknown Collection Id");
} }
} }
public static CollectionItem NewCollection(CollectionItem item, string userid) public static CollectionItem NewCollection(CollectionItem item, string userid)
@@ -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); Database db = new Database(Database.databaseType.MySql, Config.DatabaseConfiguration.ConnectionString);
// get age ratings for specified user // get age ratings for specified user
@@ -251,24 +255,29 @@ namespace gaseous_server.Classes
alwaysIncludeItem.InclusionState == CollectionItem.AlwaysIncludeStatus.AlwaysInclude || alwaysIncludeItem.InclusionState == CollectionItem.AlwaysIncludeStatus.AlwaysInclude ||
alwaysIncludeItem.InclusionState == CollectionItem.AlwaysIncludeStatus.AlwaysExclude 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 // add dynamic platforms
if (DynamicPlatforms.Count > 0) { if (DynamicPlatforms.Count > 0)
foreach (long PlatformId in platformids) { {
foreach (long PlatformId in platformids)
{
platforms.Add(Platforms.GetPlatform(PlatformId)); platforms.Add(Platforms.GetPlatform(PlatformId));
} }
} else { }
else
{
// get all platforms to pull from // get all platforms to pull from
Dictionary<string, List<Filters.FilterItem>> FilterDict = Filters.Filter(AgeGroups.AgeRestrictionGroupings.Adult, true); Dictionary<string, List<Filters.FilterItem>> FilterDict = Filters.Filter(AgeGroups.AgeRestrictionGroupings.Adult, true);
List<Classes.Filters.FilterItem> filteredPlatforms = (List<Classes.Filters.FilterItem>)FilterDict["platforms"]; List<Classes.Filters.FilterItem> filteredPlatforms = (List<Classes.Filters.FilterItem>)FilterDict["platforms"];
foreach (Filters.FilterItem filterItem in filteredPlatforms) { foreach (Filters.FilterItem filterItem in filteredPlatforms)
{
platforms.Add(Platforms.GetPlatform(filterItem.Id)); platforms.Add(Platforms.GetPlatform(filterItem.Id));
} }
} }
@@ -280,7 +289,8 @@ namespace gaseous_server.Classes
// build collection // build collection
List<CollectionContents.CollectionPlatformItem> platformItems = new List<CollectionContents.CollectionPlatformItem>(); List<CollectionContents.CollectionPlatformItem> platformItems = new List<CollectionContents.CollectionPlatformItem>();
foreach (Platform platform in platforms) { foreach (Platform platform in platforms)
{
long TotalRomSize = 0; long TotalRomSize = 0;
long TotalGameCount = 0; long TotalGameCount = 0;
@@ -297,7 +307,8 @@ namespace gaseous_server.Classes
Controllers.v1_1.GamesController.GameReturnPackage games = new Controllers.v1_1.GamesController.GameReturnPackage(); Controllers.v1_1.GamesController.GameReturnPackage games = new Controllers.v1_1.GamesController.GameReturnPackage();
if (isDynamic == true) 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 = "", Name = "",
Platform = new List<string>{ Platform = new List<string>{
platform.Id.ToString() platform.Id.ToString()
@@ -306,11 +317,13 @@ namespace gaseous_server.Classes
GameMode = collectionItem.Players.ConvertAll(s => s.ToString()), GameMode = collectionItem.Players.ConvertAll(s => s.ToString()),
PlayerPerspective = collectionItem.PlayerPerspectives.ConvertAll(s => s.ToString()), PlayerPerspective = collectionItem.PlayerPerspectives.ConvertAll(s => s.ToString()),
Theme = collectionItem.Themes.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, MinimumRating = collectionItem.MinimumRating,
MaximumRating = collectionItem.MaximumRating MaximumRating = collectionItem.MaximumRating
}, },
GameAgeRating = new Controllers.v1_1.GamesController.GameSearchModel.GameAgeRatingItem{ GameAgeRating = new Controllers.v1_1.GamesController.GameSearchModel.GameAgeRatingItem
{
AgeGroupings = UserAgeGroupings, AgeGroupings = UserAgeGroupings,
IncludeUnrated = UserAgeGroupIncludeUnrated IncludeUnrated = UserAgeGroupIncludeUnrated
} }
@@ -331,20 +344,21 @@ namespace gaseous_server.Classes
alwaysIncludeItem.InclusionState == CollectionItem.AlwaysIncludeStatus.AlwaysExclude alwaysIncludeItem.InclusionState == CollectionItem.AlwaysIncludeStatus.AlwaysExclude
) && alwaysIncludeItem.PlatformId == platform.Id ) && alwaysIncludeItem.PlatformId == platform.Id
) )
{ {
MinimalGameItem AlwaysIncludeGame = new MinimalGameItem(Games.GetGame(alwaysIncludeItem.GameId, false, false, false)); MinimalGameItem AlwaysIncludeGame = new MinimalGameItem(Games.GetGame(Communications.MetadataSource, alwaysIncludeItem.GameId));
CollectionContents.CollectionPlatformItem.CollectionGameItem gameItem = new CollectionContents.CollectionPlatformItem.CollectionGameItem(AlwaysIncludeGame); CollectionContents.CollectionPlatformItem.CollectionGameItem gameItem = new CollectionContents.CollectionPlatformItem.CollectionGameItem(AlwaysIncludeGame);
gameItem.InclusionStatus = new CollectionItem.AlwaysIncludeItem(); gameItem.InclusionStatus = new CollectionItem.AlwaysIncludeItem();
gameItem.InclusionStatus.PlatformId = alwaysIncludeItem.PlatformId; gameItem.InclusionStatus.PlatformId = alwaysIncludeItem.PlatformId;
gameItem.InclusionStatus.GameId = alwaysIncludeItem.GameId; gameItem.InclusionStatus.GameId = alwaysIncludeItem.GameId;
gameItem.InclusionStatus.InclusionState = alwaysIncludeItem.InclusionState; gameItem.InclusionStatus.InclusionState = alwaysIncludeItem.InclusionState;
gameItem.Roms = Roms.GetRoms((long)gameItem.Id, (long)platform.Id).GameRomItems; 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; bool gameAlreadyInList = false;
foreach (CollectionContents.CollectionPlatformItem.CollectionGameItem existingGame in collectionPlatformItem.Games) foreach (CollectionContents.CollectionPlatformItem.CollectionGameItem existingGame in collectionPlatformItem.Games)
{ {
@@ -364,11 +378,14 @@ namespace gaseous_server.Classes
// calculate total rom size for the game // calculate total rom size for the game
long GameRomSize = 0; long GameRomSize = 0;
foreach (Roms.GameRomItem gameRom in gameRoms) { foreach (Roms.GameRomItem gameRom in gameRoms)
{
GameRomSize += (long)gameRom.Size; GameRomSize += (long)gameRom.Size;
} }
if (collectionItem.MaximumBytesPerPlatform > 0) { if (collectionItem.MaximumBytesPerPlatform > 0)
if ((TotalRomSize + GameRomSize) < collectionItem.MaximumBytesPerPlatform) { {
if ((TotalRomSize + GameRomSize) < collectionItem.MaximumBytesPerPlatform)
{
AddGame = true; AddGame = true;
} }
} }
@@ -377,13 +394,16 @@ namespace gaseous_server.Classes
AddGame = true; AddGame = true;
} }
if (AddGame == true) { if (AddGame == true)
{
TotalRomSize += GameRomSize; TotalRomSize += GameRomSize;
bool AddRoms = false; bool AddRoms = false;
if (collectionItem.MaximumRomsPerPlatform > 0) { if (collectionItem.MaximumRomsPerPlatform > 0)
if (TotalGameCount < collectionItem.MaximumRomsPerPlatform) { {
if (TotalGameCount < collectionItem.MaximumRomsPerPlatform)
{
AddRoms = true; AddRoms = true;
} }
} }
@@ -392,7 +412,8 @@ namespace gaseous_server.Classes
AddRoms = true; AddRoms = true;
} }
if (AddRoms == true) { if (AddRoms == true)
{
TotalGameCount += 1; TotalGameCount += 1;
collectionGameItem.Roms = gameRoms; collectionGameItem.Roms = gameRoms;
collectionPlatformItem.Games.Add(collectionGameItem); collectionPlatformItem.Games.Add(collectionGameItem);
@@ -401,7 +422,8 @@ namespace gaseous_server.Classes
} }
// handle age grouping // handle age grouping
AgeGroups.AgeRestrictionGroupings CurrentAgeGroup = AgeGroups.GetAgeGroupFromAgeRatings(game.AgeRatings); List<AgeRating> gameAgeRatings = game.AgeRatings.Select(s => (AgeRating)s).ToList();
AgeGroups.AgeRestrictionGroupings CurrentAgeGroup = AgeGroups.GetAgeGroupFromAgeRatings(gameAgeRatings);
if (CurrentAgeGroup > AgeGrouping) if (CurrentAgeGroup > AgeGrouping)
{ {
AgeGrouping = CurrentAgeGroup; AgeGrouping = CurrentAgeGroup;
@@ -500,7 +522,8 @@ namespace gaseous_server.Classes
if (collectionItem.IncludeBIOSFiles == true) if (collectionItem.IncludeBIOSFiles == true)
{ {
List<Bios.BiosItem> bios = Bios.GetBios(collectionPlatformItem.Id, true); List<Bios.BiosItem> bios = Bios.GetBios(collectionPlatformItem.Id, true);
if (!Directory.Exists(ZipBiosPath)) { if (!Directory.Exists(ZipBiosPath))
{
Directory.CreateDirectory(ZipBiosPath); Directory.CreateDirectory(ZipBiosPath);
} }
@@ -590,7 +613,7 @@ namespace gaseous_server.Classes
// compress to zip // compress to zip
Logging.Log(Logging.LogType.Information, "Collections", "Compressing collection"); Logging.Log(Logging.LogType.Information, "Collections", "Compressing collection");
switch(collectionItem.ArchiveType) switch (collectionItem.ArchiveType)
{ {
case CollectionItem.ArchiveTypes.Zip: case CollectionItem.ArchiveTypes.Zip:
ZipFile.CreateFromDirectory(ZipFileTempPath, ZipFilePath, CompressionLevel.SmallestSize, false); ZipFile.CreateFromDirectory(ZipFileTempPath, ZipFilePath, CompressionLevel.SmallestSize, false);
@@ -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 strPlatforms = (string)Common.ReturnValueIfNull(row["Platforms"], "[ ]");
string strGenres = (string)Common.ReturnValueIfNull(row["Genres"], "[ ]"); string strGenres = (string)Common.ReturnValueIfNull(row["Genres"], "[ ]");
string strPlayers = (string)Common.ReturnValueIfNull(row["Players"], "[ ]"); string strPlayers = (string)Common.ReturnValueIfNull(row["Players"], "[ ]");
@@ -810,7 +834,8 @@ namespace gaseous_server.Classes
} }
} }
public class CollectionContents { public class CollectionContents
{
[JsonIgnore] [JsonIgnore]
public List<CollectionPlatformItem> Collection { get; set; } public List<CollectionPlatformItem> Collection { get; set; }
@@ -840,13 +865,16 @@ namespace gaseous_server.Classes
public AgeGroups.AgeRestrictionGroupings AgeGroup { get; set; } public AgeGroups.AgeRestrictionGroupings AgeGroup { get; set; }
public bool ContainsUnclassifiedAgeGroup { get; set; } public bool ContainsUnclassifiedAgeGroup { get; set; }
public class CollectionPlatformItem { public class CollectionPlatformItem
public CollectionPlatformItem(IGDB.Models.Platform platform) { {
public CollectionPlatformItem(Platform platform)
{
string[] PropertyWhitelist = new string[] { "Id", "Name", "Slug" }; string[] PropertyWhitelist = new string[] { "Id", "Name", "Slug" };
PropertyInfo[] srcProperties = typeof(IGDB.Models.Platform).GetProperties(); PropertyInfo[] srcProperties = typeof(Platform).GetProperties();
PropertyInfo[] dstProperties = typeof(CollectionPlatformItem).GetProperties(); PropertyInfo[] dstProperties = typeof(CollectionPlatformItem).GetProperties();
foreach (PropertyInfo srcProperty in srcProperties) { foreach (PropertyInfo srcProperty in srcProperties)
{
if (PropertyWhitelist.Contains<string>(srcProperty.Name)) if (PropertyWhitelist.Contains<string>(srcProperty.Name))
{ {
foreach (PropertyInfo dstProperty in dstProperties) foreach (PropertyInfo dstProperty in dstProperties)
@@ -866,10 +894,13 @@ namespace gaseous_server.Classes
public List<CollectionGameItem> Games { get; set; } public List<CollectionGameItem> Games { get; set; }
public int RomCount { public int RomCount
get { {
get
{
int Counter = 0; int Counter = 0;
foreach (CollectionGameItem Game in Games) { foreach (CollectionGameItem Game in Games)
{
Counter += 1; Counter += 1;
} }
@@ -877,11 +908,15 @@ namespace gaseous_server.Classes
} }
} }
public long RomSize { public long RomSize
get { {
get
{
long Size = 0; long Size = 0;
foreach (CollectionGameItem Game in Games) { foreach (CollectionGameItem Game in Games)
foreach (Roms.GameRomItem Rom in Game.Roms) { {
foreach (Roms.GameRomItem Rom in Game.Roms)
{
Size += (long)Rom.Size; Size += (long)Rom.Size;
} }
} }
@@ -905,28 +940,12 @@ namespace gaseous_server.Classes
this.AgeRatings = gameObject.AgeRatings; this.AgeRatings = gameObject.AgeRatings;
} }
public IGDB.Models.Cover? CoverItem
{
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 public AgeGroups.AgeRestrictionGroupings AgeGrouping
{ {
get get
{ {
return AgeGroups.GetAgeGroupFromAgeRatings(this.AgeRatings); List<AgeRating> gameAgeRatings = this.AgeRatings.Select(s => (AgeRating)s).ToList();
return AgeGroups.GetAgeGroupFromAgeRatings(gameAgeRatings);
} }
} }
@@ -934,17 +953,20 @@ namespace gaseous_server.Classes
public List<Roms.GameRomItem> Roms { get; set; } public List<Roms.GameRomItem> Roms { get; set; }
public long RomSize { public long RomSize
get { {
long Size = 0; get
foreach (Roms.GameRomItem Rom in Roms) { {
Size += (long)Rom.Size; long Size = 0;
} foreach (Roms.GameRomItem Rom in Roms)
{
Size += (long)Rom.Size;
}
return Size; return Size;
}
} }
} }
}
} }
} }
} }

View File

@@ -1,7 +1,6 @@
using System; using System;
using System.Data; using System.Data;
using Newtonsoft.Json; using Newtonsoft.Json;
using IGDB.Models;
using gaseous_server.Classes.Metadata; using gaseous_server.Classes.Metadata;
using NuGet.Common; 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); string MetadataPath = Path.Combine(LibraryMetadataDirectory, "Platforms", platform.Slug);
if (!Directory.Exists(MetadataPath)) { Directory.CreateDirectory(MetadataPath); } if (!Directory.Exists(MetadataPath)) { Directory.CreateDirectory(MetadataPath); }
return 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); string MetadataPath = Path.Combine(LibraryMetadataDirectory, "Games", game.Slug);
if (!Directory.Exists(MetadataPath)) { Directory.CreateDirectory(MetadataPath); } if (!Directory.Exists(MetadataPath)) { Directory.CreateDirectory(MetadataPath); }
return 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); string MetadataPath = Path.Combine(LibraryMetadataDirectory, "Companies", company.Slug);
if (!Directory.Exists(MetadataPath)) { Directory.CreateDirectory(MetadataPath); } if (!Directory.Exists(MetadataPath)) { Directory.CreateDirectory(MetadataPath); }

View File

@@ -3,7 +3,6 @@ using System.Data;
using System.Reflection; using System.Reflection;
using gaseous_server.Classes.Metadata; using gaseous_server.Classes.Metadata;
using gaseous_server.Models; using gaseous_server.Models;
using IGDB.Models;
namespace gaseous_server.Classes namespace gaseous_server.Classes
{ {
@@ -394,8 +393,8 @@ namespace gaseous_server.Classes
(string)row["Path"] (string)row["Path"]
); );
Platform platform = Platforms.GetPlatform((long)row["PlatformId"], false); HasheousClient.Models.Metadata.IGDB.Platform platform = Platforms.GetPlatform((long)row["PlatformId"]);
Game game = Games.GetGame((long)row["GameId"], false, false, false); Game game = Games.GetGame(Communications.MetadataSource, (long)row["GameId"]);
ImportGame.StoreROM(library, hash, game, platform, signature, (string)row["Path"], (long)row["Id"]); ImportGame.StoreROM(library, hash, game, platform, signature, (string)row["Path"], (long)row["Id"]);

View File

@@ -342,7 +342,7 @@ namespace gaseous_server.Classes
switch (metadataResult.Source) switch (metadataResult.Source)
{ {
case HasheousClient.Models.MetadataSources.IGDB: 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; break;
} }
} }

View File

@@ -2,7 +2,6 @@ using System;
using System.Data; using System.Data;
using gaseous_server.Classes; using gaseous_server.Classes;
using gaseous_server.Classes.Metadata; using gaseous_server.Classes.Metadata;
using IGDB.Models;
using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow; using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow;
namespace gaseous_server namespace gaseous_server
@@ -237,7 +236,7 @@ namespace gaseous_server
{ {
if (_DefaultPlatformId != 0) if (_DefaultPlatformId != 0)
{ {
Platform platform = Platforms.GetPlatform(_DefaultPlatformId); HasheousClient.Models.Metadata.IGDB.Platform platform = Platforms.GetPlatform(_DefaultPlatformId);
return platform.Name; return platform.Name;
} }
else else

View File

@@ -7,12 +7,12 @@ using System.Text.RegularExpressions;
using System.Threading.Tasks; using System.Threading.Tasks;
using gaseous_server.Classes.Metadata; using gaseous_server.Classes.Metadata;
using gaseous_server.Models; using gaseous_server.Models;
using IGDB.Models;
using NuGet.Common; using NuGet.Common;
using NuGet.LibraryModel; using NuGet.LibraryModel;
using static gaseous_server.Classes.Metadata.Games; using static gaseous_server.Classes.Metadata.Games;
using static gaseous_server.Classes.FileSignature; using static gaseous_server.Classes.FileSignature;
using HasheousClient.Models; using HasheousClient.Models;
using HasheousClient.Models.Metadata.IGDB;
namespace gaseous_server.Classes namespace gaseous_server.Classes
{ {
@@ -47,7 +47,7 @@ namespace gaseous_server.Classes
} }
} }
public Dictionary<string, object> ImportGameFile(string GameFileImportPath, IGDB.Models.Platform? OverridePlatform) public Dictionary<string, object> ImportGameFile(string GameFileImportPath, Platform? OverridePlatform)
{ {
Dictionary<string, object> RetVal = new Dictionary<string, object>(); Dictionary<string, object> RetVal = new Dictionary<string, object>();
RetVal.Add("path", Path.GetFileName(GameFileImportPath)); 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); gaseous_server.Models.Signatures_Games discoveredSignature = fileSignature.GetFileSignature(GameLibrary.GetDefaultLibrary, hash, fi, GameFileImportPath);
// get discovered platform // get discovered platform
IGDB.Models.Platform? determinedPlatform = null; Platform? determinedPlatform = null;
if (OverridePlatform == null) if (OverridePlatform == null)
{ {
determinedPlatform = Metadata.Platforms.GetPlatform(discoveredSignature.Flags.IGDBPlatformId); determinedPlatform = Metadata.Platforms.GetPlatform(discoveredSignature.Flags.IGDBPlatformId);
if (determinedPlatform == null) if (determinedPlatform == null)
{ {
determinedPlatform = new IGDB.Models.Platform(); determinedPlatform = new Platform();
} }
} }
else else
@@ -126,7 +126,7 @@ namespace gaseous_server.Classes
discoveredSignature.Flags.IGDBPlatformName = determinedPlatform.Name; 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 // add to database
long RomId = StoreROM(GameLibrary.GetDefaultLibrary, hash, determinedGame, determinedPlatform, discoveredSignature, GameFileImportPath, 0, true); 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); File.Move(GameFileImportPath, biosItem.biosPath, true);
RetVal.Add("name", biosItem.filename); RetVal.Add("name", biosItem.filename);
RetVal.Add("platform", Platforms.GetPlatform(biosItem.platformid, false, false)); RetVal.Add("platform", Platforms.GetPlatform(biosItem.platformid));
RetVal["status"] = "imported"; RetVal["status"] = "imported";
return RetVal; return RetVal;
@@ -178,7 +178,7 @@ namespace gaseous_server.Classes
return RetVal; 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) if (Signature.Flags != null)
{ {
@@ -187,7 +187,7 @@ namespace gaseous_server.Classes
// game was determined elsewhere - probably a Hasheous server // game was determined elsewhere - probably a Hasheous server
try try
{ {
return Games.GetGame(Signature.Flags.IGDBGameId, false, false, FullDownload); return Games.GetGame(Communications.MetadataSource, Signature.Flags.IGDBGameId);
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -197,7 +197,7 @@ namespace gaseous_server.Classes
} }
// search discovered game - case insensitive exact match first // 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; 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))) foreach (Metadata.Games.SearchType searchType in Enum.GetValues(typeof(Metadata.Games.SearchType)))
{ {
Logging.Log(Logging.LogType.Information, "Import Game", " Search type: " + searchType.ToString()); 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 != null)
{ {
if (games.Length == 1) if (games.Length == 1)
{ {
// exact match! // 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); Logging.Log(Logging.LogType.Information, "Import Game", " IGDB game: " + determinedGame.Name);
GameFound = true; GameFound = true;
break; break;
@@ -228,12 +228,12 @@ namespace gaseous_server.Classes
Logging.Log(Logging.LogType.Information, "Import Game", " " + games.Length + " search results found"); Logging.Log(Logging.LogType.Information, "Import Game", " " + games.Length + " search results found");
// quite likely we've found sequels and alternate types // 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) if (game.Name == SearchCandidate)
{ {
// found game title matches the search candidate // 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!"); Logging.Log(Logging.LogType.Information, "Import Game", "Found exact match!");
GameFound = true; GameFound = true;
break; break;
@@ -254,7 +254,7 @@ namespace gaseous_server.Classes
} }
if (determinedGame == null) if (determinedGame == null)
{ {
determinedGame = new IGDB.Models.Game(); determinedGame = new gaseous_server.Models.Game();
} }
string destSlug = ""; string destSlug = "";
@@ -266,9 +266,9 @@ namespace gaseous_server.Classes
return determinedGame; return determinedGame;
} }
public static List<IGDB.Models.Game> SearchForGame_GetAll(string GameName, long PlatformId) public static List<gaseous_server.Models.Game> SearchForGame_GetAll(string GameName, long PlatformId)
{ {
List<IGDB.Models.Game> searchResults = new List<IGDB.Models.Game>(); List<gaseous_server.Models.Game> searchResults = new List<gaseous_server.Models.Game>();
List<string> SearchCandidates = GetSearchCandidates(GameName); List<string> SearchCandidates = GetSearchCandidates(GameName);
@@ -278,11 +278,11 @@ namespace gaseous_server.Classes
{ {
if ((PlatformId == 0 && searchType == SearchType.searchNoPlatform) || (PlatformId != 0 && searchType != SearchType.searchNoPlatform)) if ((PlatformId == 0 && searchType == SearchType.searchNoPlatform) || (PlatformId != 0 && searchType != SearchType.searchNoPlatform))
{ {
IGDB.Models.Game[] games = Metadata.Games.SearchForGame(SearchCandidate, PlatformId, searchType); gaseous_server.Models.Game[] games = Metadata.Games.SearchForGame(SearchCandidate, PlatformId, searchType);
foreach (IGDB.Models.Game foundGame in games) foreach (gaseous_server.Models.Game foundGame in games)
{ {
bool gameInResults = false; bool gameInResults = false;
foreach (IGDB.Models.Game searchResult in searchResults) foreach (gaseous_server.Models.Game searchResult in searchResults)
{ {
if (searchResult.Id == foundGame.Id) if (searchResult.Id == foundGame.Id)
{ {
@@ -333,7 +333,7 @@ namespace gaseous_server.Classes
return SearchCandidates; 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); 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); Classes.Roms.GameRomItem rom = Classes.Roms.GetRom(RomId);
// get metadata // get metadata
IGDB.Models.Platform platform = gaseous_server.Classes.Metadata.Platforms.GetPlatform(rom.PlatformId); 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); gaseous_server.Models.Game game = gaseous_server.Classes.Metadata.Games.GetGame(Communications.MetadataSource, rom.GameId);
// build path // build path
string platformSlug = "Unknown Platform"; string platformSlug = "Unknown Platform";
@@ -728,7 +728,7 @@ namespace gaseous_server.Classes
{ {
// get discovered platform // get discovered platform
long PlatformId; long PlatformId;
IGDB.Models.Platform determinedPlatform; Platform determinedPlatform;
if (sig.Flags.IGDBPlatformId == null || sig.Flags.IGDBPlatformId == 0) if (sig.Flags.IGDBPlatformId == null || sig.Flags.IGDBPlatformId == 0)
{ {
@@ -742,7 +742,7 @@ namespace gaseous_server.Classes
} }
determinedPlatform = Platforms.GetPlatform(PlatformId); 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); StoreROM(library, hash, determinedGame, determinedPlatform, sig, LibraryFile);
} }
@@ -854,7 +854,7 @@ namespace gaseous_server.Classes
// get discovered platform // get discovered platform
long PlatformId; long PlatformId;
IGDB.Models.Platform determinedPlatform; Platform determinedPlatform;
if (sig.Flags.IGDBPlatformId == null || sig.Flags.IGDBPlatformId == 0) if (sig.Flags.IGDBPlatformId == null || sig.Flags.IGDBPlatformId == 0)
{ {
@@ -868,7 +868,7 @@ namespace gaseous_server.Classes
} }
determinedPlatform = Platforms.GetPlatform(PlatformId); 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); StoreROM(library, hash, determinedGame, determinedPlatform, sig, romPath, romId);

View File

@@ -1,8 +1,8 @@
using System; using System;
using System.Reflection; using System.Reflection;
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
using IGDB; using gaseous_server.Models;
using IGDB.Models; using HasheousClient.Models.Metadata.IGDB;
using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Classification;
namespace gaseous_server.Classes.Metadata 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) if (game == null)
{ {
@@ -23,7 +23,7 @@ namespace gaseous_server.Classes.Metadata
else else
{ {
Storage.CacheStatus? cacheStatus = new Storage.CacheStatus(); 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(); AgeGroup? RetVal = new AgeGroup();
@@ -31,16 +31,16 @@ namespace gaseous_server.Classes.Metadata
{ {
case Storage.CacheStatus.NotPresent: case Storage.CacheStatus.NotPresent:
RetVal = _GetAgeGroup(game); RetVal = _GetAgeGroup(game);
Storage.NewCacheValue(RetVal, false); Storage.NewCacheValue(Communications.MetadataSource, RetVal, false);
break; break;
case Storage.CacheStatus.Expired: case Storage.CacheStatus.Expired:
RetVal = _GetAgeGroup(game); RetVal = _GetAgeGroup(game);
Storage.NewCacheValue(RetVal, true); Storage.NewCacheValue(Communications.MetadataSource, RetVal, true);
break; break;
case Storage.CacheStatus.Current: case Storage.CacheStatus.Current:
RetVal = Storage.GetCacheValue<AgeGroup>(RetVal, "Id", game.Id); RetVal = Storage.GetCacheValue<AgeGroup>(Communications.MetadataSource, RetVal, "Id", game.Id);
break; break;
default: 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 // compile the maximum age group for the given game
if (game != null) if (game != null)
{ {
if (game.AgeRatings != null) if (game.AgeRatings != null)
{ {
if (game.AgeRatings.Ids != null) if (game.AgeRatings != null)
{ {
// collect ratings values from metadata // collect ratings values from metadata
List<AgeRating> ageRatings = new List<AgeRating>(); List<AgeRating> ageRatings = new List<AgeRating>();
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) if (rating != null)
{ {
ageRatings.Add(rating); ageRatings.Add(rating);
@@ -262,13 +262,13 @@ namespace gaseous_server.Classes.Metadata
public class AgeGroupItem public class AgeGroupItem
{ {
public List<IGDB.Models.AgeRatingTitle> ACB { get; set; } public List<AgeRatingTitle> ACB { get; set; }
public List<IGDB.Models.AgeRatingTitle> CERO { get; set; } public List<AgeRatingTitle> CERO { get; set; }
public List<IGDB.Models.AgeRatingTitle> CLASS_IND { get; set; } public List<AgeRatingTitle> CLASS_IND { get; set; }
public List<IGDB.Models.AgeRatingTitle> ESRB { get; set; } public List<AgeRatingTitle> ESRB { get; set; }
public List<IGDB.Models.AgeRatingTitle> GRAC { get; set; } public List<AgeRatingTitle> GRAC { get; set; }
public List<IGDB.Models.AgeRatingTitle> PEGI { get; set; } public List<AgeRatingTitle> PEGI { get; set; }
public List<IGDB.Models.AgeRatingTitle> USK { get; set; } public List<AgeRatingTitle> USK { get; set; }
[JsonIgnore] [JsonIgnore]
[Newtonsoft.Json.JsonIgnore] [Newtonsoft.Json.JsonIgnore]

View File

@@ -2,8 +2,7 @@
using System.Buffers; using System.Buffers;
using System.Reflection; using System.Reflection;
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
using IGDB; using HasheousClient.Models.Metadata.IGDB;
using IGDB.Models;
using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Classification;
namespace gaseous_server.Classes.Metadata 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)) if ((Id == 0) || (Id == null))
{ {
@@ -24,72 +23,16 @@ namespace gaseous_server.Classes.Metadata
} }
else else
{ {
Task<AgeRating> RetVal = _GetAgeRatings((long)Id); AgeRating? RetVal = Metadata.GetMetadata<AgeRating>(SourceType, (long)Id, false);
return RetVal.Result; return RetVal;
} }
} }
private static async Task<AgeRating> _GetAgeRatings(long searchValue) public static GameAgeRating GetConsolidatedAgeRating(HasheousClient.Models.MetadataModel.MetadataSources SourceType, long RatingId)
{
// 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<AgeRating>(returnValue, "id", (long)searchValue);
}
break;
case Storage.CacheStatus.Current:
returnValue = Storage.GetCacheValue<AgeRating>(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<AgeRating> GetObjectFromServer(long searchValue)
{
// get AgeRatings metadata
Communications comms = new Communications();
var results = await comms.APIComm<AgeRating>(Communications.MetadataEndpoint.AgeRating, searchValue);
var result = results.First();
return result;
}
public static GameAgeRating GetConsolidatedAgeRating(long RatingId)
{ {
GameAgeRating gameAgeRating = new GameAgeRating(); GameAgeRating gameAgeRating = new GameAgeRating();
AgeRating ageRating = GetAgeRatings(RatingId); AgeRating ageRating = GetAgeRating(SourceType, RatingId);
gameAgeRating.Id = (long)ageRating.Id; gameAgeRating.Id = (long)ageRating.Id;
gameAgeRating.RatingBoard = (AgeRatingCategory)ageRating.Category; gameAgeRating.RatingBoard = (AgeRatingCategory)ageRating.Category;
gameAgeRating.RatingTitle = (AgeRatingTitle)ageRating.Rating; gameAgeRating.RatingTitle = (AgeRatingTitle)ageRating.Rating;
@@ -97,9 +40,9 @@ namespace gaseous_server.Classes.Metadata
List<string> descriptions = new List<string>(); List<string> descriptions = new List<string>();
if (ageRating.ContentDescriptions != null) 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); descriptions.Add(ageRatingContentDescription.Description);
} }
} }

View File

@@ -1,6 +1,5 @@
using System; using System;
using IGDB; using HasheousClient.Models.Metadata.IGDB;
using IGDB.Models;
namespace gaseous_server.Classes.Metadata 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)) if ((Id == 0) || (Id == null))
{ {
@@ -21,54 +20,10 @@ namespace gaseous_server.Classes.Metadata
} }
else else
{ {
Task<AgeRatingContentDescription> RetVal = _GetAgeRatingContentDescriptions((long)Id); AgeRatingContentDescription? RetVal = Metadata.GetMetadata<AgeRatingContentDescription>(SourceType, (long)Id, false);
return RetVal.Result; return RetVal;
} }
} }
private static async Task<AgeRatingContentDescription> _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<AgeRatingContentDescription>(returnValue, "id", (long)searchValue);
}
break;
case Storage.CacheStatus.Current:
returnValue = Storage.GetCacheValue<AgeRatingContentDescription>(returnValue, "id", (long)searchValue);
break;
default:
throw new Exception("How did you get here?");
}
return returnValue;
}
private static async Task<AgeRatingContentDescription> GetObjectFromServer(long searchValue)
{
// get AgeRatingContentDescriptionContentDescriptions metadata
Communications comms = new Communications();
var results = await comms.APIComm<AgeRatingContentDescription>(Communications.MetadataEndpoint.AgeRatingContentDescription, searchValue);
var result = results.First();
return result;
}
} }
} }

View File

@@ -1,6 +1,5 @@
using System; using System;
using IGDB; using HasheousClient.Models.Metadata.IGDB;
using IGDB.Models;
namespace gaseous_server.Classes.Metadata 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)) if ((Id == 0) || (Id == null))
{ {
@@ -21,54 +20,10 @@ namespace gaseous_server.Classes.Metadata
} }
else else
{ {
Task<AlternativeName> RetVal = _GetAlternativeNames((long)Id); AlternativeName? RetVal = Metadata.GetMetadata<AlternativeName>(SourceType, (long)Id, false);
return RetVal.Result; return RetVal;
} }
} }
private static async Task<AlternativeName> _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<AlternativeName>(returnValue, "id", (long)searchValue);
}
break;
case Storage.CacheStatus.Current:
returnValue = Storage.GetCacheValue<AlternativeName>(returnValue, "id", (long)searchValue);
break;
default:
throw new Exception("How did you get here?");
}
return returnValue;
}
private static async Task<AlternativeName> GetObjectFromServer(long searchValue)
{
// get AlternativeNames metadata
Communications comms = new Communications();
var results = await comms.APIComm<AlternativeName>(Communications.MetadataEndpoint.AlternativeName, searchValue);
var result = results.First();
return result;
}
} }
} }

View File

@@ -1,7 +1,5 @@
using System; using System;
using IGDB; using HasheousClient.Models.Metadata.IGDB;
using IGDB.Models;
namespace gaseous_server.Classes.Metadata 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)) if ((Id == 0) || (Id == null))
{ {
@@ -21,75 +19,10 @@ namespace gaseous_server.Classes.Metadata
} }
else else
{ {
Task<Artwork> RetVal = _GetArtwork((long)Id, ImagePath, GetImages); Artwork? RetVal = Metadata.GetMetadata<Artwork>(SourceType, (long)Id, false);
return RetVal.Result; return RetVal;
} }
} }
private static async Task<Artwork> _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<Artwork>(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<Artwork>(returnValue, "id", (long)searchValue);
}
break;
case Storage.CacheStatus.Current:
returnValue = Storage.GetCacheValue<Artwork>(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<Artwork> GetObjectFromServer(long searchValue, string ImagePath)
{
// get Artwork metadata
Communications comms = new Communications();
var results = await comms.APIComm<Artwork>(Communications.MetadataEndpoint.Artwork, searchValue);
var result = results.First();
return result;
}
} }
} }

View File

@@ -1,7 +1,5 @@
using System; using System;
using IGDB; using HasheousClient.Models.Metadata.IGDB;
using IGDB.Models;
namespace gaseous_server.Classes.Metadata 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)) if ((Id == 0) || (Id == null))
{ {
@@ -21,54 +19,10 @@ namespace gaseous_server.Classes.Metadata
} }
else else
{ {
Task<Collection> RetVal = _GetCollections((long)Id); Collection? RetVal = Metadata.GetMetadata<Collection>(SourceType, (long)Id, false);
return RetVal.Result; return RetVal;
} }
} }
private static async Task<Collection> _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<Collection>(returnValue, "id", (long)searchValue);
}
break;
case Storage.CacheStatus.Current:
returnValue = Storage.GetCacheValue<Collection>(returnValue, "id", (long)searchValue);
break;
default:
throw new Exception("How did you get here?");
}
return returnValue;
}
private static async Task<Collection> GetObjectFromServer(long searchValue)
{
// get Collections metadata
Communications comms = new Communications();
var results = await comms.APIComm<Collection>(Communications.MetadataEndpoint.Collection, searchValue);
var result = results.First();
return result;
}
} }
} }

View File

@@ -211,7 +211,7 @@ namespace gaseous_server.Classes.Metadata
} }
/// <summary> /// <summary>
/// Request data from the metadata API using a slug /// Request data from the metadata API using a slug using the default source
/// </summary> /// </summary>
/// <typeparam name="T"> /// <typeparam name="T">
/// The type of object to return /// The type of object to return
@@ -227,7 +227,27 @@ namespace gaseous_server.Classes.Metadata
/// </returns> /// </returns>
public async Task<T[]?> APIComm<T>(MetadataEndpoint Endpoint, string Slug) public async Task<T[]?> APIComm<T>(MetadataEndpoint Endpoint, string Slug)
{ {
switch (_MetadataSource) return await APIComm<T>(_MetadataSource, Endpoint, Slug);
}
/// <summary>
/// Request data from the metadata API using a slug
/// </summary>
/// <typeparam name="T">
/// The type of object to return
/// </typeparam>
/// <param name="Endpoint">
/// The endpoint to access - can only be either Platform or Game
/// </param>
/// <param name="Slug">
/// The slug to query for
/// </param>
/// <returns>
/// The object requested
/// </returns>
public async Task<T[]?> APIComm<T>(HasheousClient.Models.MetadataModel.MetadataSources SourceType, MetadataEndpoint Endpoint, string Slug)
{
switch (SourceType)
{ {
case HasheousClient.Models.MetadataModel.MetadataSources.None: case HasheousClient.Models.MetadataModel.MetadataSources.None:
return null; return null;
@@ -266,7 +286,7 @@ namespace gaseous_server.Classes.Metadata
} }
/// <summary> /// <summary>
/// Request data from the metadata API using an id /// Request data from the metadata API using an id using the default source
/// </summary> /// </summary>
/// <typeparam name="T"> /// <typeparam name="T">
/// The type of object to return /// The type of object to return
@@ -282,7 +302,30 @@ namespace gaseous_server.Classes.Metadata
/// </returns> /// </returns>
public async Task<T[]> APIComm<T>(MetadataEndpoint Endpoint, long Id) public async Task<T[]> APIComm<T>(MetadataEndpoint Endpoint, long Id)
{ {
switch (_MetadataSource) return await APIComm<T>(_MetadataSource, Endpoint, Id);
}
/// <summary>
/// Request data from the metadata API using an id
/// </summary>
/// <typeparam name="T">
/// The type of object to return
/// </typeparam>
/// <param name="SourceType">
/// The source of the metadata
/// </param>
/// <param name="Endpoint">
/// The endpoint to access
/// </param>
/// <param name="Id">
/// The Id to query for
/// </param>
/// <returns>
/// The object requested
/// </returns>
public async Task<T[]> APIComm<T>(HasheousClient.Models.MetadataModel.MetadataSources SourceType, MetadataEndpoint Endpoint, long Id)
{
switch (SourceType)
{ {
case HasheousClient.Models.MetadataModel.MetadataSources.None: case HasheousClient.Models.MetadataModel.MetadataSources.None:
return null; return null;
@@ -874,14 +917,17 @@ namespace gaseous_server.Classes.Metadata
if (property.PropertyType.IsEnum) if (property.PropertyType.IsEnum)
{ {
// check if property is null // 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 if (input.GetType().GetProperty(property.Name).GetValue(input) != null)
Type enumType = property.PropertyType; {
// get the enum value // get the enum type
object enumValue = Enum.Parse(enumType, input.GetType().GetProperty(property.Name).GetValue(input).ToString()); Type enumType = property.PropertyType;
// set the enum value // get the enum value
property.SetValue(output, enumValue); 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)) else if (Common.IsNullableEnum(property.PropertyType))

View File

@@ -1,6 +1,5 @@
using System; using System;
using IGDB; using HasheousClient.Models.Metadata.IGDB;
using IGDB.Models;
namespace gaseous_server.Classes.Metadata 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)) if ((Id == 0) || (Id == null))
{ {
@@ -20,71 +19,10 @@ namespace gaseous_server.Classes.Metadata
} }
else else
{ {
Task<Company> RetVal = _GetCompanies((long)Id); Company? RetVal = Metadata.GetMetadata<Company>(SourceType, (long)Id, false);
return RetVal.Result; return RetVal;
} }
} }
private static async Task<Company> _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<Company>(returnValue, "id", (long)searchValue);
}
break;
case Storage.CacheStatus.Current:
returnValue = Storage.GetCacheValue<Company>(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<Company> GetObjectFromServer(long searchValue)
{
// get Companies metadata
Communications comms = new Communications();
var results = await comms.APIComm<Company>(Communications.MetadataEndpoint.Company, searchValue);
if (results.Length > 0)
{
var result = results.First();
return result;
}
else
{
return null;
}
}
} }
} }

View File

@@ -1,7 +1,5 @@
using System; using System;
using IGDB; using HasheousClient.Models.Metadata.IGDB;
using IGDB.Models;
namespace gaseous_server.Classes.Metadata namespace gaseous_server.Classes.Metadata
{ {
@@ -21,74 +19,10 @@ namespace gaseous_server.Classes.Metadata
} }
else else
{ {
Task<CompanyLogo> RetVal = _GetCompanyLogo((long)Id, ImagePath); CompanyLogo? RetVal = Metadata.GetMetadata<CompanyLogo>((long)Id, false);
return RetVal.Result; return RetVal;
} }
} }
private static async Task<CompanyLogo> _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<CompanyLogo>(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<CompanyLogo>(returnValue, "id", (long)searchValue);
}
break;
case Storage.CacheStatus.Current:
returnValue = Storage.GetCacheValue<CompanyLogo>(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<CompanyLogo> GetObjectFromServer(long searchValue, string ImagePath)
{
// get Artwork metadata
Communications comms = new Communications();
var results = await comms.APIComm<CompanyLogo>(Communications.MetadataEndpoint.CompanyLogo, searchValue);
var result = results.First();
return result;
}
} }
} }

View File

@@ -1,9 +1,5 @@
using System; using System;
using System.Net; using HasheousClient.Models.Metadata.IGDB;
using IGDB;
using IGDB.Models;
using Microsoft.CodeAnalysis.Elfie.Model.Strings;
namespace gaseous_server.Classes.Metadata 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)) if ((Id == 0) || (Id == null))
{ {
@@ -23,75 +19,10 @@ namespace gaseous_server.Classes.Metadata
} }
else else
{ {
Task<Cover> RetVal = _GetCover((long)Id, ImagePath, GetImages); Cover? RetVal = Metadata.GetMetadata<Cover>(SourceType, (long)Id, false);
return RetVal.Result; return RetVal;
} }
} }
private static async Task<Cover> _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<Cover>(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<Cover>(returnValue, "id", (long)searchValue);
}
break;
case Storage.CacheStatus.Current:
returnValue = Storage.GetCacheValue<Cover>(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<Cover> GetObjectFromServer(long searchValue, string ImagePath)
{
// get Cover metadata
Communications comms = new Communications();
var results = await comms.APIComm<Cover>(Communications.MetadataEndpoint.Cover, searchValue);
var result = results.First();
return result;
}
} }
} }

View File

@@ -1,7 +1,5 @@
using System; using System;
using IGDB; using HasheousClient.Models.Metadata.IGDB;
using IGDB.Models;
namespace gaseous_server.Classes.Metadata 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)) if ((Id == 0) || (Id == null))
{ {
@@ -21,62 +19,8 @@ namespace gaseous_server.Classes.Metadata
} }
else else
{ {
Task<ExternalGame> RetVal = _GetExternalGames((long)Id); ExternalGame? RetVal = Metadata.GetMetadata<ExternalGame>(SourceType, (long)Id, false);
return RetVal.Result; return RetVal;
}
}
private static async Task<ExternalGame> _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<ExternalGame>(returnValue, "id", (long)searchValue);
}
break;
case Storage.CacheStatus.Current:
returnValue = Storage.GetCacheValue<ExternalGame>(returnValue, "id", (long)searchValue);
break;
default:
throw new Exception("How did you get here?");
}
return returnValue;
}
private static async Task<ExternalGame?> GetObjectFromServer(long searchValue)
{
// get ExternalGames metadata
Communications comms = new Communications();
var results = await comms.APIComm<ExternalGame>(Communications.MetadataEndpoint.ExternalGame, searchValue);
if (results.Length > 0)
{
var result = results.First();
return result;
}
else
{
return null;
} }
} }
} }

View File

@@ -1,7 +1,5 @@
using System; using System;
using IGDB; using HasheousClient.Models.Metadata.IGDB;
using IGDB.Models;
namespace gaseous_server.Classes.Metadata 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)) if ((Id == 0) || (Id == null))
{ {
@@ -21,54 +19,10 @@ namespace gaseous_server.Classes.Metadata
} }
else else
{ {
Task<Franchise> RetVal = _GetFranchises((long)Id); Franchise? RetVal = Metadata.GetMetadata<Franchise>(SourceType, (long)Id, false);
return RetVal.Result; return RetVal;
} }
} }
private static async Task<Franchise> _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<Franchise>(returnValue, "id", (long)searchValue);
}
break;
case Storage.CacheStatus.Current:
returnValue = Storage.GetCacheValue<Franchise>(returnValue, "id", (long)searchValue);
break;
default:
throw new Exception("How did you get here?");
}
return returnValue;
}
private static async Task<Franchise> GetObjectFromServer(long searchValue)
{
// get FranchiseContentDescriptions metadata
Communications comms = new Communications();
var results = await comms.APIComm<Franchise>(Communications.MetadataEndpoint.Franchise, searchValue);
var result = results.First();
return result;
}
} }
} }

View File

@@ -1,6 +1,5 @@
using System; using System;
using IGDB; using HasheousClient.Models.Metadata.IGDB;
using IGDB.Models;
namespace gaseous_server.Classes.Metadata 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)) if ((Id == 0) || (Id == null))
{ {
@@ -21,54 +20,10 @@ namespace gaseous_server.Classes.Metadata
} }
else else
{ {
Task<GameMode> RetVal = _GetGame_Modes((long)Id); GameMode? RetVal = Metadata.GetMetadata<GameMode>(SourceType, (long)Id, false);
return RetVal.Result; return RetVal;
} }
} }
private static async Task<GameMode> _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<GameMode>(returnValue, "id", (long)searchValue);
}
break;
case Storage.CacheStatus.Current:
returnValue = Storage.GetCacheValue<GameMode>(returnValue, "id", (long)searchValue);
break;
default:
throw new Exception("How did you get here?");
}
return returnValue;
}
private static async Task<GameMode> GetObjectFromServer(long searchValue)
{
// get Game_Modes metadata
Communications comms = new Communications();
var results = await comms.APIComm<GameMode>(Communications.MetadataEndpoint.GameMode, searchValue);
var result = results.First();
return result;
}
} }
} }

View File

@@ -1,6 +1,5 @@
using System; using System;
using IGDB; using HasheousClient.Models.Metadata.IGDB;
using IGDB.Models;
namespace gaseous_server.Classes.Metadata 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)) if ((Id == 0) || (Id == null))
{ {
@@ -21,54 +20,10 @@ namespace gaseous_server.Classes.Metadata
} }
else else
{ {
Task<GameVideo> RetVal = _GetGame_Videos((long)Id); GameVideo? RetVal = Metadata.GetMetadata<GameVideo>(SourceType, (long)Id, false);
return RetVal.Result; return RetVal;
} }
} }
private static async Task<GameVideo> _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<GameVideo>(returnValue, "id", (long)searchValue);
}
break;
case Storage.CacheStatus.Current:
returnValue = Storage.GetCacheValue<GameVideo>(returnValue, "id", (long)searchValue);
break;
default:
throw new Exception("How did you get here?");
}
return returnValue;
}
private static async Task<GameVideo> GetObjectFromServer(long searchValue)
{
// get Game_Videos metadata
Communications comms = new Communications();
var results = await comms.APIComm<GameVideo>(Communications.MetadataEndpoint.GameVideo, searchValue);
var result = results.First();
return result;
}
} }
} }

View File

@@ -2,8 +2,6 @@
using System.Data; using System.Data;
using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.X509Certificates;
using gaseous_server.Models; using gaseous_server.Models;
using IGDB;
using IGDB.Models;
namespace gaseous_server.Classes.Metadata 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(); return null;
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<Game>(returnValue, "id", 0);
}
} }
else else
{ {
Task<Game> RetVal = _GetGame(SearchUsing.Id, Id, getAllMetadata, followSubGames, forceRefresh); Game? RetVal = Metadata.GetMetadata<Game>(SourceType, (long)Id, false);
return RetVal.Result; 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<Game> RetVal = _GetGame(SearchUsing.Slug, Slug, getAllMetadata, followSubGames, forceRefresh); throw new NotImplementedException();
return RetVal.Result;
} }
public static Game GetGame(DataRow dataRow) public static Game GetGame(DataRow dataRow)
@@ -62,323 +45,30 @@ namespace gaseous_server.Classes.Metadata
return Storage.BuildCacheObject<Game>(new Game(), dataRow); return Storage.BuildCacheObject<Game>(new Game(), dataRow);
} }
private static async Task<Game> _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<Game>(returnValue, searchUsing.ToString(), searchValue);
}
return returnValue;
case Storage.CacheStatus.Current:
returnValue = Storage.GetCacheValue<Game>(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<long> gamesToFetch = new List<long>();
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<Game> GetObjectFromServer(string Slug)
{
// get Game metadata
Communications comms = new Communications();
var results = await comms.APIComm<Game>(Communications.MetadataEndpoint.Game, Slug);
var result = results.First();
result = MassageResult(result);
return result;
}
private static async Task<Game> GetObjectFromServer(long Id)
{
// get Game metadata
Communications comms = new Communications();
var results = await comms.APIComm<Game>(Communications.MetadataEndpoint.Game, Id);
var result = results.First();
result = MassageResult(result);
return result;
}
private static Game MassageResult(Game result) private static Game MassageResult(Game result)
{ {
// add artificial unknown platform mapping Game? parentGame = null;
List<long> platformIds = new List<long>();
platformIds.Add(0);
if (result.Platforms != null)
{
if (result.Platforms.Ids != null)
{
platformIds.AddRange(result.Platforms.Ids.ToList());
}
}
result.Platforms = new IdentitiesOrValues<Platform>(
ids: platformIds.ToArray<long>()
);
// get cover art from parent if this has no cover // get cover art from parent if this has no cover
if (result.Cover == null) if (result.Cover == null)
{ {
if (result.ParentGame != 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");
{ parentGame = GetGame(result.MetadataSource, (long)result.ParentGame);
Logging.Log(Logging.LogType.Information, "Game Metadata", "Game has no cover art, fetching cover art from parent game"); result.Cover = parentGame.Cover;
Game parentGame = GetGame((long)result.ParentGame.Id, false, false, false);
result.Cover = parentGame.Cover;
}
} }
} }
// get missing metadata from parent if this is a port // 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.Summary == null)
{ {
if (result.ParentGame != 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");
{ result.Summary = parentGame.Summary;
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;
}
} }
} }
} }
@@ -386,20 +76,6 @@ namespace gaseous_server.Classes.Metadata
return result; 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<string, object> dbDict = new Dictionary<string, object>();
dbDict.Add("Id", (long)gameRow["Id"]);
db.ExecuteCMD(sql, dbDict);
}
}
private static bool AllowNoPlatformSearch = false; private static bool AllowNoPlatformSearch = false;
public static Game[] SearchForGame(string SearchString, long PlatformId, SearchType searchType) public static Game[] SearchForGame(string SearchString, long PlatformId, SearchType searchType)
@@ -515,7 +191,7 @@ namespace gaseous_server.Classes.Metadata
Game[]? results = new Game[0]; Game[]? results = new Game[0];
if (allowSearch == true) if (allowSearch == true)
{ {
results = await comms.APIComm<Game>(IGDBClient.Endpoints.Games, searchFields, searchBody); results = await comms.APIComm<Game>(IGDB.IGDBClient.Endpoints.Games, searchFields, searchBody);
Communications.SetSearchCache<Game[]?>(searchFields, searchBody, results); Communications.SetSearchCache<Game[]?>(searchFields, searchBody, results);
} }
@@ -598,7 +274,7 @@ ORDER BY Platform.`Name`;";
List<AvailablePlatformItem> platforms = new List<AvailablePlatformItem>(); List<AvailablePlatformItem> platforms = new List<AvailablePlatformItem>();
foreach (DataRow row in data.Rows) 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); PlatformMapping.UserEmulatorConfiguration? emulatorConfiguration = platformMapping.GetUserEmulator(UserId, GameId, (long)platform.Id);
if (emulatorConfiguration == null) if (emulatorConfiguration == null)
@@ -688,7 +364,7 @@ ORDER BY Platform.`Name`;";
db.ExecuteCMD(sql, dbDict); 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 PlatformMapping.UserEmulatorConfiguration emulatorConfiguration { get; set; }
public long? LastPlayedRomId { get; set; } public long? LastPlayedRomId { get; set; }
@@ -727,12 +403,12 @@ ORDER BY Platform.`Name`;";
this.FirstReleaseDate = gameObject.FirstReleaseDate; this.FirstReleaseDate = gameObject.FirstReleaseDate;
// compile age ratings // compile age ratings
this.AgeRatings = new List<AgeRating>(); this.AgeRatings = new List<object>();
if (gameObject.AgeRatings != null) 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) if (rating != null)
{ {
this.AgeRatings.Add(rating); this.AgeRatings.Add(rating);
@@ -751,9 +427,9 @@ ORDER BY Platform.`Name`;";
public bool HasSavedGame { get; set; } = false; public bool HasSavedGame { get; set; } = false;
public bool IsFavourite { get; set; } = false; public bool IsFavourite { get; set; } = false;
public DateTimeOffset? FirstReleaseDate { get; set; } public DateTimeOffset? FirstReleaseDate { get; set; }
public IGDB.IdentityOrValue<IGDB.Models.Cover> Cover { get; set; } public object Cover { get; set; }
public IGDB.IdentitiesOrValues<IGDB.Models.Artwork> Artworks { get; set; } public List<object> Artworks { get; set; }
public List<IGDB.Models.AgeRating> AgeRatings { get; set; } public List<object> AgeRatings { get; set; }
} }
} }
} }

View File

@@ -1,11 +1,10 @@
using System; using System;
using IGDB; using HasheousClient.Models.Metadata.IGDB;
using IGDB.Models;
namespace gaseous_server.Classes.Metadata namespace gaseous_server.Classes.Metadata
{ {
public class Genres public class Genres
{ {
public const string fieldList = "fields checksum,created_at,name,slug,updated_at,url;"; 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)) if ((Id == 0) || (Id == null))
{ {
@@ -21,54 +20,10 @@ namespace gaseous_server.Classes.Metadata
} }
else else
{ {
Task<Genre> RetVal = _GetGenres((long)Id); Genre? RetVal = Metadata.GetMetadata<Genre>(SourceType, (long)Id, false);
return RetVal.Result; return RetVal;
} }
} }
}
private static async Task<Genre> _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<Genre>(returnValue, "id", (long)searchValue);
}
break;
case Storage.CacheStatus.Current:
returnValue = Storage.GetCacheValue<Genre>(returnValue, "id", (long)searchValue);
break;
default:
throw new Exception("How did you get here?");
}
return returnValue;
}
private static async Task<Genre> GetObjectFromServer(long searchValue)
{
// get Genres metadata
Communications comms = new Communications();
var results = await comms.APIComm<Genre>(Communications.MetadataEndpoint.Genre, searchValue);
var result = results.First();
return result;
}
}
} }

View File

@@ -1,6 +1,5 @@
using System; using System;
using IGDB; using HasheousClient.Models.Metadata.IGDB;
using IGDB.Models;
namespace gaseous_server.Classes.Metadata namespace gaseous_server.Classes.Metadata
{ {
@@ -20,63 +19,10 @@ namespace gaseous_server.Classes.Metadata
} }
else else
{ {
Task<InvolvedCompany> RetVal = _GetInvolvedCompanies((long)Id); InvolvedCompany? RetVal = Metadata.GetMetadata<InvolvedCompany>(Communications.MetadataSource, (long)Id, false);
return RetVal.Result; return RetVal;
} }
} }
private static async Task<InvolvedCompany> _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<InvolvedCompany>(returnValue, "id", (long)searchValue);
}
break;
case Storage.CacheStatus.Current:
returnValue = Storage.GetCacheValue<InvolvedCompany>(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<InvolvedCompany> GetObjectFromServer(long searchValue)
{
// get Genres metadata
Communications comms = new Communications();
var results = await comms.APIComm<InvolvedCompany>(Communications.MetadataEndpoint.InvolvedCompany, searchValue);
var result = results.First();
return result;
}
} }
} }

View File

@@ -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
/// <summary>
/// Get metadata from the default source
/// </summary>
/// <typeparam name="T">
/// The type of metadata to get
/// </typeparam>
/// <param name="Id">
/// The id of the metadata to get
/// </param>
/// <returns>
/// The metadata object
/// </returns>
/// <exception cref="InvalidMetadataId">
/// Thrown when the id is invalid
/// </exception>
public static T? GetMetadata<T>(long Id, Boolean ForceRefresh = false) where T : class
{
if (Id < 0)
{
throw new InvalidMetadataId(Id);
}
return _GetMetadata<T>(Communications.MetadataSource, Id, ForceRefresh);
}
/// <summary>
/// Get metadata from the specified source
/// </summary>
/// <typeparam name="T">
/// The type of metadata to get
/// </typeparam>
/// <param name="SourceType">
/// The source of the metadata
/// </param>
/// <param name="Id">
/// The id of the metadata to get
/// </param>
/// <returns>
/// The metadata object
/// </returns>
/// <exception cref="InvalidMetadataId">
/// Thrown when the id is invalid
/// </exception>
public static T? GetMetadata<T>(HasheousClient.Models.MetadataModel.MetadataSources SourceType, long Id, Boolean ForceRefresh = false) where T : class
{
if (Id < 0)
{
throw new InvalidMetadataId(SourceType, Id);
}
return _GetMetadata<T>(SourceType, Id, ForceRefresh);
}
private static T? _GetMetadata<T>(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<T>(SourceType, metadata, "Id", Id);
break;
case Storage.CacheStatus.Expired:
metadata = GetMetadataFromServer<T>(SourceType, Id).Result;
Storage.NewCacheValue<T>(SourceType, metadata, true);
break;
case Storage.CacheStatus.NotPresent:
metadata = GetMetadataFromServer<T>(SourceType, Id).Result;
Storage.NewCacheValue<T>(SourceType, metadata, false);
break;
}
return metadata;
}
private static async Task<T> GetMetadataFromServer<T>(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<T>(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<T>();
}
#endregion
}
}

View File

@@ -1,6 +1,5 @@
using System; using System;
using IGDB; using HasheousClient.Models.Metadata.IGDB;
using IGDB.Models;
namespace gaseous_server.Classes.Metadata namespace gaseous_server.Classes.Metadata
@@ -21,54 +20,10 @@ namespace gaseous_server.Classes.Metadata
} }
else else
{ {
Task<MultiplayerMode> RetVal = _GetGame_MultiplayerModes((long)Id); MultiplayerMode? RetVal = Metadata.GetMetadata<MultiplayerMode>(Communications.MetadataSource, (long)Id, false);
return RetVal.Result; return RetVal;
} }
} }
private static async Task<MultiplayerMode> _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<MultiplayerMode>(returnValue, "id", (long)searchValue);
}
break;
case Storage.CacheStatus.Current:
returnValue = Storage.GetCacheValue<MultiplayerMode>(returnValue, "id", (long)searchValue);
break;
default:
throw new Exception("How did you get here?");
}
return returnValue;
}
private static async Task<MultiplayerMode> GetObjectFromServer(long searchValue)
{
// get Game_MultiplayerModes metadata
Communications comms = new Communications();
var results = await comms.APIComm<MultiplayerMode>(Communications.MetadataEndpoint.MultiplayerMode, searchValue);
var result = results.First();
return result;
}
} }
} }

View File

@@ -1,6 +1,5 @@
using System; using System;
using IGDB; using HasheousClient.Models.Metadata.IGDB;
using IGDB.Models;
namespace gaseous_server.Classes.Metadata 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)) if ((Id == 0) || (Id == null))
{ {
@@ -21,77 +20,10 @@ namespace gaseous_server.Classes.Metadata
} }
else else
{ {
Task<PlatformLogo> RetVal = _GetPlatformLogo((long)Id, ImagePath); PlatformLogo? RetVal = Metadata.GetMetadata<PlatformLogo>(Communications.MetadataSource, (long)Id, false);
return RetVal.Result; return RetVal;
} }
} }
private static async Task<PlatformLogo> _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<PlatformLogo>(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<PlatformLogo>(returnValue, "id", (long)searchValue);
}
break;
case Storage.CacheStatus.Current:
returnValue = Storage.GetCacheValue<PlatformLogo>(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<PlatformLogo> GetObjectFromServer(long searchValue, string ImagePath)
{
// get Artwork metadata
Communications comms = new Communications();
var results = await comms.APIComm<PlatformLogo>(Communications.MetadataEndpoint.PlatformLogo, searchValue);
var result = results.First();
return result;
}
} }
} }

View File

@@ -1,7 +1,6 @@
using System; using System;
using System.Data; using System.Data;
using IGDB; using HasheousClient.Models.Metadata.IGDB;
using IGDB.Models;
namespace gaseous_server.Classes.Metadata 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) if (Id == 0)
{ {
@@ -21,79 +20,8 @@ namespace gaseous_server.Classes.Metadata
} }
else else
{ {
Task<PlatformVersion> RetVal = _GetPlatformVersion((long)Id, ParentPlatform, GetImages); PlatformVersion? RetVal = Metadata.GetMetadata<PlatformVersion>(SourceType, Id, false);
return RetVal.Result; return RetVal;
}
}
private static async Task<PlatformVersion> _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<PlatformVersion>(returnValue, "id", (long)searchValue);
}
return returnValue;
case Storage.CacheStatus.Current:
return Storage.GetCacheValue<PlatformVersion>(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<PlatformVersion?> GetObjectFromServer(long searchValue)
{
// get PlatformVersion metadata
Communications comms = new Communications();
var results = await comms.APIComm<PlatformVersion>(Communications.MetadataEndpoint.PlatformVersion, searchValue);
if (results.Length > 0)
{
var result = results.First();
return result;
}
else
{
return null;
} }
} }
} }

View File

@@ -1,8 +1,7 @@
using System; using System;
using System.Data; using System.Data;
using System.Net; using System.Net;
using IGDB; using HasheousClient.Models.Metadata.IGDB;
using IGDB.Models;
namespace gaseous_server.Classes.Metadata 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(); return null;
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<Platform>(returnValue, "id", 0);
}
} }
else else
{ {
try Platform? RetVal = Metadata.GetMetadata<Platform>(Communications.MetadataSource, (long)Id, false);
{ return RetVal;
Task<Platform> 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;
}
} }
} }
public static Platform GetPlatform(string Slug, bool forceRefresh = false, bool GetImages = false) public static Platform GetPlatform(string Slug, bool forceRefresh = false, bool GetImages = false)
{ {
Task<Platform> RetVal = _GetPlatform(SearchUsing.Slug, Slug, forceRefresh, GetImages); throw new NotImplementedException();
return RetVal.Result;
}
private static async Task<Platform> _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<Platform>(returnValue, searchUsing.ToString(), searchValue);
}
case Storage.CacheStatus.Current:
return Storage.GetCacheValue<Platform>(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);
}
}
}
} }
private static void AddPlatformMapping(Platform platform) private static void AddPlatformMapping(Platform platform)
@@ -171,46 +57,6 @@ namespace gaseous_server.Classes.Metadata
Models.PlatformMapping.WritePlatformMap(item, false, true); Models.PlatformMapping.WritePlatformMap(item, false, true);
} }
} }
private enum SearchUsing
{
Id,
Slug
}
private static async Task<Platform> GetObjectFromServer(string Slug)
{
// get platform metadata
Communications comms = new Communications();
var results = await comms.APIComm<Platform>(Communications.MetadataEndpoint.Platform, Slug);
var result = results.First();
return result;
}
private static async Task<Platform> GetObjectFromServer(long Id)
{
// get platform metadata
Communications comms = new Communications();
var results = await comms.APIComm<Platform>(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<string, object> dbDict = new Dictionary<string, object>();
dbDict.Add("Id", (long)platformRow["Id"]);
db.ExecuteCMD(sql, dbDict);
}
}
} }
} }

View File

@@ -1,6 +1,5 @@
using System; using System;
using IGDB; using HasheousClient.Models.Metadata.IGDB;
using IGDB.Models;
namespace gaseous_server.Classes.Metadata 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)) if ((Id == 0) || (Id == null))
{ {
@@ -21,56 +20,10 @@ namespace gaseous_server.Classes.Metadata
} }
else else
{ {
Task<PlayerPerspective> RetVal = _GetGame_PlayerPerspectives((long)Id); PlayerPerspective? RetVal = Metadata.GetMetadata<PlayerPerspective>(SourceType, (long)Id, false);
return RetVal.Result; return RetVal;
} }
} }
private static async Task<PlayerPerspective> _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<PlayerPerspective>(returnValue, "id", (long)searchValue);
}
break;
case Storage.CacheStatus.Current:
returnValue = Storage.GetCacheValue<PlayerPerspective>(returnValue, "id", (long)searchValue);
break;
default:
throw new Exception("How did you get here?");
}
return returnValue;
}
private static async Task<PlayerPerspective> GetObjectFromServer(long searchValue)
{
// get Game_PlayerPerspectives metadata
Communications comms = new Communications();
var results = await comms.APIComm<PlayerPerspective>(Communications.MetadataEndpoint.PlayerPerspective, searchValue);
var result = results.First();
return result;
}
} }
} }

View File

@@ -1,6 +1,5 @@
using System; using System;
using IGDB; using HasheousClient.Models.Metadata.IGDB;
using IGDB.Models;
namespace gaseous_server.Classes.Metadata 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)) if ((Id == 0) || (Id == null))
{ {
@@ -21,54 +20,10 @@ namespace gaseous_server.Classes.Metadata
} }
else else
{ {
Task<ReleaseDate> RetVal = _GetReleaseDates((long)Id); ReleaseDate? RetVal = Metadata.GetMetadata<ReleaseDate>(SourceType, (long)Id, false);
return RetVal.Result; return RetVal;
} }
} }
private static async Task<ReleaseDate> _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<ReleaseDate>(returnValue, "id", (long)searchValue);
}
break;
case Storage.CacheStatus.Current:
returnValue = Storage.GetCacheValue<ReleaseDate>(returnValue, "id", (long)searchValue);
break;
default:
throw new Exception("How did you get here?");
}
return returnValue;
}
private static async Task<ReleaseDate> GetObjectFromServer(long searchValue)
{
// get ReleaseDates metadata
Communications comms = new Communications();
var results = await comms.APIComm<ReleaseDate>(Communications.MetadataEndpoint.ReleaseDate, searchValue);
var result = results.First();
return result;
}
} }
} }

View File

@@ -1,6 +1,5 @@
using System; using System;
using IGDB; using HasheousClient.Models.Metadata.IGDB;
using IGDB.Models;
namespace gaseous_server.Classes.Metadata 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)) if ((Id == 0) || (Id == null))
{ {
@@ -21,75 +20,10 @@ namespace gaseous_server.Classes.Metadata
} }
else else
{ {
Task<Screenshot> RetVal = _GetScreenshot((long)Id, ImagePath, GetImages); Screenshot? RetVal = Metadata.GetMetadata<Screenshot>(SourceType, (long)Id, false);
return RetVal.Result; return RetVal;
} }
} }
private static async Task<Screenshot> _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<Screenshot>(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<Screenshot>(returnValue, "id", (long)searchValue);
}
break;
case Storage.CacheStatus.Current:
returnValue = Storage.GetCacheValue<Screenshot>(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<Screenshot> GetObjectFromServer(long searchValue, string ImagePath)
{
// get Screenshot metadata
Communications comms = new Communications();
var results = await comms.APIComm<Screenshot>(Communications.MetadataEndpoint.Screenshot, searchValue);
var result = results.First();
return result;
}
} }
} }

View File

@@ -9,23 +9,79 @@ namespace gaseous_server.Classes.Metadata
{ {
public class Storage public class Storage
{ {
/// <summary>
/// Cache status of a record
/// </summary>
public enum CacheStatus public enum CacheStatus
{ {
/// <summary>
/// The record is not present in the database
/// </summary>
NotPresent, NotPresent,
/// <summary>
/// The record is present in the database and is current
/// </summary>
Current, Current,
/// <summary>
/// The record is present in the database but is expired
/// </summary>
Expired Expired
} }
public static CacheStatus GetCacheStatus(string Endpoint, string Slug) /// <summary>
/// Get the cache status of a record in the database
/// </summary>
/// <param name="SourceType">
/// The source of the metadata (IGDB, RAWG, etc.)
/// </param>
/// <param name="Endpoint">
/// The endpoint of the metadata (games, companies, etc.)
/// </param>
/// <param name="Slug">
/// The slug of the metadata record
/// </param>
/// <returns>
/// The cache status of the record
/// </returns>
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) /// <summary>
/// Get the cache status of a record in the database
/// </summary>
/// <param name="SourceType">
/// The source of the metadata (IGDB, RAWG, etc.)
/// </param>
/// <param name="Endpoint">
/// The endpoint of the metadata (games, companies, etc.)
/// </param>
/// <param name="Id">
/// The ID of the metadata record
/// </param>
/// <returns>
/// The cache status of the record
/// </returns>
public static CacheStatus GetCacheStatus(HasheousClient.Models.MetadataModel.MetadataSources SourceType, string Endpoint, long Id)
{ {
return _GetCacheStatus(Endpoint, "id", Id); return _GetCacheStatus(SourceType, Endpoint, "id", Id);
} }
/// <summary>
/// Get the cache status of a record in the database
/// </summary>
/// <param name="Row">
/// The DataRow object to check
/// </param>
/// <returns>
/// The cache status of the record
/// </returns>
/// <exception cref="Exception">
/// Thrown when the DataRow object does not contain a "lastUpdated" column
/// </exception>
public static CacheStatus GetCacheStatus(DataRow Row) public static CacheStatus GetCacheStatus(DataRow Row)
{ {
if (Row.Table.Columns.Contains("lastUpdated")) 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); 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<string, object> dbDict = new Dictionary<string, object>(); Dictionary<string, object> dbDict = new Dictionary<string, object>();
dbDict.Add("SourceType", SourceType);
dbDict.Add("Endpoint", Endpoint); dbDict.Add("Endpoint", Endpoint);
dbDict.Add(SearchField, SearchValue); dbDict.Add(SearchField, SearchValue);
@@ -76,16 +133,41 @@ namespace gaseous_server.Classes.Metadata
} }
} }
public static void NewCacheValue(object ObjectToCache, bool UpdateRecord = false) /// <summary>
/// Add a new record to the cache
/// </summary>
/// <param name="SourceType">
/// The source of the metadata (IGDB, RAWG, etc.)
/// </param>
/// <param name="ObjectToCache">
/// The object to cache
/// </param>
/// <param name="UpdateRecord">
/// Whether to update the record if it already exists
/// </param>
public static void NewCacheValue<T>(HasheousClient.Models.MetadataModel.MetadataSources SourceType, T ObjectToCache, bool UpdateRecord = false)
{ {
// get the object type name // get the object type name
string ObjectTypeName = ObjectToCache.GetType().Name; string ObjectTypeName = ObjectToCache.GetType().Name;
// build dictionary // build dictionary
string objectJson = Newtonsoft.Json.JsonConvert.SerializeObject(ObjectToCache); Dictionary<string, object?> objectDict = new Dictionary<string, object?>
Dictionary<string, object?> objectDict = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object?>>(objectJson); {
objectDict.Add("dateAdded", DateTime.UtcNow); { "SourceId", SourceType },
objectDict.Add("lastUpdated", DateTime.UtcNow); { "dateAdded", DateTime.UtcNow },
{ "lastUpdated", DateTime.UtcNow }
};
foreach (PropertyInfo property in ObjectToCache.GetType().GetProperties())
{
if (property.GetCustomAttribute<Models.NoDatabaseAttribute>() == null)
{
object? propertyValue = property.GetValue(ObjectToCache);
if (propertyValue != null)
{
objectDict.Add(property.Name, propertyValue);
}
}
}
// generate sql // generate sql
string fieldList = ""; string fieldList = "";
@@ -135,6 +217,12 @@ namespace gaseous_server.Classes.Metadata
newObjectValue = Newtonsoft.Json.JsonConvert.SerializeObject(newDict["Ids"]); newObjectValue = Newtonsoft.Json.JsonConvert.SerializeObject(newDict["Ids"]);
objectDict[key.Key] = newObjectValue; 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); StoreRelations(ObjectTypeName, key.Key, (long)objectDict["Id"], newObjectValue);
break; break;
@@ -163,15 +251,40 @@ namespace gaseous_server.Classes.Metadata
db.ExecuteCMD(sql, objectDict); db.ExecuteCMD(sql, objectDict);
} }
public static T GetCacheValue<T>(T EndpointType, string SearchField, object SearchValue) /// <summary>
/// Get a record from the cache
/// </summary>
/// <typeparam name="T">
/// The type of the object to return
/// </typeparam>
/// <param name="SourceType">
/// The source of the metadata (IGDB, RAWG, etc.)
/// </param>
/// <param name="EndpointType">
/// The type of the endpoint (games, companies, etc.)
/// </param>
/// <param name="SearchField">
/// The field to search for the record by
/// </param>
/// <param name="SearchValue">
/// The value to search for
/// </param>
/// <returns>
/// The object from the cache
/// </returns>
/// <exception cref="Exception">
/// Thrown when no record is found that matches the search criteria
/// </exception>
public static T GetCacheValue<T>(HasheousClient.Models.MetadataModel.MetadataSources SourceType, T? EndpointType, string SearchField, object SearchValue)
{ {
string Endpoint = EndpointType.GetType().Name; string Endpoint = EndpointType.GetType().Name;
Database db = new Database(Database.databaseType.MySql, Config.DatabaseConfiguration.ConnectionString); 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<string, object> dbDict = new Dictionary<string, object>(); Dictionary<string, object> dbDict = new Dictionary<string, object>();
dbDict.Add("SourceType", SourceType);
dbDict.Add("Endpoint", Endpoint); dbDict.Add("Endpoint", Endpoint);
dbDict.Add(SearchField, SearchValue); dbDict.Add(SearchField, SearchValue);
@@ -192,202 +305,63 @@ namespace gaseous_server.Classes.Metadata
public static T BuildCacheObject<T>(T EndpointType, DataRow dataRow) public static T BuildCacheObject<T>(T EndpointType, DataRow dataRow)
{ {
// copy the DataRow to EndpointType
foreach (PropertyInfo property in EndpointType.GetType().GetProperties()) foreach (PropertyInfo property in EndpointType.GetType().GetProperties())
{ {
if (dataRow.Table.Columns.Contains(property.Name)) if (property.GetCustomAttribute<Models.NoDatabaseAttribute>() == 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]; // check the property type - if it's a list or array, deserialize it. Otherwise, just set the value
string subObjectTypeName = ""; Type objectType = EndpointType.GetType();
object? objectToStore = null; if (objectType != null)
if (objectTypeName == "nullable")
{ {
objectTypeName = property.PropertyType.UnderlyingSystemType.ToString().Split("`1")[1].Replace("[System.", "").Replace("]", "").ToLower(); // fullname = System.Nullable`1[[System.DateTimeOffset,
} string propertyTypeName = property.PropertyType.FullName.Split(",")[0];
try bool isNullable = false;
{ if (propertyTypeName.StartsWith("System.Nullable"))
switch (objectTypeName)
{ {
//case "boolean": isNullable = true;
// Boolean storedBool = Convert.ToBoolean((int)dataRow[property.Name]); propertyTypeName = propertyTypeName.Split("[[")[1];
// property.SetValue(EndpointType, storedBool); }
// break; propertyTypeName = propertyTypeName.Split("`")[0];
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();
switch (subObjectTypeName) switch (propertyTypeName.ToLower())
{ {
case "collection": case "system.collections.generic.list":
objectToStore = new IdentityOrValue<Collection>(id: (long)dataRow[property.Name]); var listArray = Newtonsoft.Json.JsonConvert.DeserializeObject<List<object>>(value.ToString());
break; property.SetValue(EndpointType, listArray);
case "company": break;
objectToStore = new IdentityOrValue<Company>(id: (long)dataRow[property.Name]);
break;
case "cover":
objectToStore = new IdentityOrValue<Cover>(id: (long)dataRow[property.Name]);
break;
case "franchise":
objectToStore = new IdentityOrValue<Franchise>(id: (long)dataRow[property.Name]);
break;
case "game":
objectToStore = new IdentityOrValue<Game>(id: (long)dataRow[property.Name]);
break;
case "platformfamily":
objectToStore = new IdentityOrValue<PlatformFamily>(id: (long)dataRow[property.Name]);
break;
case "platformlogo":
objectToStore = new IdentityOrValue<PlatformLogo>(id: (long)dataRow[property.Name]);
break;
case "platformversioncompany":
objectToStore = new IdentityOrValue<PlatformVersionCompany>(id: (long)dataRow[property.Name]);
break;
}
if (objectToStore != null) case "system.int32[]":
{ var int32array = Newtonsoft.Json.JsonConvert.DeserializeObject<int[]>(value.ToString());
property.SetValue(EndpointType, objectToStore); property.SetValue(EndpointType, int32array);
} break;
case "system.datetimeoffset":
property.SetValue(EndpointType, (DateTimeOffset)(DateTime?)value);
break; break;
case "identitiesorvalues":
subObjectTypeName = property.PropertyType.UnderlyingSystemType.ToString().Split("`1")[1].Replace("[IGDB.Models.", "").Replace("]", "").ToLower();
long[] fromJsonObject = Newtonsoft.Json.JsonConvert.DeserializeObject<long[]>((string)dataRow[property.Name]);
switch (subObjectTypeName)
{
case "agerating":
objectToStore = new IdentitiesOrValues<AgeRating>(ids: fromJsonObject);
break;
case "alternativename":
objectToStore = new IdentitiesOrValues<AlternativeName>(ids: fromJsonObject);
break;
case "artwork":
objectToStore = new IdentitiesOrValues<Artwork>(ids: fromJsonObject);
break;
case "ageratingcontentdescription":
objectToStore = new IdentitiesOrValues<AgeRatingContentDescription>(ids: fromJsonObject);
break;
case "game":
objectToStore = new IdentitiesOrValues<Game>(ids: fromJsonObject);
break;
case "externalgame":
objectToStore = new IdentitiesOrValues<ExternalGame>(ids: fromJsonObject);
break;
case "franchise":
objectToStore = new IdentitiesOrValues<Franchise>(ids: fromJsonObject);
break;
case "gameengine":
objectToStore = new IdentitiesOrValues<GameEngine>(ids: fromJsonObject);
break;
case "gamemode":
objectToStore = new IdentitiesOrValues<GameMode>(ids: fromJsonObject);
break;
case "gamevideo":
objectToStore = new IdentitiesOrValues<GameVideo>(ids: fromJsonObject);
break;
case "genre":
objectToStore = new IdentitiesOrValues<Genre>(ids: fromJsonObject);
break;
case "involvedcompany":
objectToStore = new IdentitiesOrValues<InvolvedCompany>(ids: fromJsonObject);
break;
case "multiplayermode":
objectToStore = new IdentitiesOrValues<MultiplayerMode>(ids: fromJsonObject);
break;
case "platform":
objectToStore = new IdentitiesOrValues<Platform>(ids: fromJsonObject);
break;
case "platformversion":
objectToStore = new IdentitiesOrValues<PlatformVersion>(ids: fromJsonObject);
break;
case "platformwebsite":
objectToStore = new IdentitiesOrValues<PlatformWebsite>(ids: fromJsonObject);
break;
case "platformversioncompany":
objectToStore = new IdentitiesOrValues<PlatformVersionCompany>(ids: fromJsonObject);
break;
case "platformversionreleasedate":
objectToStore = new IdentitiesOrValues<PlatformVersionReleaseDate>(ids: fromJsonObject);
break;
case "playerperspective":
objectToStore = new IdentitiesOrValues<PlayerPerspective>(ids: fromJsonObject);
break;
case "releasedate":
objectToStore = new IdentitiesOrValues<ReleaseDate>(ids: fromJsonObject);
break;
case "screenshot":
objectToStore = new IdentitiesOrValues<Screenshot>(ids: fromJsonObject);
break;
case "theme":
objectToStore = new IdentitiesOrValues<Theme>(ids: fromJsonObject);
break;
case "website":
objectToStore = new IdentitiesOrValues<Website>(ids: fromJsonObject);
break;
}
if (objectToStore != null)
{
property.SetValue(EndpointType, objectToStore);
}
break;
case "int32[]":
Int32[] fromJsonObject_int32Array = Newtonsoft.Json.JsonConvert.DeserializeObject<Int32[]>((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: 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; break;
} }
} }
catch (Exception ex)
{
Console.WriteLine("Error occurred in column " + property.Name);
Console.WriteLine(ex.ToString());
}
} }
} }
} }

View File

@@ -1,6 +1,5 @@
using System; using System;
using IGDB; using HasheousClient.Models.Metadata.IGDB;
using IGDB.Models;
namespace gaseous_server.Classes.Metadata 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)) if ((Id == 0) || (Id == null))
{ {
@@ -21,56 +20,10 @@ namespace gaseous_server.Classes.Metadata
} }
else else
{ {
Task<Theme> RetVal = _GetGame_Themes((long)Id); Theme? RetVal = Metadata.GetMetadata<Theme>(SourceType, (long)Id, false);
return RetVal.Result; return RetVal;
} }
} }
private static async Task<Theme> _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<Theme>(returnValue, "id", (long)searchValue);
}
case Storage.CacheStatus.Current:
returnValue = Storage.GetCacheValue<Theme>(returnValue, "id", (long)searchValue);
break;
default:
throw new Exception("How did you get here?");
}
return returnValue;
}
private static async Task<Theme> GetObjectFromServer(long searchValue)
{
// get Game_Themes metadata
Communications comms = new Communications();
var results = await comms.APIComm<Theme>(Communications.MetadataEndpoint.Theme, searchValue);
var result = results.First();
return result;
}
} }
} }

View File

@@ -1,5 +1,6 @@
using System; using System;
using System.Data; using System.Data;
using gaseous_server.Classes.Metadata;
using gaseous_server.Models; using gaseous_server.Models;
namespace gaseous_server.Classes namespace gaseous_server.Classes
@@ -8,8 +9,8 @@ namespace gaseous_server.Classes
{ {
public void RefreshMetadata(bool forceRefresh = false) public void RefreshMetadata(bool forceRefresh = false)
{ {
Database db = new Database(Database.databaseType.MySql, Config.DatabaseConfiguration.ConnectionString); Database db = new Database(Database.databaseType.MySql, Config.DatabaseConfiguration.ConnectionString);
string sql = ""; string sql = "";
DataTable dt = new DataTable(); DataTable dt = new DataTable();
// disabling forceRefresh // disabling forceRefresh
@@ -27,7 +28,7 @@ namespace gaseous_server.Classes
try try
{ {
Logging.Log(Logging.LogType.Information, "Metadata Refresh", "(" + StatusCounter + "/" + dt.Rows.Count + "): Refreshing metadata for platform " + dr["name"] + " (" + dr["id"] + ")"); 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) catch (Exception ex)
{ {
@@ -59,7 +60,7 @@ namespace gaseous_server.Classes
try try
{ {
Logging.Log(Logging.LogType.Information, "Metadata Refresh", "(" + StatusCounter + "/" + dt.Rows.Count + "): Refreshing metadata for game " + dr["name"] + " (" + dr["id"] + ")"); 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) catch (Exception ex)
{ {
@@ -69,7 +70,7 @@ namespace gaseous_server.Classes
StatusCounter += 1; StatusCounter += 1;
} }
ClearStatus(); ClearStatus();
} }
} }
} }

View File

@@ -2,12 +2,12 @@ using System;
using System.Data; using System.Data;
using gaseous_signature_parser.models.RomSignatureObject; using gaseous_signature_parser.models.RomSignatureObject;
using Microsoft.VisualBasic; using Microsoft.VisualBasic;
using IGDB.Models;
using gaseous_server.Classes.Metadata; using gaseous_server.Classes.Metadata;
using System.IO.Compression; using System.IO.Compression;
using SharpCompress.Archives; using SharpCompress.Archives;
using SharpCompress.Common; using SharpCompress.Common;
using gaseous_server.Models; using gaseous_server.Models;
using HasheousClient.Models.Metadata.IGDB;
namespace gaseous_server.Classes namespace gaseous_server.Classes
{ {
@@ -296,8 +296,8 @@ namespace gaseous_server.Classes
GameRomMediaGroupItem mediaGroupItem = GetMediaGroup(Id); GameRomMediaGroupItem mediaGroupItem = GetMediaGroup(Id);
if (mediaGroupItem.Status == GameRomMediaGroupItem.GroupBuildStatus.WaitingForBuild) if (mediaGroupItem.Status == GameRomMediaGroupItem.GroupBuildStatus.WaitingForBuild)
{ {
Game GameObject = Games.GetGame(mediaGroupItem.GameId, false, false, false); Models.Game GameObject = Games.GetGame(Communications.MetadataSource, mediaGroupItem.GameId);
Platform PlatformObject = Platforms.GetPlatform(mediaGroupItem.PlatformId, false); Platform PlatformObject = Platforms.GetPlatform(mediaGroupItem.PlatformId);
PlatformMapping.PlatformMapItem platformMapItem = PlatformMapping.GetPlatformMap(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); 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 try
{ {
return Platforms.GetPlatform(PlatformId, false).Name; return Platforms.GetPlatform(PlatformId).Name;
} }
catch catch
{ {

View File

@@ -3,7 +3,6 @@ using System.Data;
using gaseous_signature_parser.models.RomSignatureObject; using gaseous_signature_parser.models.RomSignatureObject;
using static gaseous_server.Classes.RomMediaGroup; using static gaseous_server.Classes.RomMediaGroup;
using gaseous_server.Classes.Metadata; using gaseous_server.Classes.Metadata;
using IGDB.Models;
using static HasheousClient.Models.FixMatchModel; using static HasheousClient.Models.FixMatchModel;
using NuGet.Protocol.Core.Types; using NuGet.Protocol.Core.Types;
using static gaseous_server.Classes.FileSignature; using static gaseous_server.Classes.FileSignature;
@@ -154,10 +153,10 @@ namespace gaseous_server.Classes
public static GameRomItem UpdateRom(long RomId, long PlatformId, long GameId) public static GameRomItem UpdateRom(long RomId, long PlatformId, long GameId)
{ {
// ensure metadata for platformid is present // 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 // 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); Database db = new Database(Database.databaseType.MySql, Config.DatabaseConfiguration.ConnectionString);
string sql = "UPDATE Games_Roms SET PlatformId=@platformid, GameId=@gameid WHERE Id = @id"; string sql = "UPDATE Games_Roms SET PlatformId=@platformid, GameId=@gameid WHERE Id = @id";

View File

@@ -1,6 +1,5 @@
using System.Data; using System.Data;
using gaseous_server.Classes.Metadata; using gaseous_server.Classes.Metadata;
using IGDB.Models;
namespace gaseous_server.Classes namespace gaseous_server.Classes
{ {
@@ -62,8 +61,8 @@ namespace gaseous_server.Classes
{ {
NowPlaying = new Models.UserProfile.NowPlayingItem NowPlaying = new Models.UserProfile.NowPlayingItem
{ {
Game = Games.GetGame((long)nowPlayingData.Rows[0]["GameId"], false, false, false), Game = Games.GetGame(Communications.MetadataSource, (long)nowPlayingData.Rows[0]["GameId"]),
Platform = Platforms.GetPlatform((long)nowPlayingData.Rows[0]["PlatformId"], false, false), Platform = Platforms.GetPlatform((long)nowPlayingData.Rows[0]["PlatformId"]),
Duration = Convert.ToInt64(nowPlayingData.Rows[0]["SessionLength"]) Duration = Convert.ToInt64(nowPlayingData.Rows[0]["SessionLength"])
}; };
} }

View File

@@ -10,8 +10,8 @@ using Asp.Versioning;
using Authentication; using Authentication;
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity;
using gaseous_server.Models; using gaseous_server.Models;
using IGDB.Models;
using gaseous_server.Classes.Metadata; using gaseous_server.Classes.Metadata;
using HasheousClient.Models.Metadata.IGDB;
namespace gaseous_server.Controllers namespace gaseous_server.Controllers
{ {

View File

@@ -10,7 +10,6 @@ using Authentication;
using gaseous_server.Classes; using gaseous_server.Classes;
using gaseous_server.Classes.Metadata; using gaseous_server.Classes.Metadata;
using gaseous_server.Models; using gaseous_server.Models;
using IGDB.Models;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity;
@@ -19,6 +18,7 @@ using Microsoft.CodeAnalysis.Scripting;
using static gaseous_server.Classes.Metadata.AgeRatings; using static gaseous_server.Classes.Metadata.AgeRatings;
using Asp.Versioning; using Asp.Versioning;
using static gaseous_server.Models.PlatformMapping; using static gaseous_server.Models.PlatformMapping;
using HasheousClient.Models.Metadata.IGDB;
namespace gaseous_server.Controllers namespace gaseous_server.Controllers
{ {
@@ -43,7 +43,7 @@ namespace gaseous_server.Controllers
[MapToApiVersion("1.0")] [MapToApiVersion("1.0")]
[HttpGet] [HttpGet]
[ProducesResponseType(typeof(List<Game>), StatusCodes.Status200OK)] [ProducesResponseType(typeof(List<gaseous_server.Models.Game>), StatusCodes.Status200OK)]
public async Task<ActionResult> Game( public async Task<ActionResult> Game(
string name = "", string name = "",
string platform = "", 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)); return Ok(GetGames(name, platform, genre, gamemode, playerperspective, theme, minrating, maxrating, "Adult", true, true, sortdescending));
} }
public static List<Game> GetGames( public static List<gaseous_server.Models.Game> GetGames(
string name = "", string name = "",
string platform = "", string platform = "",
string genre = "", string genre = "",
@@ -283,7 +283,7 @@ namespace gaseous_server.Controllers
Database db = new Database(Database.databaseType.MySql, Config.DatabaseConfiguration.ConnectionString); 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; 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<IGDB.Models.Game> RetVal = new List<IGDB.Models.Game>(); List<gaseous_server.Models.Game> RetVal = new List<gaseous_server.Models.Game>();
DataTable dbResponse = db.ExecuteCMD(sql, whereParams); DataTable dbResponse = db.ExecuteCMD(sql, whereParams);
foreach (DataRow dr in dbResponse.Rows) foreach (DataRow dr in dbResponse.Rows)
@@ -299,14 +299,14 @@ namespace gaseous_server.Controllers
[MapToApiVersion("1.1")] [MapToApiVersion("1.1")]
[HttpGet] [HttpGet]
[Route("{GameId}")] [Route("{GameId}")]
[ProducesResponseType(typeof(Game), StatusCodes.Status200OK)] [ProducesResponseType(typeof(gaseous_server.Models.Game), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesResponseType(StatusCodes.Status404NotFound)]
[ResponseCache(CacheProfileName = "5Minute")] [ResponseCache(CacheProfileName = "5Minute")]
public async Task<ActionResult> Game(long GameId) public async Task<ActionResult> Game(long GameId)
{ {
try 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) if (game != null)
{ {
@@ -334,14 +334,14 @@ namespace gaseous_server.Controllers
{ {
try 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<AlternativeName> altNames = new List<AlternativeName>(); List<AlternativeName> altNames = new List<AlternativeName>();
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); return Ok(altNames);
} }
@@ -367,14 +367,14 @@ namespace gaseous_server.Controllers
{ {
try 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.GameAgeRating> ageRatings = new List<AgeRatings.GameAgeRating>(); List<AgeRatings.GameAgeRating> ageRatings = new List<AgeRatings.GameAgeRating>();
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); return Ok(ageRatings);
} }
@@ -400,14 +400,14 @@ namespace gaseous_server.Controllers
{ {
try try
{ {
Game gameObject = Classes.Metadata.Games.GetGame(GameId, false, false, false); gaseous_server.Models.Game game = Classes.Metadata.Games.GetGame(Communications.MetadataSource, GameId);
List<Artwork> artworks = new List<Artwork>(); List<Artwork> artworks = new List<Artwork>();
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); artworks.Add(GameArtwork);
} }
} }
@@ -431,11 +431,11 @@ namespace gaseous_server.Controllers
{ {
try 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 try
{ {
IGDB.Models.Artwork artworkObject = Artworks.GetArtwork(ArtworkId, Config.LibraryConfiguration.LibraryMetadataDirectory_Game(gameObject), false); Artwork artworkObject = Artworks.GetArtwork(game.MetadataSource, ArtworkId);
if (artworkObject != null) if (artworkObject != null)
{ {
return Ok(artworkObject); return Ok(artworkObject);
@@ -467,10 +467,10 @@ namespace gaseous_server.Controllers
{ {
try 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.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) if (coverObject != null)
{ {
return Ok(coverObject); return Ok(coverObject);
@@ -502,7 +502,7 @@ namespace gaseous_server.Controllers
{ {
try 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? imageId = null;
string? imageTypePath = null; string? imageTypePath = null;
@@ -510,14 +510,11 @@ namespace gaseous_server.Controllers
switch (imageType) switch (imageType)
{ {
case MetadataImageType.cover: case MetadataImageType.cover:
if (gameObject.Cover != null) if (game.Cover != null)
{ {
if (gameObject.Cover.Id != null) Cover cover = Classes.Metadata.Covers.GetCover(game.MetadataSource, (long?)game.Cover);
{ imageId = cover.ImageId;
IGDB.Models.Cover cover = Classes.Metadata.Covers.GetCover(gameObject.Cover.Id, Config.LibraryConfiguration.LibraryMetadataDirectory_Game(gameObject), false); imageTypePath = "Covers";
imageId = cover.ImageId;
imageTypePath = "Covers";
}
} }
else else
{ {
@@ -526,11 +523,11 @@ namespace gaseous_server.Controllers
break; break;
case MetadataImageType.screenshots: 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; imageId = imageObject.ImageId;
imageTypePath = "Screenshots"; imageTypePath = "Screenshots";
@@ -543,11 +540,11 @@ namespace gaseous_server.Controllers
break; break;
case MetadataImageType.artwork: 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; imageId = imageObject.ImageId;
imageTypePath = "Artwork"; imageTypePath = "Artwork";
@@ -568,13 +565,13 @@ namespace gaseous_server.Controllers
return NotFound(); return NotFound();
} }
string basePath = Path.Combine(Config.LibraryConfiguration.LibraryMetadataDirectory_Game(gameObject), imageTypePath); string basePath = Path.Combine(Config.LibraryConfiguration.LibraryMetadataDirectory_Game(game), imageTypePath);
string imagePath = Path.Combine(Config.LibraryConfiguration.LibraryMetadataDirectory_Game(gameObject), imageTypePath, size.ToString(), imageId + ".jpg"); string imagePath = Path.Combine(Config.LibraryConfiguration.LibraryMetadataDirectory_Game(game), imageTypePath, size.ToString(), imageId + ".jpg");
if (!System.IO.File.Exists(imagePath)) if (!System.IO.File.Exists(imagePath))
{ {
Communications comms = new Communications(); Communications comms = new Communications();
Task<string> ImgFetch = comms.GetSpecificImageFromServer(Path.Combine(Config.LibraryConfiguration.LibraryMetadataDirectory_Game(gameObject), imageTypePath), imageId, size, new List<Communications.IGDBAPI_ImageSize> { Communications.IGDBAPI_ImageSize.cover_big, Communications.IGDBAPI_ImageSize.original }); Task<string> ImgFetch = comms.GetSpecificImageFromServer(Path.Combine(Config.LibraryConfiguration.LibraryMetadataDirectory_Game(game), imageTypePath), imageId, size, new List<Communications.IGDBAPI_ImageSize> { Communications.IGDBAPI_ImageSize.cover_big, Communications.IGDBAPI_ImageSize.original });
imagePath = ImgFetch.Result; imagePath = ImgFetch.Result;
} }
@@ -640,9 +637,9 @@ namespace gaseous_server.Controllers
{ {
try 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); var user = await _userManager.GetUserAsync(User);
@@ -677,9 +674,9 @@ namespace gaseous_server.Controllers
{ {
try 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); var user = await _userManager.GetUserAsync(User);
@@ -715,15 +712,15 @@ namespace gaseous_server.Controllers
{ {
try 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)
{ {
List<IGDB.Models.GameMode> gameModeObjects = new List<GameMode>(); List<GameMode> gameModeObjects = new List<GameMode>();
if (gameObject.GameModes != null) 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 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)
{ {
List<IGDB.Models.Genre> genreObjects = new List<Genre>(); List<Genre> genreObjects = new List<Genre>();
if (gameObject.Genres != null) 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<IGDB.Models.Genre> sortedGenreObjects = genreObjects.OrderBy(o => o.Name).ToList(); List<Genre> sortedGenreObjects = genreObjects.OrderBy(o => o.Name).ToList();
return Ok(sortedGenreObjects); return Ok(sortedGenreObjects);
} }
@@ -789,16 +786,16 @@ namespace gaseous_server.Controllers
{ {
try 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)
{ {
List<Dictionary<string, object>> icObjects = new List<Dictionary<string, object>>(); List<Dictionary<string, object>> icObjects = new List<Dictionary<string, object>>();
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); 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.Developed = null;
company.Published = null; company.Published = null;
@@ -834,14 +831,14 @@ namespace gaseous_server.Controllers
{ {
try 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)
{ {
List<Dictionary<string, object>> icObjects = new List<Dictionary<string, object>>(); List<Dictionary<string, object>> icObjects = new List<Dictionary<string, object>>();
if (gameObject.InvolvedCompanies != null) if (game.InvolvedCompanies != null)
{ {
InvolvedCompany involvedCompany = Classes.Metadata.InvolvedCompanies.GetInvolvedCompanies(CompanyId); 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.Developed = null;
company.Published = null; company.Published = null;
@@ -877,10 +874,10 @@ namespace gaseous_server.Controllers
{ {
try 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); 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"); string coverFilePath = Path.Combine(Config.LibraryConfiguration.LibraryMetadataDirectory_Company(company), "Logo_Medium.png");
if (System.IO.File.Exists(coverFilePath)) if (System.IO.File.Exists(coverFilePath))
@@ -923,11 +920,11 @@ namespace gaseous_server.Controllers
{ {
try 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) if (platformObject != null)
{ {
@@ -965,11 +962,11 @@ namespace gaseous_server.Controllers
{ {
try 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) if (platformObject != null)
{ {
@@ -1004,11 +1001,11 @@ namespace gaseous_server.Controllers
{ {
try 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) if (platformObject != null)
{ {
@@ -1070,15 +1067,15 @@ namespace gaseous_server.Controllers
{ {
try 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)
{ {
List<ReleaseDate> rdObjects = new List<ReleaseDate>(); List<ReleaseDate> rdObjects = new List<ReleaseDate>();
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); rdObjects.Add(releaseDate);
} }
@@ -1110,7 +1107,7 @@ namespace gaseous_server.Controllers
try 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)); return Ok(Classes.Roms.GetRoms(GameId, PlatformId, NameSearch, pageNumber, pageSize, user.Id));
} }
@@ -1131,7 +1128,7 @@ namespace gaseous_server.Controllers
{ {
try 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); Classes.Roms.GameRomItem rom = Classes.Roms.GetRom(RomId);
if (rom.GameId == GameId) if (rom.GameId == GameId)
@@ -1160,7 +1157,7 @@ namespace gaseous_server.Controllers
{ {
try 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); Classes.Roms.GameRomItem rom = Classes.Roms.GetRom(RomId);
if (rom.GameId == GameId) if (rom.GameId == GameId)
@@ -1190,7 +1187,7 @@ namespace gaseous_server.Controllers
{ {
try 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); Classes.Roms.GameRomItem rom = Classes.Roms.GetRom(RomId);
if (rom.GameId == GameId) if (rom.GameId == GameId)
@@ -1221,7 +1218,7 @@ namespace gaseous_server.Controllers
{ {
ApplicationUser? user = await _userManager.GetUserAsync(User); 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) if (IsMediaGroup == false)
{ {
@@ -1283,7 +1280,7 @@ namespace gaseous_server.Controllers
{ {
try 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); Classes.Roms.GameRomItem rom = Classes.Roms.GetRom(RomId);
if (rom.GameId != GameId) if (rom.GameId != GameId)
@@ -1322,7 +1319,7 @@ namespace gaseous_server.Controllers
{ {
try 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); Classes.Roms.GameRomItem rom = Classes.Roms.GetRom(RomId);
if (rom.GameId != GameId || rom.Name != FileName) if (rom.GameId != GameId || rom.Name != FileName)
@@ -1361,7 +1358,7 @@ namespace gaseous_server.Controllers
try 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); Classes.RomMediaGroup.GameRomMediaGroupItem rom = Classes.RomMediaGroup.GetMediaGroup(RomGroupId, user.Id);
if (rom.GameId == GameId) if (rom.GameId == GameId)
@@ -1391,7 +1388,7 @@ namespace gaseous_server.Controllers
try try
{ {
Game gameObject = Classes.Metadata.Games.GetGame(GameId, false, false, false); gaseous_server.Models.Game game = Classes.Metadata.Games.GetGame(Communications.MetadataSource, GameId);
try try
{ {
@@ -1420,7 +1417,7 @@ namespace gaseous_server.Controllers
{ {
try try
{ {
Game gameObject = Classes.Metadata.Games.GetGame(GameId, false, false, false); gaseous_server.Models.Game game = Classes.Metadata.Games.GetGame(Communications.MetadataSource, GameId);
try try
{ {
@@ -1451,7 +1448,7 @@ namespace gaseous_server.Controllers
try 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); Classes.RomMediaGroup.GameRomMediaGroupItem rom = Classes.RomMediaGroup.GetMediaGroup(RomGroupId, user.Id);
if (rom.GameId == GameId) if (rom.GameId == GameId)
@@ -1481,7 +1478,7 @@ namespace gaseous_server.Controllers
{ {
try 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); Classes.RomMediaGroup.GameRomMediaGroupItem rom = Classes.RomMediaGroup.GetMediaGroup(RomGroupId);
if (rom.GameId == GameId) if (rom.GameId == GameId)
@@ -1514,7 +1511,7 @@ namespace gaseous_server.Controllers
{ {
try 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); Classes.RomMediaGroup.GameRomMediaGroupItem rom = Classes.RomMediaGroup.GetMediaGroup(RomGroupId);
if (rom.GameId != GameId) if (rom.GameId != GameId)
@@ -1529,7 +1526,7 @@ namespace gaseous_server.Controllers
string returnFileName = ""; string returnFileName = "";
if (filename == "") if (filename == "")
{ {
returnFileName = gameObject.Name + ".zip"; returnFileName = game.Name + ".zip";
} }
else else
{ {
@@ -1553,7 +1550,7 @@ namespace gaseous_server.Controllers
[MapToApiVersion("1.1")] [MapToApiVersion("1.1")]
[HttpGet] [HttpGet]
[Route("search")] [Route("search")]
[ProducesResponseType(typeof(List<Game>), StatusCodes.Status200OK)] [ProducesResponseType(typeof(List<gaseous_server.Models.Game>), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult> GameSearch(long RomId = 0, string SearchString = "") public async Task<ActionResult> GameSearch(long RomId = 0, string SearchString = "")
{ {
@@ -1565,7 +1562,7 @@ namespace gaseous_server.Controllers
Common.hashObject hash = new Common.hashObject(romItem.Path); Common.hashObject hash = new Common.hashObject(romItem.Path);
FileSignature fileSignature = new FileSignature(); FileSignature fileSignature = new FileSignature();
gaseous_server.Models.Signatures_Games romSig = fileSignature.GetFileSignature(romItem.Library, hash, new FileInfo(romItem.Path), romItem.Path); gaseous_server.Models.Signatures_Games romSig = fileSignature.GetFileSignature(romItem.Library, hash, new FileInfo(romItem.Path), romItem.Path);
List<Game> searchResults = Classes.ImportGame.SearchForGame_GetAll(romSig.Game.Name, romSig.Flags.IGDBPlatformId); List<gaseous_server.Models.Game> searchResults = Classes.ImportGame.SearchForGame_GetAll(romSig.Game.Name, romSig.Flags.IGDBPlatformId);
return Ok(searchResults); return Ok(searchResults);
} }
@@ -1573,7 +1570,7 @@ namespace gaseous_server.Controllers
{ {
if (SearchString.Length > 0) if (SearchString.Length > 0)
{ {
List<Game> searchResults = Classes.ImportGame.SearchForGame_GetAll(SearchString, 0); List<gaseous_server.Models.Game> searchResults = Classes.ImportGame.SearchForGame_GetAll(SearchString, 0);
return Ok(searchResults); return Ok(searchResults);
} }
@@ -1600,14 +1597,14 @@ namespace gaseous_server.Controllers
{ {
try try
{ {
Game gameObject = Classes.Metadata.Games.GetGame(GameId, false, false, false); gaseous_server.Models.Game game = Classes.Metadata.Games.GetGame(Communications.MetadataSource, GameId);
List<Screenshot> screenshots = new List<Screenshot>(); List<Screenshot> screenshots = new List<Screenshot>();
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); screenshots.Add(GameScreenshot);
} }
} }
@@ -1631,10 +1628,10 @@ namespace gaseous_server.Controllers
{ {
try 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.Screenshot screenshotObject = Screenshots.GetScreenshot(ScreenshotId, Config.LibraryConfiguration.LibraryMetadataDirectory_Game(gameObject), false); Screenshot screenshotObject = Screenshots.GetScreenshot(game.MetadataSource, ScreenshotId);
if (screenshotObject != null) if (screenshotObject != null)
{ {
return Ok(screenshotObject); 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<ActionResult> 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<string> ImgFetch = comms.GetSpecificImageFromServer(basePath, screenshotObject.ImageId, Size, new List<Communications.IGDBAPI_ImageSize> { 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.0")]
[MapToApiVersion("1.1")] [MapToApiVersion("1.1")]
[HttpGet] [HttpGet]
@@ -1717,14 +1663,14 @@ namespace gaseous_server.Controllers
{ {
try try
{ {
Game gameObject = Classes.Metadata.Games.GetGame(GameId, false, false, false); gaseous_server.Models.Game game = Classes.Metadata.Games.GetGame(Communications.MetadataSource, GameId);
List<GameVideo> videos = new List<GameVideo>(); List<GameVideo> videos = new List<GameVideo>();
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); videos.Add(gameVideo);
} }
} }

View File

@@ -8,12 +8,12 @@ using System.Threading.Tasks;
using gaseous_server.Classes; using gaseous_server.Classes;
using gaseous_server.Classes.Metadata; using gaseous_server.Classes.Metadata;
using gaseous_server.Models; using gaseous_server.Models;
using IGDB.Models;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.CodeAnalysis.Scripting; using Microsoft.CodeAnalysis.Scripting;
using Asp.Versioning; using Asp.Versioning;
using HasheousClient.Models.Metadata.IGDB;
namespace gaseous_server.Controllers namespace gaseous_server.Controllers
{ {
@@ -60,7 +60,7 @@ namespace gaseous_server.Controllers
{ {
try try
{ {
IGDB.Models.Platform platformObject = Classes.Metadata.Platforms.GetPlatform(PlatformId); Platform platformObject = Classes.Metadata.Platforms.GetPlatform(PlatformId);
if (platformObject != null) if (platformObject != null)
{ {
@@ -87,10 +87,11 @@ namespace gaseous_server.Controllers
{ {
try try
{ {
IGDB.Models.Platform platformObject = Classes.Metadata.Platforms.GetPlatform(PlatformId); Platform platformObject = Classes.Metadata.Platforms.GetPlatform(PlatformId);
if (platformObject != null) 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) if (logoObject != null)
{ {
return Ok(logoObject); return Ok(logoObject);
@@ -121,21 +122,22 @@ namespace gaseous_server.Controllers
{ {
try try
{ {
IGDB.Models.Platform platformObject = Classes.Metadata.Platforms.GetPlatform(PlatformId); Platform platformObject = Classes.Metadata.Platforms.GetPlatform(PlatformId);
IGDB.Models.PlatformLogo? logoObject = null; PlatformLogo? logoObject = null;
try try
{ {
logoObject = PlatformLogos.GetPlatformLogo(platformObject.PlatformLogo.Id, Config.LibraryConfiguration.LibraryMetadataDirectory_Platform(platformObject));
logoObject = PlatformLogos.GetPlatformLogo((long)platformObject.PlatformLogo);
} }
catch catch
{ {
// getting the logo failed, so we'll try a platform variant if available // getting the logo failed, so we'll try a platform variant if available
if (platformObject.Versions != null) 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); PlatformVersion platformVersion = Classes.Metadata.PlatformVersions.GetPlatformVersion(Communications.MetadataSource, (long)platformObject.Versions[0]);
logoObject = PlatformLogos.GetPlatformLogo(platformVersion.PlatformLogo.Id, Config.LibraryConfiguration.LibraryMetadataDirectory_Platform(platformObject)); logoObject = PlatformLogos.GetPlatformLogo((long)platformVersion.PlatformLogo);
} }
else else
{ {

View File

@@ -8,13 +8,13 @@ using System.Reflection;
using System.Threading.Tasks; using System.Threading.Tasks;
using gaseous_server.Classes; using gaseous_server.Classes;
using gaseous_server.Classes.Metadata; using gaseous_server.Classes.Metadata;
using IGDB.Models;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.CodeAnalysis.Scripting; using Microsoft.CodeAnalysis.Scripting;
using static gaseous_server.Classes.Metadata.AgeRatings; using static gaseous_server.Classes.Metadata.AgeRatings;
using Asp.Versioning; using Asp.Versioning;
using HasheousClient.Models.Metadata.IGDB;
namespace gaseous_server.Controllers namespace gaseous_server.Controllers
{ {
@@ -62,7 +62,7 @@ namespace gaseous_server.Controllers
} }
// get override platform if specified // get override platform if specified
IGDB.Models.Platform? OverridePlatform = null; Platform? OverridePlatform = null;
if (OverridePlatformId != null) if (OverridePlatformId != null)
{ {
OverridePlatform = Platforms.GetPlatform((long)OverridePlatformId); OverridePlatform = Platforms.GetPlatform((long)OverridePlatformId);
@@ -76,10 +76,10 @@ namespace gaseous_server.Controllers
case "rom": case "rom":
if (RetVal["status"] == "imported") 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) if (game.Id == null)
{ {
RetVal["game"] = Games.GetGame(0, false, false, false); RetVal["game"] = Games.GetGame(Communications.MetadataSource, 0);
} }
} }
break; break;

View File

@@ -6,8 +6,7 @@ using System.Threading.Tasks;
using gaseous_server.Classes; using gaseous_server.Classes;
using gaseous_server.Classes.Metadata; using gaseous_server.Classes.Metadata;
using gaseous_server.Models; using gaseous_server.Models;
using IGDB; using HasheousClient.Models.Metadata.IGDB;
using IGDB.Models;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using NuGet.Common; using NuGet.Common;
@@ -44,7 +43,7 @@ namespace gaseous_server.Controllers
List<Platform> platforms = new List<Platform>(); List<Platform> platforms = new List<Platform>();
foreach (DataRow row in data.Rows) 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); platforms.Add(platform);
} }
@@ -56,14 +55,14 @@ namespace gaseous_server.Controllers
[MapToApiVersion("1.1")] [MapToApiVersion("1.1")]
[HttpGet] [HttpGet]
[Route("Game")] [Route("Game")]
[ProducesResponseType(typeof(List<GaseousGame>), StatusCodes.Status200OK)] [ProducesResponseType(typeof(List<gaseous_server.Models.Game>), StatusCodes.Status200OK)]
public async Task<ActionResult> SearchGame(long PlatformId, string SearchString) public async Task<ActionResult> SearchGame(long PlatformId, string SearchString)
{ {
List<GaseousGame> RetVal = await _SearchForGame(PlatformId, SearchString); List<gaseous_server.Models.Game> RetVal = await _SearchForGame(PlatformId, SearchString);
return Ok(RetVal); return Ok(RetVal);
} }
private static async Task<List<GaseousGame>> _SearchForGame(long PlatformId, string SearchString) private static async Task<List<gaseous_server.Models.Game>> _SearchForGame(long PlatformId, string SearchString)
{ {
switch (Communications.MetadataSource) switch (Communications.MetadataSource)
{ {
@@ -74,35 +73,35 @@ namespace gaseous_server.Controllers
searchBody += "where platforms = (" + PlatformId + ");"; searchBody += "where platforms = (" + PlatformId + ");";
searchBody += "limit 100;"; searchBody += "limit 100;";
List<GaseousGame>? searchCache = Communications.GetSearchCache<List<GaseousGame>>(searchFields, searchBody); List<gaseous_server.Models.Game>? searchCache = Communications.GetSearchCache<List<gaseous_server.Models.Game>>(searchFields, searchBody);
if (searchCache == null) if (searchCache == null)
{ {
// cache miss // cache miss
// get Game metadata from data source // get Game metadata from data source
Communications comms = new Communications(); Communications comms = new Communications();
var results = await comms.APIComm<Game>(IGDBClient.Endpoints.Games, searchFields, searchBody); var results = await comms.APIComm<gaseous_server.Models.Game>("Game", searchFields, searchBody);
List<GaseousGame> games = new List<GaseousGame>(); List<gaseous_server.Models.Game> games = new List<gaseous_server.Models.Game>();
foreach (Game game in results.ToList()) 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) switch (cacheStatus)
{ {
case Storage.CacheStatus.NotPresent: case Storage.CacheStatus.NotPresent:
Storage.NewCacheValue(game, false); Storage.NewCacheValue(Communications.MetadataSource, game, false);
break; break;
case Storage.CacheStatus.Expired: case Storage.CacheStatus.Expired:
Storage.NewCacheValue(game, true); Storage.NewCacheValue(Communications.MetadataSource, game, true);
break; break;
} }
games.Add(new GaseousGame(game)); games.Add(game);
} }
Communications.SetSearchCache<List<GaseousGame>>(searchFields, searchBody, games); Communications.SetSearchCache<List<gaseous_server.Models.Game>>(searchFields, searchBody, games);
return games; return games;
} }
@@ -110,11 +109,14 @@ namespace gaseous_server.Controllers
{ {
// get full version of results from database // get full version of results from database
// this is a hacky workaround due to the readonly nature of IGDB.Model.Game IdentityOrValue fields // this is a hacky workaround due to the readonly nature of IGDB.Model.Game IdentityOrValue fields
List<GaseousGame> gamesToReturn = new List<GaseousGame>(); List<gaseous_server.Models.Game> gamesToReturn = new List<gaseous_server.Models.Game>();
foreach (GaseousGame game in searchCache) foreach (gaseous_server.Models.Game game in searchCache)
{ {
Game tempGame = Games.GetGame((long)game.Id, false, false, false); gaseous_server.Models.Game? tempGame = Games.GetGame(Communications.MetadataSource, (long)game.Id);
gamesToReturn.Add(new GaseousGame(tempGame)); if (tempGame != null)
{
gamesToReturn.Add(tempGame);
}
} }
return gamesToReturn; return gamesToReturn;
@@ -123,19 +125,18 @@ namespace gaseous_server.Controllers
case HasheousClient.Models.MetadataModel.MetadataSources.Hasheous: case HasheousClient.Models.MetadataModel.MetadataSources.Hasheous:
HasheousClient.Hasheous hasheous = new HasheousClient.Hasheous(); HasheousClient.Hasheous hasheous = new HasheousClient.Hasheous();
Communications.ConfigureHasheousClient(ref hasheous); Communications.ConfigureHasheousClient(ref hasheous);
List<HasheousClient.Models.Metadata.IGDB.Game> hSearch = hasheous.GetMetadataProxy_SearchGame<HasheousClient.Models.Metadata.IGDB.Game>(HasheousClient.Hasheous.MetadataProvider.IGDB, PlatformId.ToString(), SearchString).ToList<HasheousClient.Models.Metadata.IGDB.Game>(); List<gaseous_server.Models.Game> hSearch = hasheous.GetMetadataProxy_SearchGame<gaseous_server.Models.Game>(HasheousClient.Hasheous.MetadataProvider.IGDB, PlatformId.ToString(), SearchString).ToList<gaseous_server.Models.Game>();
List<GaseousGame> hGamesToReturn = new List<GaseousGame>(); List<gaseous_server.Models.Game> hGamesToReturn = new List<gaseous_server.Models.Game>();
foreach (HasheousClient.Models.Metadata.IGDB.Game game in hSearch) foreach (gaseous_server.Models.Game game in hSearch)
{ {
IGDB.Models.Game tempGame = Communications.ConvertToIGDBModel<IGDB.Models.Game>(game); hGamesToReturn.Add(game);
hGamesToReturn.Add(new GaseousGame(tempGame));
} }
return hGamesToReturn; return hGamesToReturn;
default: default:
return new List<GaseousGame>(); return new List<gaseous_server.Models.Game>();
} }
} }
} }

View File

@@ -9,7 +9,6 @@ using System.Threading.Tasks;
using Authentication; using Authentication;
using gaseous_server.Classes; using gaseous_server.Classes;
using gaseous_server.Classes.Metadata; using gaseous_server.Classes.Metadata;
using IGDB.Models;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity;
@@ -19,6 +18,7 @@ using Microsoft.CodeAnalysis.Scripting;
using static gaseous_server.Classes.Metadata.AgeRatings; using static gaseous_server.Classes.Metadata.AgeRatings;
using Asp.Versioning; using Asp.Versioning;
using Humanizer; using Humanizer;
using HasheousClient.Models.Metadata.IGDB;
namespace gaseous_server.Controllers.v1_1 namespace gaseous_server.Controllers.v1_1
{ {
@@ -117,13 +117,13 @@ namespace gaseous_server.Controllers.v1_1
dbDict.Add("id", GameId); dbDict.Add("id", GameId);
dbDict.Add("agegroupid", (int)user.SecurityProfile.AgeRestrictionPolicy.MaximumAgeRestriction); dbDict.Add("agegroupid", (int)user.SecurityProfile.AgeRestrictionPolicy.MaximumAgeRestriction);
List<IGDB.Models.Game> RetVal = new List<IGDB.Models.Game>(); List<Models.Game> RetVal = new List<Models.Game>();
DataTable dbResponse = db.ExecuteCMD(sql, dbDict); DataTable dbResponse = db.ExecuteCMD(sql, dbDict);
foreach (DataRow dr in dbResponse.Rows) 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); GameReturnPackage gameReturn = new GameReturnPackage(RetVal.Count, RetVal);
@@ -571,7 +571,7 @@ FROM
} }
} }
Game retGame = Storage.BuildCacheObject<Game>(new Game(), dbResponse.Rows[i]); Models.Game retGame = Storage.BuildCacheObject<Models.Game>(new Models.Game(), dbResponse.Rows[i]);
Games.MinimalGameItem retMinGame = new Games.MinimalGameItem(retGame); Games.MinimalGameItem retMinGame = new Games.MinimalGameItem(retGame);
retMinGame.Index = i; retMinGame.Index = i;
if (dbResponse.Rows[i]["RomSaveCount"] != DBNull.Value || dbResponse.Rows[i]["MediaGroupSaveCount"] != DBNull.Value) if (dbResponse.Rows[i]["RomSaveCount"] != DBNull.Value || dbResponse.Rows[i]["MediaGroupSaveCount"] != DBNull.Value)
@@ -654,12 +654,12 @@ FROM
} }
public GameReturnPackage(int Count, List<Game> Games) public GameReturnPackage(int Count, List<Models.Game> Games)
{ {
this.Count = Count; this.Count = Count;
List<Games.MinimalGameItem> minimalGames = new List<Games.MinimalGameItem>(); List<Games.MinimalGameItem> minimalGames = new List<Games.MinimalGameItem>();
foreach (Game game in Games) foreach (Models.Game game in Games)
{ {
minimalGames.Add(new Classes.Metadata.Games.MinimalGameItem(game)); minimalGames.Add(new Classes.Metadata.Games.MinimalGameItem(game));
} }

View File

@@ -270,7 +270,7 @@ namespace gaseous_server.Controllers.v1_1
else else
{ {
RomMediaGroup.GameRomMediaGroupItem mediaGroupItem = RomMediaGroup.GetMediaGroup(RomId); 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")); Classes.Common.hashObject hashObject = new Classes.Common.hashObject(Path.Combine(Config.LibraryConfiguration.LibraryMediaGroupDirectory, mediaGroupItem.Id.ToString() + ".zip"));
romName = game.Name; romName = game.Name;
romMd5 = hashObject.md5hash; romMd5 = hashObject.md5hash;

View File

@@ -5,50 +5,19 @@ using Swashbuckle.AspNetCore.SwaggerGen;
namespace gaseous_server.Models namespace gaseous_server.Models
{ {
public class GaseousGame : IGDB.Models.Game public class Game : HasheousClient.Models.Metadata.IGDB.Game
{ {
public GaseousGame() [NoDatabase]
{ public bool IsFavourite { get; set; } = false;
}
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 HasSavedGame { get; set; } = false; public bool HasSavedGame { get; set; } = false;
public IGDB.Models.Cover? CoverItem [NoDatabase]
{ public HasheousClient.Models.MetadataModel.MetadataSources MetadataSource { get; set; }
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
};
}
}
return null; internal class NoDatabaseAttribute : Attribute
} {
}
} }
} }

View File

@@ -8,7 +8,7 @@ using System.Web;
using gaseous_server.Classes; using gaseous_server.Classes;
using gaseous_server.Classes.Metadata; using gaseous_server.Classes.Metadata;
using gaseous_server.Controllers; using gaseous_server.Controllers;
using IGDB.Models; using HasheousClient.Models.Metadata.IGDB;
using Newtonsoft.Json; using Newtonsoft.Json;
namespace gaseous_server.Models 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, Id = mapItem.IGDBId,
Name = mapItem.IGDBName, Name = mapItem.IGDBName,
@@ -102,9 +102,9 @@ namespace gaseous_server.Models
AlternativeName = mapItem.AlternateNames.FirstOrDefault() 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; return platform;
@@ -310,15 +310,14 @@ namespace gaseous_server.Models
string sql = ""; string sql = "";
// get platform data // get platform data
// IGDB.Models.Platform? platform = Platforms.GetPlatform(IGDBId, false); Platform? platform = null;
IGDB.Models.Platform? platform = null; if (Storage.GetCacheStatus(Communications.MetadataSource, "Platform", IGDBId) == Storage.CacheStatus.NotPresent)
if (Storage.GetCacheStatus("Platform", IGDBId) == Storage.CacheStatus.NotPresent)
{ {
//platform = Platforms.GetPlatform(IGDBId, false); //platform = Platforms.GetPlatform(IGDBId, false);
} }
else else
{ {
platform = (IGDB.Models.Platform)Storage.GetCacheValue<IGDB.Models.Platform>(new Platform(), "id", IGDBId); platform = (Platform)Storage.GetCacheValue<Platform>(Communications.MetadataSource, new Platform(), "id", IGDBId);
} }
if (platform != null) if (platform != null)

View File

@@ -1,5 +1,3 @@
using IGDB.Models;
namespace gaseous_server.Models namespace gaseous_server.Models
{ {
public class UserProfile public class UserProfile
@@ -11,7 +9,7 @@ namespace gaseous_server.Models
public class NowPlayingItem public class NowPlayingItem
{ {
public Game Game { get; set; } 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 long Duration { get; set; }
} }
public ProfileImageItem? Avatar { get; set; } public ProfileImageItem? Avatar { get; set; }

View File

@@ -329,12 +329,6 @@ app.Use(async (context, next) =>
// setup library directories // setup library directories
Config.LibraryConfiguration.InitLibrary(); 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 // extract platform map if not present
PlatformMapping.ExtractPlatformMap(); PlatformMapping.ExtractPlatformMap();

View File

@@ -99,9 +99,157 @@ SELECT *, DATE_ADD(
FROM UserTimeTracking; FROM UserTimeTracking;
CREATE INDEX idx_game_name ON Game (`Name`); CREATE INDEX idx_game_name ON Game (`Name`);
CREATE INDEX idx_game_totalratingcount ON Game (TotalRatingCount); CREATE INDEX idx_game_totalratingcount ON Game (TotalRatingCount);
CREATE INDEX idx_alternativename_game ON AlternativeName (Game); CREATE INDEX idx_alternativename_game ON AlternativeName (Game);
CREATE INDEX idx_gamestate_romid ON GameState (RomId); CREATE INDEX idx_gamestate_romid ON GameState (RomId);
CREATE INDEX idx_gamestate_ismediagroup_userid ON GameState (IsMediaGroup, UserId); CREATE INDEX idx_gamestate_ismediagroup_userid ON GameState (IsMediaGroup, UserId);
CREATE INDEX idx_rommediagroup_gameid ON RomMediaGroup (GameId); CREATE INDEX idx_rommediagroup_gameid ON RomMediaGroup (GameId);
CREATE INDEX idx_favourites_userid_gameid ON Favourites (UserId, GameId); 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`);