GoldbergGUI/GoldbergGUI.Core/Services/SteamService.cs

304 lines
13 KiB
C#
Raw Normal View History

2021-01-08 12:36:57 -05:00
using AngleSharp.Dom;
using AngleSharp.Html.Parser;
using GoldbergGUI.Core.Models;
using GoldbergGUI.Core.Utils;
2022-05-12 15:40:28 -04:00
using Microsoft.Extensions.Logging;
2021-03-21 08:01:32 -04:00
using NinjaNye.SearchExtensions;
2021-03-21 10:20:46 -04:00
using SQLite;
2021-01-08 12:36:57 -05:00
using SteamStorefrontAPI;
2021-12-22 07:15:28 -05:00
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
2021-01-08 12:36:57 -05:00
namespace GoldbergGUI.Core.Services
{
// gets info from steam api
public interface ISteamService
{
2022-05-12 15:40:28 -04:00
public Task Initialize(ILogger<ISteamService> log);
public Task<IEnumerable<SteamApp>> GetListOfAppsByName(string name);
public Task<SteamApp> GetAppByName(string name);
public Task<SteamApp> GetAppById(int appid);
public Task<List<Achievement>> GetListOfAchievements(SteamApp steamApp);
public Task<List<DlcApp>> GetListOfDlc(SteamApp steamApp, bool useSteamDb);
2021-01-08 12:36:57 -05:00
}
2021-01-13 14:29:12 -05:00
class SteamCache
{
public string SteamUri { get; }
public Type ApiVersion { get; }
2021-03-21 10:20:46 -04:00
public string SteamAppType { get; }
2021-01-13 14:29:12 -05:00
2021-03-21 10:20:46 -04:00
public SteamCache(string uri, Type apiVersion, string steamAppType)
2021-01-13 14:29:12 -05:00
{
SteamUri = uri;
ApiVersion = apiVersion;
SteamAppType = steamAppType;
}
}
2021-01-08 12:36:57 -05:00
// ReSharper disable once UnusedType.Global
// ReSharper disable once ClassNeverInstantiated.Global
2021-03-21 08:01:32 -04:00
public class SteamService : ISteamService
2021-01-08 12:36:57 -05:00
{
// ReSharper disable StringLiteralTypo
2021-03-21 10:20:46 -04:00
private readonly Dictionary<string, SteamCache> _caches =
new Dictionary<string, SteamCache>
{
2021-01-13 14:29:12 -05:00
{
2021-03-21 10:20:46 -04:00
AppTypeGame,
2021-01-13 14:29:12 -05:00
new SteamCache(
"https://api.steampowered.com/IStoreService/GetAppList/v1/" +
"?max_results=50000" +
"&include_games=1" +
"&key=" + Secrets.SteamWebApiKey(),
typeof(SteamAppsV1),
2021-03-21 10:20:46 -04:00
AppTypeGame
2021-01-13 14:29:12 -05:00
)
},
{
2021-03-21 10:20:46 -04:00
AppTypeDlc,
2021-01-13 14:29:12 -05:00
new SteamCache(
"https://api.steampowered.com/IStoreService/GetAppList/v1/" +
"?max_results=50000" +
"&include_games=0" +
"&include_dlc=1" +
"&key=" + Secrets.SteamWebApiKey(),
typeof(SteamAppsV1),
2021-03-21 10:20:46 -04:00
AppTypeDlc
2021-01-13 14:29:12 -05:00
)
}
};
private static readonly Secrets Secrets = new Secrets();
2021-01-08 12:36:57 -05:00
private const string UserAgent =
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) " +
"Chrome/87.0.4280.88 Safari/537.36";
2021-03-21 10:20:46 -04:00
private const string AppTypeGame = "game";
private const string AppTypeDlc = "dlc";
2021-03-21 11:15:17 -04:00
private const string Database = "steamapps.cache";
private const string GameSchemaUrl = "https://api.steampowered.com/ISteamUserStats/GetSchemaForGame/v2/";
2021-03-21 10:20:46 -04:00
2022-05-12 15:40:28 -04:00
private ILogger<ISteamService> _log;
private SQLiteAsyncConnection _db;
2021-03-21 10:20:46 -04:00
2022-05-12 15:40:28 -04:00
public async Task Initialize(ILogger<ISteamService> log)
2021-01-08 12:36:57 -05:00
{
2021-01-13 14:29:12 -05:00
static SteamApps DeserializeSteamApps(Type type, string cacheString)
{
2021-03-21 10:20:46 -04:00
return type == typeof(SteamAppsV2)
2021-12-22 07:15:28 -05:00
? (SteamApps)JsonSerializer.Deserialize<SteamAppsV2>(cacheString)
2021-03-21 10:20:46 -04:00
: JsonSerializer.Deserialize<SteamAppsV1>(cacheString);
}
2021-03-21 10:20:46 -04:00
_log = log;
_db = new SQLiteAsyncConnection(Database);
//_db.CreateTable<SteamApp>();
await _db.CreateTableAsync<SteamApp>()
2022-05-12 15:40:28 -04:00
//.ContinueWith(x => _log.LogDebug("Table success!"))
.ConfigureAwait(false);
var countAsync = await _db.Table<SteamApp>().CountAsync().ConfigureAwait(false);
if (DateTime.Now.Subtract(File.GetLastWriteTimeUtc(Database)).TotalDays >= 1 || countAsync == 0)
{
2021-03-21 10:20:46 -04:00
foreach (var (appType, steamCache) in _caches)
{
2022-05-12 15:40:28 -04:00
_log.LogInformation($"Updating cache ({appType})...");
2021-03-21 10:20:46 -04:00
bool haveMoreResults;
long lastAppId = 0;
var client = new HttpClient();
var cacheRaw = new HashSet<SteamApp>();
do
{
var response = lastAppId > 0
? await client.GetAsync($"{steamCache.SteamUri}&last_appid={lastAppId}")
.ConfigureAwait(false)
: await client.GetAsync(steamCache.SteamUri).ConfigureAwait(false);
var responseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
var steamApps = DeserializeSteamApps(steamCache.ApiVersion, responseBody);
foreach (var appListApp in steamApps.AppList.Apps) cacheRaw.Add(appListApp);
haveMoreResults = steamApps.AppList.HaveMoreResults;
lastAppId = steamApps.AppList.LastAppid;
} while (haveMoreResults);
2021-01-13 14:29:12 -05:00
var cache = new HashSet<SteamApp>();
foreach (var steamApp in cacheRaw)
{
2021-08-29 16:42:33 -04:00
steamApp.AppType = steamCache.SteamAppType;
2021-03-21 11:15:17 -04:00
steamApp.ComparableName = PrepareStringToCompare(steamApp.Name);
2021-01-13 14:29:12 -05:00
cache.Add(steamApp);
}
2021-01-13 14:29:12 -05:00
await _db.InsertAllAsync(cache, "OR IGNORE").ConfigureAwait(false);
}
}
}
public async Task<IEnumerable<SteamApp>> GetListOfAppsByName(string name)
2021-01-08 12:36:57 -05:00
{
var query = await _db.Table<SteamApp>()
2021-08-29 16:42:33 -04:00
.Where(x => x.AppType == AppTypeGame).ToListAsync().ConfigureAwait(false);
var listOfAppsByName = query.Search(x => x.Name)
2021-01-08 12:36:57 -05:00
.SetCulture(StringComparison.OrdinalIgnoreCase)
.ContainingAll(name.Split(' '));
return listOfAppsByName;
2021-01-08 12:36:57 -05:00
}
public async Task<SteamApp> GetAppByName(string name)
2021-01-08 12:36:57 -05:00
{
2022-05-12 15:40:28 -04:00
_log.LogInformation($"Trying to get app {name}");
2021-03-21 11:15:17 -04:00
var comparableName = PrepareStringToCompare(name);
var app = await _db.Table<SteamApp>()
2021-08-29 16:42:33 -04:00
.FirstOrDefaultAsync(x => x.AppType == AppTypeGame && x.ComparableName.Equals(comparableName))
.ConfigureAwait(false);
2022-05-12 15:40:28 -04:00
if (app != null) _log.LogInformation($"Successfully got app {app}");
2021-01-08 12:36:57 -05:00
return app;
}
public async Task<SteamApp> GetAppById(int appid)
2021-01-08 12:36:57 -05:00
{
2022-05-12 15:40:28 -04:00
_log.LogInformation($"Trying to get app with ID {appid}");
2021-08-29 16:42:33 -04:00
var app = await _db.Table<SteamApp>().Where(x => x.AppType == AppTypeGame)
.FirstOrDefaultAsync(x => x.AppId.Equals(appid)).ConfigureAwait(false);
2022-05-12 15:40:28 -04:00
if (app != null) _log.LogInformation($"Successfully got app {app}");
2021-01-08 12:36:57 -05:00
return app;
}
public async Task<List<Achievement>> GetListOfAchievements(SteamApp steamApp)
{
var achievementList = new List<Achievement>();
if (steamApp == null)
{
return achievementList;
}
2022-05-12 15:40:28 -04:00
_log.LogInformation($"Getting achievements for App {steamApp}");
var client = new HttpClient();
client.DefaultRequestHeaders.UserAgent.ParseAdd(UserAgent);
var apiUrl = $"{GameSchemaUrl}?key={Secrets.SteamWebApiKey()}&appid={steamApp.AppId}&l=en";
var response = await client.GetAsync(apiUrl).ConfigureAwait(false);
var responseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
var jsonResponse = JsonDocument.Parse(responseBody);
var achievementData = jsonResponse.RootElement.GetProperty("game")
.GetProperty("availableGameStats")
.GetProperty("achievements");
achievementList = JsonSerializer.Deserialize<List<Achievement>>(achievementData.GetRawText());
return achievementList;
}
public async Task<List<DlcApp>> GetListOfDlc(SteamApp steamApp, bool useSteamDb)
2021-01-08 12:36:57 -05:00
{
var dlcList = new List<DlcApp>();
2021-01-08 12:36:57 -05:00
if (steamApp != null)
{
2022-05-12 15:40:28 -04:00
_log.LogInformation($"Get DLC for App {steamApp}");
2021-01-08 12:36:57 -05:00
var task = AppDetails.GetAsync(steamApp.AppId);
var steamAppDetails = await task.ConfigureAwait(true);
2021-03-21 10:20:46 -04:00
if (steamAppDetails.Type == AppTypeGame)
2021-01-08 12:36:57 -05:00
{
steamAppDetails.DLC.ForEach(async x =>
2021-01-08 12:36:57 -05:00
{
2021-08-29 16:42:33 -04:00
var result = await _db.Table<SteamApp>().Where(z => z.AppType == AppTypeDlc)
.FirstOrDefaultAsync(y => y.AppId.Equals(x)).ConfigureAwait(true)
2021-08-29 16:42:33 -04:00
?? new SteamApp() { AppId = x, Name = $"Unknown DLC {x}", ComparableName = $"unknownDlc{x}", AppType = AppTypeDlc };
dlcList.Add(new DlcApp(result));
2022-05-12 15:40:28 -04:00
_log.LogDebug($"{result.AppId}={result.Name}");
2021-01-08 12:36:57 -05:00
});
2022-05-12 15:40:28 -04:00
_log.LogInformation("Got DLC successfully...");
2021-01-08 12:36:57 -05:00
// Get DLC from SteamDB
// Get Cloudflare cookie (not implemented)
2021-01-08 12:36:57 -05:00
// Scrape and parse HTML page
// Add missing to DLC list
2021-03-21 10:20:46 -04:00
2021-04-07 07:52:56 -04:00
// Return current list if we don't intend to use SteamDB
if (!useSteamDb) return dlcList;
2021-12-22 07:15:28 -05:00
2021-04-07 07:52:56 -04:00
try
2021-01-08 12:36:57 -05:00
{
var steamDbUri = new Uri($"https://steamdb.info/app/{steamApp.AppId}/dlc/");
var client = new HttpClient();
client.DefaultRequestHeaders.UserAgent.ParseAdd(UserAgent);
2022-05-12 15:40:28 -04:00
_log.LogInformation($"Get SteamDB App {steamApp}");
2021-01-08 12:36:57 -05:00
var httpCall = client.GetAsync(steamDbUri);
var response = await httpCall.ConfigureAwait(false);
2022-05-12 15:40:28 -04:00
_log.LogDebug(httpCall.Status.ToString());
_log.LogDebug(response.EnsureSuccessStatusCode().ToString());
2021-01-08 12:36:57 -05:00
var readAsStringAsync = response.Content.ReadAsStringAsync();
var responseBody = await readAsStringAsync.ConfigureAwait(false);
2022-05-12 15:40:28 -04:00
_log.LogDebug(readAsStringAsync.Status.ToString());
2021-01-08 12:36:57 -05:00
var parser = new HtmlParser();
var doc = parser.ParseDocument(responseBody);
var query1 = doc.QuerySelector("#dlc");
if (query1 != null)
{
2022-05-12 15:40:28 -04:00
_log.LogInformation("Got list of DLC from SteamDB.");
2021-01-08 12:36:57 -05:00
var query2 = query1.QuerySelectorAll(".app");
foreach (var element in query2)
{
var dlcId = element.GetAttribute("data-appid");
var query3 = element.QuerySelectorAll("td");
2021-01-13 14:29:12 -05:00
var dlcName = query3 != null
? query3[1].Text().Replace("\n", "").Trim()
: $"Unknown DLC {dlcId}";
2021-12-22 07:15:28 -05:00
var dlcApp = new DlcApp { AppId = Convert.ToInt32(dlcId), Name = dlcName };
2021-01-08 12:36:57 -05:00
var i = dlcList.FindIndex(x => x.AppId.Equals(dlcApp.AppId));
if (i > -1)
{
if (dlcList[i].Name.Contains("Unknown DLC")) dlcList[i] = dlcApp;
2021-01-08 12:36:57 -05:00
}
else
{
dlcList.Add(dlcApp);
2021-01-08 12:36:57 -05:00
}
}
2022-05-12 15:40:28 -04:00
dlcList.ForEach(x => _log.LogDebug($"{x.AppId}={x.Name}"));
_log.LogInformation("Got DLC from SteamDB successfully...");
2021-01-08 12:36:57 -05:00
}
else
{
2022-05-12 15:40:28 -04:00
_log.LogError("Could not get DLC from SteamDB!");
2021-01-08 12:36:57 -05:00
}
}
2021-04-07 07:52:56 -04:00
catch (Exception e)
{
2022-05-12 15:40:28 -04:00
_log.LogError("Could not get DLC from SteamDB! Skipping...");
_log.LogError(e.ToString());
2021-04-07 07:52:56 -04:00
}
2021-01-08 12:36:57 -05:00
}
else
{
2022-05-12 15:40:28 -04:00
_log.LogError("Could not get DLC: Steam App is not of type \"game\"");
2021-01-08 12:36:57 -05:00
}
}
else
{
2022-05-12 15:40:28 -04:00
_log.LogError("Could not get DLC: Invalid Steam App");
2021-01-08 12:36:57 -05:00
}
return dlcList;
}
2021-03-21 11:15:17 -04:00
private static string PrepareStringToCompare(string name)
{
return Regex.Replace(name, Misc.AlphaNumOnlyRegex, "").ToLower();
}
2021-01-08 12:36:57 -05:00
}
}