-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
SteamApi.cs
1073 lines (931 loc) · 41.1 KB
/
SteamApi.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using CommonPluginsShared;
using CommonPluginsShared.Extensions;
using CommonPluginsStores.Models;
using CommonPluginsStores.Steam.Models;
using Microsoft.Win32;
using Playnite.SDK;
using Playnite.SDK.Data;
using SteamKit2;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Text;
using CommonPlayniteShared;
using static CommonPluginsShared.PlayniteTools;
using AngleSharp.Dom.Html;
using AngleSharp.Parser.Html;
using AngleSharp.Dom;
using CommonPlayniteShared.Common;
using System.Security.Principal;
using System.Threading.Tasks;
using CommonPluginsShared.Converters;
using System.Globalization;
using System.Windows.Media;
using System.Text.RegularExpressions;
using CommonPlayniteShared.PluginLibrary.SteamLibrary.SteamShared;
using System.Net;
namespace CommonPluginsStores.Steam
{
public class SteamApi : StoreApi
{
#region Url
private string SteamDbDlc => "https://steamdb.info/app/{0}/dlc/";
private static string UrlSteamCommunity { get; } = @"https://steamcommunity.com";
private static string UrlApi { get; } = @"https://api.steampowered.com";
private static string UrlStore { get; } = @"https://store.steampowered.com";
private static string UrlProfileById { get; } = UrlSteamCommunity + @"/profiles/{0}";
private static string UrlProfileByName { get; } = UrlSteamCommunity + @"/id/{0}";
private static string UrlUserData { get; } = UrlStore + @"/dynamicstore/userdata/";
private static string UrlApiAppsList { get; } = UrlApi + @"/ISteamApps/GetAppList/v2/";
private static string UrlApiFriendList { get; } = UrlApi + @"/ISteamUser/GetFriendList/v1/?key={0}&steamid={1}";
private static string UrlApiUser { get; } = UrlApi + @"/ISteamUser/GetPlayerSummaries/v2/?key={0}&steamids={1}";
private static string UrlGetPlayerAchievements { get; } = UrlApi + @"/ISteamUserStats/GetPlayerAchievements/v1/?appid={0}&language={1}&key={2}&steamid={3}";
private static string UrlGetGameAchievements { get; } = UrlApi + @"/IPlayerService/GetGameAchievements/v1/?format=json&appid={0}&language={1}";
private static string UrlApiGameDetails { get; } = UrlStore + @"/api/appdetails?appids={0}&l={1}";
private static string UrlSteamGame => UrlApi + @"/app/{0}/?l={1}";
private static string UrlAchievementImg => @"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/apps/{0}/{1}";
#endregion
protected List<App> _AppsList;
internal List<App> AppsList
{
get
{
if (_AppsList == null)
{
// From cache if exists & not expired
if (File.Exists(AppsListPath) && File.GetLastWriteTime(AppsListPath).AddDays(3) > DateTime.Now)
{
Common.LogDebug(true, "GetSteamAppListFromCache");
AppsList = Serialization.FromJsonFile<List<App>>(AppsListPath);
}
// From web
else
{
Common.LogDebug(true, "GetSteamAppsListFromWeb");
AppsList = GetSteamAppsListFromWeb();
}
}
return _AppsList;
}
set => _AppsList = value;
}
private Models.SteamUser _CurrentUser;
public Models.SteamUser CurrentUser
{
get
{
if (_CurrentUser == null)
{
_CurrentUser = GetCurrentUser();
}
return _CurrentUser;
}
set => SetValue(ref _CurrentUser, value);
}
private SteamUserData _UserData = null;
public SteamUserData UserData
{
get
{
if (_UserData == null)
{
try
{
_UserData = LoadUserData(true);
if (_UserData == null)
{
using (IWebView WebViewOffscreen = API.Instance.WebViews.CreateOffscreenView())
{
WebViewOffscreen.NavigateAndWait(UrlUserData);
WebViewOffscreen.NavigateAndWait(UrlUserData);
string data = WebViewOffscreen.GetPageText();
Serialization.TryFromJson(data, out _UserData);
if (_UserData?.rgOwnedApps?.Count > 0)
{
SaveUserData(_UserData);
}
else
{
SteamUserData loadedData = LoadUserData();
_UserData = loadedData ?? _UserData;
}
}
}
}
catch (Exception ex)
{
Common.LogError(ex, false, $"Steam", true, PluginName);
}
}
return _UserData;
}
}
#region Paths
private string AppsListPath { get; set; }
private string FileUserData { get; set; }
public string KeyPath { get; set; }
private string _InstallationPath;
public string InstallationPath
{
get
{
if (_InstallationPath == null)
{
_InstallationPath = GetInstallationPath();
}
return _InstallationPath;
}
set => SetValue(ref _InstallationPath, value);
}
public string LoginUsersPath => Path.Combine(InstallationPath, "config", "loginusers.vdf");
public string SteamLibraryConfigFile => Path.Combine(PlaynitePaths.ExtensionsDataPath, CommonPluginsShared.PlayniteTools.GetPluginId(ExternalPlugin.SteamLibrary).ToString(), "config.json");
#endregion
public SteamApi(string PluginName) : base(PluginName, ExternalPlugin.SteamLibrary, "Steam")
{
AppsListPath = Path.Combine(PathStoresData, "Steam_AppsList.json");
AppsListPath = Path.Combine(PathStoresData, "SteamUserData.json");
KeyPath = Path.Combine(PathStoresData, "Steam.dat");
}
#region Configuration
protected override bool GetIsUserLoggedIn()
{
bool withId = IsProfilePublic(string.Format(UrlProfileById, CurrentUser.SteamId), GetStoredCookies()).GetAwaiter().GetResult();
bool withPersona = IsProfilePublic(string.Format(UrlProfileByName, CurrentUser.PersonaName), GetStoredCookies()).GetAwaiter().GetResult();
return withId || withPersona;
}
public override void Login()
{
ResetIsUserLoggedIn();
string steamId = string.Empty;
using (var view = API.Instance.WebViews.CreateView(675, 440, Colors.Black))
{
view.LoadingChanged += async (s, e) =>
{
string address = view.GetCurrentAddress();
if (address.Contains(@"steamcommunity.com"))
{
string source = await view.GetPageSourceAsync();
Match idMatch = Regex.Match(source, @"g_steamID = ""(\d+)""");
if (idMatch.Success)
{
steamId = idMatch.Groups[1].Value;
}
else
{
idMatch = Regex.Match(source, @"steamid"":""(\d+)""");
if (idMatch.Success)
{
steamId = idMatch.Groups[1].Value;
}
}
if (idMatch.Success)
{
SetStoredCookies(GetWebCookies());
view.Close();
}
}
};
view.DeleteDomainCookies(".steamcommunity.com");
view.DeleteDomainCookies("steamcommunity.com");
view.DeleteDomainCookies("steampowered.com");
view.DeleteDomainCookies("store.steampowered.com");
view.DeleteDomainCookies("help.steampowered.com");
view.DeleteDomainCookies("login.steampowered.com");
view.Navigate(@"https://steamcommunity.com/login/home/?goto=");
view.OpenDialog();
}
}
public override void Save()
{
if (CurrentUser != null)
{
SaveKeys(CurrentUser.ApiKey);
}
}
#endregion
#region Current user
protected override AccountInfos GetCurrentAccountInfos()
{
if (!IsUserLoggedIn)
{
return null;
}
try
{
string Url = string.Format(UrlApiUser, CurrentUser.ApiKey, CurrentUser.SteamId);
string WebData = Web.DownloadStringData(Url).GetAwaiter().GetResult();
if (Serialization.TryFromJson(WebData, out PlayerSummaries playerSummaries))
{
Player player = playerSummaries.response.players[0];
AccountInfos userInfos = new AccountInfos
{
UserId = long.Parse(player.steamid),
Avatar = player.avatarfull,
Pseudo = player.personaname,
Link = player.profileurl,
IsCurrent = true
};
return userInfos;
}
}
catch (Exception ex)
{
Common.LogError(ex, false, true, PluginName);
}
return null;
}
protected override ObservableCollection<AccountInfos> GetCurrentFriendsInfos()
{
try
{
//List<HttpHeader> httpHeaders = new List<HttpHeader>
//{
// new HttpHeader { Key = "AuthToken", Value = AuthToken.Token },
// new HttpHeader { Key = "X-Api-Version", Value = "2" },
// new HttpHeader { Key = "X-Application-Key", Value = "Origin" }
//};
//string Url = string.Format(UrlUserFriends, CurrentAccountInfos.UserId);
//string WebData = Web.DownloadStringData(Url, httpHeaders).GetAwaiter().GetResult();
//Serialization.TryFromJson(WebData, out FriendsResponse friendsResponse);
//
//ObservableCollection<AccountInfos> accountsInfos = new ObservableCollection<AccountInfos>();
//friendsResponse?.entries.ForEach(x =>
//{
// long UserId = x.userId;
// long ClientId = x.personaId;
// string Avatar = GetAvatar(UserId);
// string Pseudo = x.displayName;
// string Link = string.Format(UrlUserProfile, GetEncoded(UserId));
// DateTime? DateAdded = x.dateTime;
//
// AccountInfos userInfos = new AccountInfos
// {
// ClientId = ClientId,
// UserId = UserId,
// Avatar = Avatar,
// Pseudo = Pseudo,
// Link = Link
// };
// accountsInfos.Add(userInfos);
//});
//
//return accountsInfos;
}
catch (Exception ex)
{
Common.LogError(ex, false, true, PluginName);
}
return null;
}
#endregion
#region User details
public override ObservableCollection<AccountGameInfos> GetAccountGamesInfos(AccountInfos accountInfos)
{
try
{
//List<HttpHeader> httpHeaders = new List<HttpHeader>
//{
// new HttpHeader { Key = "AuthToken", Value = AuthToken.Token },
// new HttpHeader { Key = "Accept", Value = "application/json" }
//};
//string Url = string.Format(UrlApi3UserGames, CurrentAccountInfos.UserId, accountInfos.UserId);
//string WebData = Web.DownloadStringData(Url, httpHeaders).GetAwaiter().GetResult();
//Serialization.TryFromJson(WebData, out ProductInfosResponse productInfosResponse);
//
//ObservableCollection<AccountGameInfos> accountGamesInfos = new ObservableCollection<AccountGameInfos>();
//productInfosResponse?.productInfos?.ForEach(x =>
//{
// string Id = x.productId;
// string Name = x.displayProductName;
//
// bool IsCommun = false;
// if (!accountInfos.IsCurrent)
// {
// IsCommun = CurrentGamesInfos?.Where(y => y.Id.IsEqual(Id))?.Count() != 0;
// }
//
// GameInfos gameInfos = GetGameInfos(Id, Local);
// string Link = gameInfos?.Link;
//
// string achId = x?.softwares?.softwareList?.First().achievementSetOverride;
// ObservableCollection<GameAchievement> Achievements = null;
// if (!achId.IsNullOrEmpty())
// {
// Achievements = GetAchievements(achId, accountInfos);
// }
//
// AccountGameInfos accountGameInfos = new AccountGameInfos
// {
// Id = Id,
// Name = Name,
// Link = Link,
// IsCommun = IsCommun,
// Achievements = Achievements,
// HoursPlayed = 0
// };
// accountGamesInfos.Add(accountGameInfos);
//});
//
//return accountGamesInfos;
}
catch (Exception ex)
{
// Error 403 when no data
Common.LogError(ex, false, true, PluginName);
}
return null;
}
public override ObservableCollection<GameAchievement> GetAchievements(string Id, AccountInfos accountInfos)
{
try
{
if (Id == "0")
{
return new ObservableCollection<GameAchievement>();
}
string WebData = Web.DownloadStringData(string.Format(UrlGetGameAchievements, Id, CodeLang.GetSteamLang(Local))).GetAwaiter().GetResult();
ObservableCollection<GameAchievement> gameAchievements = new ObservableCollection<GameAchievement>();
if (Serialization.TryFromJson(WebData, out SteamAchievements steamAchievements))
{
if (steamAchievements?.response?.achievements == null)
{
return gameAchievements;
}
foreach (Achievement achievements in steamAchievements.response.achievements)
{
GameAchievement gameAchievement = new GameAchievement
{
Id = achievements.internal_name,
Name = achievements.localized_name,
Description = achievements.localized_desc,
UrlUnlocked = achievements.icon.IsNullOrEmpty() ? string.Empty : string.Format(UrlAchievementImg, Id, achievements.icon),
UrlLocked = achievements.icon_gray.IsNullOrEmpty() ? string.Empty : string.Format(UrlAchievementImg, Id, achievements.icon_gray),
DateUnlocked = default,
Percent = float.Parse(achievements.player_percent_unlocked.Replace(".", CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator)),
IsHidden = achievements.hidden
};
gameAchievements.Add(gameAchievement);
}
}
if (gameAchievements?.Count() == 0)
{
return gameAchievements;
}
if (accountInfos != null && accountInfos.IsCurrent)
{
if (CurrentUser.IsPrivateAccount || CurrentUser.ApiKey.IsNullOrEmpty())
{
gameAchievements = GetAchievementsByWeb(Id, gameAchievements);
}
else
{
using (dynamic steamWebAPI = WebAPI.GetInterface("ISteamUserStats", CurrentUser.ApiKey))
{
KeyValue PlayerAchievements = steamWebAPI.GetPlayerAchievements(steamid: CurrentUser.SteamId, appid: Id, l: CodeLang.GetSteamLang(Local));
if (PlayerAchievements != null && PlayerAchievements.Children != null)
{
KeyValue PlayerAchievementsData = PlayerAchievements.Children.Find(x => x.Name == "achievements");
if (PlayerAchievementsData != null)
{
foreach (KeyValue AchievementsData in PlayerAchievementsData.Children)
{
string ApiName = AchievementsData.Children.Find(x => x.Name == "apiname").Value;
string Name = AchievementsData.Children.Find(x => x.Name == "name").Value;
string Description = AchievementsData.Children.Find(x => x.Name == "description").Value;
bool achieved = int.Parse(AchievementsData.Children.Find(x => x.Name == "achieved").Value) == 1;
int.TryParse(AchievementsData.Children.Find(x => x.Name == "unlocktime").Value, out int unlocktime);
DateTime DateUnlocked = achieved ? new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(unlocktime).ToLocalTime() : default;
gameAchievements.Where(x => x.Id.IsEqual(ApiName)).FirstOrDefault().DateUnlocked = DateUnlocked;
}
}
}
}
}
}
return gameAchievements;
}
catch (Exception ex)
{
// Error 403 when no data
Common.LogError(ex, false, true, PluginName);
}
return null;
}
private ObservableCollection<GameAchievement> GetAchievementsByWeb(string Id, ObservableCollection<GameAchievement> gameAchievement)
{
string UrlById = string.Format(UrlProfileById, CurrentUser.SteamId) + $"/stats/{Id}/achievements?l=english";
string UrlByPersona = string.Format(UrlProfileByName, CurrentUser.PersonaName) + $"/stats/{Id}?l=english";
try
{
List<HttpCookie> cookies = GetStoredCookies();
string Url = UrlById;
string ResultWeb = Web.DownloadStringData(Url, cookies, string.Empty, true).GetAwaiter().GetResult();
if (ResultWeb.IndexOf("achieveRow") == -1)
{
Url = UrlByPersona;
ResultWeb = Web.DownloadStringData(UrlByPersona, cookies, string.Empty, true).GetAwaiter().GetResult();
}
if (ResultWeb.IndexOf("achieveRow") > -1)
{
IHtmlDocument htmlDocument = new HtmlParser().Parse(ResultWeb);
foreach (IElement el in htmlDocument.QuerySelectorAll(".achieveRow"))
{
string UrlUnlocked = el.QuerySelector(".achieveImgHolder img")?.GetAttribute("src") ?? string.Empty;
string Name = el.QuerySelector(".achieveTxtHolder h3").InnerHtml;
string Description = el.QuerySelector(".achieveTxtHolder h5").InnerHtml;
DateTime DateUnlocked = default;
string stringDateUnlocked = el.QuerySelector(".achieveUnlockTime")?.InnerHtml ?? string.Empty;
if (!stringDateUnlocked.IsNullOrEmpty())
{
stringDateUnlocked = stringDateUnlocked.Replace("Unlocked", string.Empty).Replace("<br>", string.Empty).Trim();
DateTime.TryParseExact(stringDateUnlocked, new [] { "d MMM, yyyy @ h:mmtt", "d MMM @ h:mmtt" }, new CultureInfo("en-US"), DateTimeStyles.AssumeLocal, out DateUnlocked);
}
if (DateUnlocked != default)
{
gameAchievement.Where(x => x.UrlUnlocked.Split('/').Last().IsEqual(UrlUnlocked.Split('/').Last())).FirstOrDefault().DateUnlocked = DateUnlocked;
}
}
}
else if (ResultWeb.IndexOf("The specified profile could not be found") > -1)
{
}
}
catch (WebException ex)
{
Common.LogError(ex, false, true, PluginName);
}
return gameAchievement;
}
#endregion
#region Game
public override GameInfos GetGameInfos(string Id, AccountInfos accountInfos)
{
try
{
string Url = string.Format(UrlApiGameDetails, Id, CodeLang.GetSteamLang(Local));
string WebData = Web.DownloadStringData(Url).GetAwaiter().GetResult();
if (Serialization.TryFromJson(WebData, out Dictionary<string, StoreAppDetailsResult> parsedData))
{
StoreAppDetailsResult storeAppDetailsResult = parsedData[Id];
GameInfos gameInfos = new GameInfos
{
Id = storeAppDetailsResult?.data.steam_appid.ToString(),
Name = storeAppDetailsResult?.data.name,
Link = string.Format(UrlSteamGame, Id, CodeLang.GetSteamLang(Local)),
Image = storeAppDetailsResult?.data.header_image,
Description = ParseDescription(storeAppDetailsResult?.data.about_the_game)
};
// DLC
List<int> DlcsIdSteam = storeAppDetailsResult?.data.dlc ?? new List<int>();
List<int> DlcsIdSteamDb = GetFromSteamDb(storeAppDetailsResult?.data.steam_appid.ToString());
List<int> DlcsId = DlcsIdSteam.Union(DlcsIdSteamDb).Distinct().OrderBy(x => x).ToList();
if (DlcsId.Count > 0)
{
ObservableCollection<DlcInfos> Dlcs = GetDlcInfos(DlcsId, accountInfos);
gameInfos.Dlcs = Dlcs;
}
return gameInfos;
}
else
{
return null;
}
}
catch (Exception ex)
{
Common.LogError(ex, false, true, PluginName);
}
return null;
}
public override ObservableCollection<DlcInfos> GetDlcInfos(string Id, AccountInfos accountInfos)
{
GameInfos gameInfos = GetGameInfos(Id, accountInfos);
return gameInfos?.Dlcs ?? new ObservableCollection<DlcInfos>();
}
public ObservableCollection<DlcInfos> GetDlcInfos(List<int> dlcs, AccountInfos accountInfos)
{
try
{
ObservableCollection<DlcInfos> Dlcs = new ObservableCollection<DlcInfos>();
dlcs.ForEach(x =>
{
string Url = string.Format(UrlApiGameDetails, x, CodeLang.GetSteamLang(Local));
string WebData = Web.DownloadStringData(Url).GetAwaiter().GetResult();
if (Serialization.TryFromJson(WebData, out Dictionary<string, StoreAppDetailsResult> parsedData))
{
StoreAppDetailsResult storeAppDetailsResult = parsedData[x.ToString()];
bool IsOwned = false;
if (accountInfos != null && accountInfos.IsCurrent)
{
IsOwned = DlcIsOwned(storeAppDetailsResult?.data.steam_appid.ToString());
}
DlcInfos dlc = new DlcInfos
{
Id = storeAppDetailsResult.data.steam_appid.ToString(),
Name = storeAppDetailsResult.data.name,
Description = ParseDescription(storeAppDetailsResult?.data.about_the_game),
Image = storeAppDetailsResult.data.header_image,
Link = string.Format(UrlSteamGame, storeAppDetailsResult.data.steam_appid.ToString(), CodeLang.GetSteamLang(Local)),
IsOwned = IsOwned,
Price = storeAppDetailsResult.data.is_free ? "0" : storeAppDetailsResult.data.price_overview?.final_formatted,
PriceBase = storeAppDetailsResult.data.is_free ? "0" : storeAppDetailsResult.data.price_overview?.initial_formatted
};
Dlcs.Add(dlc);
}
});
return Dlcs;
}
catch (Exception ex)
{
Common.LogError(ex, false, true, PluginName);
}
return null;
}
#endregion
#region Games owned
internal override ObservableCollection<GameDlcOwned> GetGamesDlcsOwned()
{
if (!IsUserLoggedIn)
{
return null;
}
try
{
ObservableCollection<GameDlcOwned> GamesDlcsOwned = new ObservableCollection<GameDlcOwned>();
UserData?.rgOwnedApps?.ForEach(x =>
{
GamesDlcsOwned.Add(new GameDlcOwned { Id = x.ToString() });
});
return GamesDlcsOwned;
}
catch (Exception ex)
{
Common.LogError(ex, false, true, PluginName);
return null;
}
}
#endregion
#region Steam
private string LoadKey()
{
string key = string.Empty;
if (!FileSystem.FileExists(KeyPath))
{
return key;
}
try
{
key = Encryption.DecryptFromFile(
KeyPath,
Encoding.UTF8,
WindowsIdentity.GetCurrent().User.Value);
}
catch (Exception ex)
{
Common.LogError(ex, false, true, PluginName ,"Failed to load Steam API keys.");
}
return key;
}
private void SaveKeys(string key)
{
FileSystem.PrepareSaveFile(KeyPath);
Encryption.EncryptToFile(
KeyPath,
key,
Encoding.UTF8,
WindowsIdentity.GetCurrent().User.Value);
}
/// <summary>
/// Get the list of all games from the Steam store.
/// </summary>
/// <returns></returns>
private List<App> GetSteamAppsListFromWeb()
{
string Url = string.Empty;
List<App> AppsList = null;
try
{
Url = UrlApiAppsList;
string WebData = Web.DownloadStringData(Url).GetAwaiter().GetResult();
if (WebData.IsNullOrEmpty() || WebData == "{\"applist\":{\"apps\":[]}}")
{
WebData = "{}";
}
Serialization.TryFromJson(WebData, out Models.SteamApps appsListResponse);
// Write file for cache
if (appsListResponse != null)
{
AppsList = appsListResponse.applist.apps;
File.WriteAllText(AppsListPath, Serialization.ToJson(AppsList), Encoding.UTF8);
}
else
{
logger.Warn($"appsListResponse is empty");
}
}
catch (Exception ex)
{
Common.LogError(ex, false, $"Failed to load from {Url}");
}
return AppsList;
}
/// <summary>
/// Get AppId from Steam store with a game name.
/// </summary>
/// <param name="Name"></param>
/// <returns></returns>
public int GetAppId(string Name)
{
AppsList.Sort((x, y) => x.appid.CompareTo(y.appid));
List<int> found = AppsList.FindAll(x => x.name.IsEqual(Name, true)).Select(x => x.appid).Distinct().ToList();
if (found != null && found.Count > 0)
{
if (found.Count > 1)
{
logger.Warn($"Found {found.Count} SteamAppId data for {Name}: " + string.Join(", ", found));
return 0;
}
Common.LogDebug(true, $"Found SteamAppId data for {Name} - {Serialization.ToJson(found)}");
return found.First();
}
return 0;
}
/// <summary>
/// Get name from Steam store with a AppId.
/// </summary>
/// <param name="AppId"></param>
/// <returns></returns>
public string GetGameName(int AppId)
{
AppsList.Sort((x, y) => x.appid.CompareTo(y.appid));
App found = AppsList.Find(x => x.appid == AppId); ;
if (found != null)
{
Common.LogDebug(true, $"Found Steam data for {AppId} - {Serialization.ToJson(found)}");
return found.name;
}
return string.Empty;
}
/// <summary>
/// Get AccountID for a SteamId
/// </summary>
/// <returns></returns>
public static uint GetAccountId(ulong SteamId)
{
try
{
SteamID steamID = new SteamID();
steamID.SetFromUInt64(SteamId);
return steamID.AccountID;
}
catch (Exception ex)
{
Common.LogError(ex, false);
}
return 0;
}
private ObservableCollection<AccountInfos> GetCurrentFriendsInfos_Api()
{
try
{
string Url = string.Format(UrlApiFriendList, CurrentUser.ApiKey, CurrentUser.SteamId);
string WebData = Web.DownloadStringData(Url).GetAwaiter().GetResult();
Serialization.TryFromJson(WebData, out FriendsList friendsList);
ObservableCollection<AccountInfos> accountsInfos = new ObservableCollection<AccountInfos>();
friendsList?.friendslist?.friends?.ForEach(x =>
{
long.TryParse(x.steamid, out long UserId);
string Avatar = string.Empty;
string Pseudo = string.Empty;
string Link = string.Empty;
DateTime? DateAdded = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(x.friend_since);
AccountInfos userInfos = new AccountInfos
{
UserId = UserId,
Avatar = Avatar,
Pseudo = Pseudo,
Link = Link
};
accountsInfos.Add(userInfos);
});
return accountsInfos;
}
catch (Exception ex)
{
Common.LogError(ex, false, true, PluginName);
}
return null;
}
/// <summary>
/// Get the Steam installation path.
/// </summary>
/// <returns></returns>
public string GetInstallationPath()
{
try
{
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Valve\Steam"))
{
if (key?.GetValueNames().Contains("SteamPath") == true)
{
return key.GetValue("SteamPath")?.ToString().Replace('/', '\\') ?? string.Empty;
}
}
}
catch (Exception ex)
{
Common.LogError(ex, false, true, PluginName);
}
logger.Warn("No Steam installation found");
return string.Empty;
}
/// <summary>
/// Get the Steam screanshots folder.
/// </summary>
/// <returns></returns>
public string GetScreeshotsPath()
{
string PathScreeshotsFolder = Path.Combine(InstallationPath, "userdata", CurrentUser.AccountId.ToString(), "760", "remote");
if (Directory.Exists(PathScreeshotsFolder))
{
return PathScreeshotsFolder;
}
logger.Warn("No Steam screenshots folder found");
return string.Empty;
}
/// <summary>
/// Get the list of all users defined in local.
/// </summary>
/// <returns></returns>
public List<Models.SteamUser> GetSteamUsers()
{
List<Models.SteamUser> users = new List<Models.SteamUser>();
if (File.Exists(LoginUsersPath))
{
KeyValue config = new KeyValue();
try
{
Stream sFile = FileSystem.OpenReadFileStreamSafe(LoginUsersPath);
config.ReadAsText(sFile);
foreach (KeyValue user in config.Children)
{
users.Add(new Models.SteamUser()
{
SteamId = ulong.Parse(user.Name),
AccountName = user["AccountName"].Value,
PersonaName = user["PersonaName"].Value,
});
}
return users;
}
catch (Exception ex)
{
Common.LogError(ex, false, true, PluginName);
}
}
return null;
}
/// <summary>
/// Get Playnite configured user.
/// </summary>
/// <returns></returns>
private Models.SteamUser GetCurrentUser()
{
try
{
if (File.Exists(SteamLibraryConfigFile))
{
dynamic SteamConfig = Serialization.FromJsonFile<dynamic>(SteamLibraryConfigFile);
ulong.TryParse(SteamConfig["UserId"].ToString(), out ulong SteamId);
string ApiKey = LoadKey();
List<Models.SteamUser> SteamUsers = GetSteamUsers();
Models.SteamUser steamUser = SteamUsers.Find(x => x.SteamId == SteamId);
if (steamUser != null)
{
Task.Run(() =>
{
steamUser.IsPrivateAccount = !CheckIsPublic(steamUser).GetAwaiter().GetResult();
steamUser.AccountStatus = steamUser.IsPrivateAccount ? AccountStatus.Private : AccountStatus.Public;
});
steamUser.ApiKey = ApiKey;
}
return steamUser;
}
else
{
logger.Warn("No SteamLibrary configuration found");
}
}
catch (Exception ex)
{
Common.LogError(ex, false, true, PluginName);
}
return null;
}
public async Task<bool> CheckIsPublic(Models.SteamUser steamUser)
{
bool withId = await IsProfilePublic(string.Format(UrlProfileById, steamUser.SteamId));
bool withPersona = await IsProfilePublic(string.Format(UrlProfileByName, steamUser.PersonaName));
return withId || withPersona;
}
private async Task<bool> IsProfilePublic(string profilePageUrl)
{
return await IsProfilePublic(profilePageUrl, null);
}
private async Task<bool> IsProfilePublic(string profilePageUrl, List<HttpCookie> httpCookies)
{
try
{
string ResultWeb = await Web.DownloadStringData(profilePageUrl, httpCookies);
IHtmlDocument HtmlDoc = new HtmlParser().Parse(ResultWeb);
IElement profile_private_info = HtmlDoc.QuerySelector("div.profile_private_info");
IElement error_ctn = HtmlDoc.QuerySelector("div.error_ctn");
return profile_private_info == null && error_ctn == null;
}
catch (Exception ex)
{
Common.LogError(ex, false);
}
return false;
}
private SteamUserData LoadUserData(bool OnlyNow = false)
{
if (File.Exists(FileUserData))
{
try
{
DateTime DateLastWrite = File.GetLastWriteTime(FileUserData);
if (OnlyNow && !(DateLastWrite.ToString("yyyy-MM-dd") == DateTime.Now.ToString("yyyy-MM-dd")))
{
return null;
}
if (!OnlyNow)
{
LocalDateTimeConverter localDateTimeConverter = new LocalDateTimeConverter();
string formatedDateLastWrite = localDateTimeConverter.Convert(DateLastWrite, null, null, CultureInfo.CurrentCulture).ToString();
logger.Warn($"Use saved UserData - {formatedDateLastWrite}");
API.Instance.Notifications.Add(new NotificationMessage(
$"{PluginName}-steam-saveddata",