Added support for retrieving game achievements

This commit is contained in:
UrbanCMC 2022-01-28 15:50:40 +01:00 committed by Jeddunk
parent 71021ee767
commit 9545f83833
4 changed files with 147 additions and 2 deletions

View File

@ -208,6 +208,7 @@ namespace GoldbergGUI.Core.Services
{ {
_log.Info("Reading configuration..."); _log.Info("Reading configuration...");
var appId = -1; var appId = -1;
var achievementList = new List<Achievement>();
var dlcList = new List<DlcApp>(); var dlcList = new List<DlcApp>();
var steamAppidTxt = Path.Combine(path, "steam_appid.txt"); var steamAppidTxt = Path.Combine(path, "steam_appid.txt");
if (File.Exists(steamAppidTxt)) if (File.Exists(steamAppidTxt))
@ -221,6 +222,19 @@ namespace GoldbergGUI.Core.Services
_log.Info(@"""steam_appid.txt"" missing! Skipping..."); _log.Info(@"""steam_appid.txt"" missing! Skipping...");
} }
var achievementJson = Path.Combine(path, "steam_settings", "achievements.json");
if (File.Exists(achievementJson))
{
_log.Info("Getting achievements...");
var json = await File.ReadAllTextAsync(achievementJson)
.ConfigureAwait(false);
achievementList = System.Text.Json.JsonSerializer.Deserialize<List<Achievement>>(json);
}
else
{
_log.Info(@"""steam_settings/achievements.json"" missing! Skipping...");
}
var dlcTxt = Path.Combine(path, "steam_settings", "DLC.txt"); var dlcTxt = Path.Combine(path, "steam_settings", "DLC.txt");
var appPathTxt = Path.Combine(path, "steam_settings", "app_paths.txt"); var appPathTxt = Path.Combine(path, "steam_settings", "app_paths.txt");
if (File.Exists(dlcTxt)) if (File.Exists(dlcTxt))
@ -263,6 +277,7 @@ namespace GoldbergGUI.Core.Services
return new GoldbergConfiguration return new GoldbergConfiguration
{ {
AppId = appId, AppId = appId,
Achievements = achievementList,
DlcList = dlcList, DlcList = dlcList,
Offline = File.Exists(Path.Combine(path, "steam_settings", "offline.txt")), Offline = File.Exists(Path.Combine(path, "steam_settings", "offline.txt")),
DisableNetworking = File.Exists(Path.Combine(path, "steam_settings", "disable_networking.txt")), DisableNetworking = File.Exists(Path.Combine(path, "steam_settings", "disable_networking.txt")),
@ -303,6 +318,53 @@ namespace GoldbergGUI.Core.Services
await File.WriteAllTextAsync(Path.Combine(path, "steam_appid.txt"), c.AppId.ToString()) await File.WriteAllTextAsync(Path.Combine(path, "steam_appid.txt"), c.AppId.ToString())
.ConfigureAwait(false); .ConfigureAwait(false);
// Achievements + Images
if (c.Achievements.Count > 0)
{
_log.Info("Downloading images...");
var imagePath = Path.Combine(path, "steam_settings", "images");
Directory.CreateDirectory(imagePath);
foreach (var achievement in c.Achievements)
{
await DownloadImageAsync(imagePath, achievement.Icon);
await DownloadImageAsync(imagePath, achievement.IconGray);
// Update achievement list to point to local images instead
achievement.Icon = $"images/{Path.GetFileName(achievement.Icon)}";
achievement.IconGray = $"images/{Path.GetFileName(achievement.IconGray)}";
}
_log.Info("Saving achievements...");
var achievementJson = System.Text.Json.JsonSerializer.Serialize(
c.Achievements,
new System.Text.Json.JsonSerializerOptions
{
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
WriteIndented = true
});
await File.WriteAllTextAsync(Path.Combine(path, "steam_settings", "achievements.json"), achievementJson)
.ConfigureAwait(false);
_log.Info("Finished saving achievements.");
}
else
{
_log.Info("No achievements set! Removing achievement files...");
var imagePath = Path.Combine(path, "steam_settings", "images");
if (Directory.Exists(imagePath))
{
Directory.Delete(imagePath);
}
var achievementPath = Path.Combine(path, "steam_settings", "achievements");
if (File.Exists(achievementPath))
{
File.Delete(achievementPath);
}
_log.Info("Removed achievement files.");
}
// DLC + App path // DLC + App path
if (c.DlcList.Count > 0) if (c.DlcList.Count > 0)
{ {
@ -621,5 +683,22 @@ namespace GoldbergGUI.Core.Services
return success; return success;
} }
private async Task DownloadImageAsync(string imageFolder, string imageUrl)
{
var fileName = Path.GetFileName(imageUrl);
var targetPath = Path.Combine(imageFolder, fileName);
if (File.Exists(targetPath))
{
return;
}
else if (imageUrl.StartsWith("images/"))
{
_log.Warn($"Previously downloaded image '{imageUrl}' is now missing!");
}
var wc = new System.Net.WebClient();
await wc.DownloadFileTaskAsync(new Uri(imageUrl, UriKind.Absolute), targetPath);
}
} }
} }

View File

@ -23,6 +23,7 @@ namespace GoldbergGUI.Core.Services
public Task<IEnumerable<SteamApp>> GetListOfAppsByName(string name); public Task<IEnumerable<SteamApp>> GetListOfAppsByName(string name);
public Task<SteamApp> GetAppByName(string name); public Task<SteamApp> GetAppByName(string name);
public Task<SteamApp> GetAppById(int appid); public Task<SteamApp> GetAppById(int appid);
public Task<List<Achievement>> GetListOfAchievements(SteamApp steamApp);
public Task<List<DlcApp>> GetListOfDlc(SteamApp steamApp, bool useSteamDb); public Task<List<DlcApp>> GetListOfDlc(SteamApp steamApp, bool useSteamDb);
} }
@ -81,6 +82,7 @@ namespace GoldbergGUI.Core.Services
private const string AppTypeGame = "game"; private const string AppTypeGame = "game";
private const string AppTypeDlc = "dlc"; private const string AppTypeDlc = "dlc";
private const string Database = "steamapps.cache"; private const string Database = "steamapps.cache";
private const string GameSchemaUrl = "https://api.steampowered.com/ISteamUserStats/GetSchemaForGame/v2/";
private IMvxLog _log; private IMvxLog _log;
@ -168,6 +170,32 @@ namespace GoldbergGUI.Core.Services
return app; return app;
} }
public async Task<List<Achievement>> GetListOfAchievements(SteamApp steamApp)
{
var achievementList = new List<Achievement>();
if (steamApp == null)
{
return achievementList;
}
_log.Info($"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);
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) public async Task<List<DlcApp>> GetListOfDlc(SteamApp steamApp, bool useSteamDb)
{ {
var dlcList = new List<DlcApp>(); var dlcList = new List<DlcApp>();

View File

@ -30,6 +30,7 @@ namespace GoldbergGUI.Core.ViewModels
private int _appId; private int _appId;
//private SteamApp _currentGame; //private SteamApp _currentGame;
private List<Achievement> achievements;
private ObservableCollection<DlcApp> _dlcs; private ObservableCollection<DlcApp> _dlcs;
private string _accountName; private string _accountName;
private long _steamId; private long _steamId;
@ -368,6 +369,32 @@ namespace GoldbergGUI.Core.ViewModels
if (steamApp != null) GameName = steamApp.Name; if (steamApp != null) GameName = steamApp.Name;
} }
public IMvxCommand GetListOfAchievementsCommand => new MvxAsyncCommand(GetListOfAchievements);
private async Task GetListOfAchievements()
{
if (AppId <= 0)
{
_log.Error("Invalid Steam App!");
return;
}
MainWindowEnabled = false;
StatusText = "Trying to get list of achievements...";
achievements = await _steam.GetListOfAchievements(new SteamApp { AppId = AppId, Name = GameName });
MainWindowEnabled = true;
if (achievements.Count > 0)
{
var empty = achievements.Count == 1 ? "" : "s";
StatusText = $"Successfully got {achievements.Count} achievement{empty}! Ready.";
}
else
{
StatusText = "No achievements found! Ready.";
}
}
public IMvxCommand GetListOfDlcCommand => new MvxAsyncCommand(GetListOfDlc); public IMvxCommand GetListOfDlcCommand => new MvxAsyncCommand(GetListOfDlc);
private async Task GetListOfDlc() private async Task GetListOfDlc()
@ -416,6 +443,7 @@ namespace GoldbergGUI.Core.ViewModels
await _goldberg.Save(dirPath, new GoldbergConfiguration await _goldberg.Save(dirPath, new GoldbergConfiguration
{ {
AppId = AppId, AppId = AppId,
Achievements = achievements.ToList(),
DlcList = DLCs.ToList(), DlcList = DLCs.ToList(),
Offline = Offline, Offline = Offline,
DisableNetworking = DisableNetworking, DisableNetworking = DisableNetworking,
@ -526,6 +554,7 @@ namespace GoldbergGUI.Core.ViewModels
DllPath = "Path to game's steam_api(64).dll..."; DllPath = "Path to game's steam_api(64).dll...";
GameName = "Game name..."; GameName = "Game name...";
AppId = -1; AppId = -1;
achievements = new List<Achievement>();
DLCs = new ObservableCollection<DlcApp>(); DLCs = new ObservableCollection<DlcApp>();
AccountName = "Account name..."; AccountName = "Account name...";
SteamId = -1; SteamId = -1;
@ -546,6 +575,7 @@ namespace GoldbergGUI.Core.ViewModels
private void SetFormFromConfig(GoldbergConfiguration config) private void SetFormFromConfig(GoldbergConfiguration config)
{ {
AppId = config.AppId; AppId = config.AppId;
achievements = new List<Achievement>(config.Achievements);
DLCs = new ObservableCollection<DlcApp>(config.DlcList); DLCs = new ObservableCollection<DlcApp>(config.DlcList);
Offline = config.Offline; Offline = config.Offline;
DisableNetworking = config.DisableNetworking; DisableNetworking = config.DisableNetworking;

View File

@ -61,8 +61,16 @@
<DataGridTextColumn Header="App Path" Binding="{Binding AppPath}" Width="*" Visibility="{Binding Source={x:Reference ShowOptionalDlcSettings}, Path=IsChecked, Converter={StaticResource B2V}}" /> <DataGridTextColumn Header="App Path" Binding="{Binding AppPath}" Width="*" Visibility="{Binding Source={x:Reference ShowOptionalDlcSettings}, Path=IsChecked, Converter={StaticResource B2V}}" />
</DataGrid.Columns> </DataGrid.Columns>
</DataGrid> </DataGrid>
<CheckBox Grid.Row="1" x:Name="ShowOptionalDlcSettings" Margin="0,5,0,0" Content="Show optional settings"/> <Grid Grid.Row="1">
<Button Content="Get _DLCs for AppID" Command="{Binding GetListOfDlcCommand}" Grid.Row="1" Width="120" HorizontalAlignment="Right" Margin="0,5,0,0" Height="20"/> <Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<CheckBox Grid.Column="1" x:Name="ShowOptionalDlcSettings" Margin="0,5,0,0" Content="Show optional settings"/>
<Button Grid.Column="1" Content="Get _Achievements for AppID" Command="{Binding GetListOfAchievementsCommand}" Margin="0,5,20,0" Width="200" HorizontalAlignment="Right" />
<Button Grid.Column="2" Content="Get _DLCs for AppID" Command="{Binding GetListOfDlcCommand}" Width="120" HorizontalAlignment="Right" Margin="0,5,0,0" Height="20"/>
</Grid>
</Grid> </Grid>
</GroupBox> </GroupBox>
</Grid> </Grid>