GoldbergGUI/GoldbergGUI.Core/Services/SteamService.cs

259 lines
10 KiB
C#
Raw Normal View History

2021-01-08 12:36:57 -05:00
using System;
using System.Collections.Generic;
using System.IO;
2021-03-21 08:01:32 -04:00
using System.Linq;
2021-01-08 12:36:57 -05:00
using System.Net.Http;
2021-03-21 08:01:32 -04:00
using System.Text.Json;
using System.Text.RegularExpressions;
2021-01-08 12:36:57 -05:00
using System.Threading.Tasks;
using AngleSharp.Dom;
using AngleSharp.Html.Parser;
using GoldbergGUI.Core.Models;
using GoldbergGUI.Core.Utils;
using MvvmCross.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;
namespace GoldbergGUI.Core.Services
{
// gets info from steam api
public interface ISteamService
{
public Task Initialize(IMvxLog log);
public IEnumerable<SteamApp> GetListOfAppsByName(string name);
public SteamApp GetAppByName(string name);
public SteamApp GetAppById(int appid);
public Task<List<SteamApp>> GetListOfDlc(SteamApp steamApp, bool useSteamDb);
}
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";
private const string Database = "steamapps.db";
2021-01-08 12:36:57 -05:00
private IMvxLog _log;
2021-03-21 10:20:46 -04:00
private SQLiteConnection _db;
2021-01-08 12:36:57 -05:00
public async Task Initialize(IMvxLog log)
{
//var (path, uri, jsonType, appType) = _caches[0];
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)
? (SteamApps) JsonSerializer.Deserialize<SteamAppsV2>(cacheString)
: JsonSerializer.Deserialize<SteamAppsV1>(cacheString);
}
2021-03-21 10:20:46 -04:00
_log = log;
_db = new SQLiteConnection(Database);
_db.CreateTable<SteamApp>();
if (DateTime.Now.Subtract(File.GetLastWriteTimeUtc(Database)).TotalDays >= 1 || !_db.Table<SteamApp>().Any())
{
2021-03-21 10:20:46 -04:00
foreach (var (appType, steamCache) in _caches)
{
2021-03-21 10:20:46 -04:00
_log.Info($"Updating cache ({appType})...");
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-03-21 10:20:46 -04:00
steamApp.type = steamCache.SteamAppType;
2021-01-13 14:29:12 -05:00
cache.Add(steamApp);
}
2021-01-13 14:29:12 -05:00
2021-03-21 10:20:46 -04:00
_db.InsertAll(cache);
}
}
}
2021-01-08 12:36:57 -05:00
public IEnumerable<SteamApp> GetListOfAppsByName(string name)
{
2021-03-21 10:20:46 -04:00
var listOfAppsByName = _db.Table<SteamApp>()
.Where(x => x.type == AppTypeGame).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 SteamApp GetAppByName(string name)
{
_log.Info($"Trying to get app {name}");
var comparableName = Regex.Replace(name, Misc.AlphaNumOnlyRegex, "").ToLower();
2021-03-21 10:20:46 -04:00
var app = _db.Table<SteamApp>().Where(x => x.type == AppTypeGame)
.FirstOrDefault(x => x.ComparableName.Equals(comparableName));
2021-01-08 12:36:57 -05:00
if (app != null) _log.Info($"Successfully got app {app}");
return app;
}
public SteamApp GetAppById(int appid)
{
_log.Info($"Trying to get app with ID {appid}");
2021-03-21 10:20:46 -04:00
var app = _db.Table<SteamApp>().Where(x => x.type == AppTypeGame)
.FirstOrDefault(x => x.AppId.Equals(appid));
2021-01-08 12:36:57 -05:00
if (app != null) _log.Info($"Successfully got app {app}");
return app;
}
public async Task<List<SteamApp>> GetListOfDlc(SteamApp steamApp, bool useSteamDb)
{
_log.Info("Get DLC");
var dlcList = new List<SteamApp>();
if (steamApp != null)
{
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(x =>
{
2021-03-21 10:20:46 -04:00
var result = _db.Table<SteamApp>().Where(z => z.type == AppTypeDlc)
.FirstOrDefault(y => y.AppId.Equals(x))
2021-01-13 14:29:12 -05:00
?? new SteamApp {AppId = x, Name = $"Unknown DLC {x}"};
2021-01-08 12:36:57 -05:00
dlcList.Add(result);
});
dlcList.ForEach(x => _log.Debug($"{x.AppId}={x.Name}"));
_log.Info("Got DLC successfully...");
// Get DLC from SteamDB
// Get Cloudflare cookie
// Scrape and parse HTML page
// Add missing to DLC list
2021-03-21 10:20:46 -04:00
2021-01-13 14:29:12 -05:00
// ReSharper disable once InvertIf
2021-01-08 12:36:57 -05:00
if (useSteamDb)
{
var steamDbUri = new Uri($"https://steamdb.info/app/{steamApp.AppId}/dlc/");
var client = new HttpClient();
client.DefaultRequestHeaders.UserAgent.ParseAdd(UserAgent);
_log.Info("Get SteamDB App");
var httpCall = client.GetAsync(steamDbUri);
var response = await httpCall.ConfigureAwait(false);
_log.Debug(httpCall.Status.ToString());
_log.Debug(response.EnsureSuccessStatusCode().ToString());
var readAsStringAsync = response.Content.ReadAsStringAsync();
var responseBody = await readAsStringAsync.ConfigureAwait(false);
_log.Debug(readAsStringAsync.Status.ToString());
var parser = new HtmlParser();
var doc = parser.ParseDocument(responseBody);
var query1 = doc.QuerySelector("#dlc");
if (query1 != null)
{
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-01-08 12:36:57 -05:00
var dlcApp = new SteamApp {AppId = Convert.ToInt32(dlcId), Name = dlcName};
var i = dlcList.FindIndex(x => x.AppId.Equals(dlcApp.AppId));
if (i > -1)
{
if (dlcList[i].Name.Contains("Unknown DLC")) dlcList[i] = dlcApp;
}
else
{
dlcList.Add(dlcApp);
}
}
dlcList.ForEach(x => _log.Debug($"{x.AppId}={x.Name}"));
_log.Info("Got DLC from SteamDB successfully...");
}
else
{
_log.Error("Could not get DLC from SteamDB!");
}
}
}
else
{
_log.Error("Could not get DLC: Steam App is not of type \"game\"");
}
}
else
{
_log.Error("Could not get DLC: Invalid Steam App");
}
return dlcList;
}
}
}