-
Notifications
You must be signed in to change notification settings - Fork 0
/
SteamChecks.cs
1215 lines (1107 loc) · 52.4 KB
/
SteamChecks.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 System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.Linq;
using Oxide.Core;
using Oxide.Core.Libraries.Covalence;
namespace Oxide.Plugins
{
[Info("Steam Checks", "Sapd", "5.0.4")]
[Description("Kick players depending on information on their Steam profile")]
public class SteamChecks : CovalencePlugin
{
/// <summary>
/// Set of steamids, which already passed the steamcheck test on joining
/// </summary>
/// <remarks>
/// Resets after a plugin reload
/// </remarks>
private HashSet<string> passedList;
/// <summary>
/// Set of steamids, which failed the steamcheck test on joining
/// </summary>
/// <remarks>
/// Resets after a plugin reload
/// </remarks>
private HashSet<string> failedList;
/// <summary>
/// AppID of the game, where the plugin is loaded
/// </summary>
private uint appId;
/// <summary>
/// Url to the Steam Web API
/// </summary>
private const string apiURL = "https://api.steampowered.com";
/// <summary>
/// Oxide permission for a whitelist
/// </summary>
private const string skipPermission = "steamchecks.skip";
/// <summary>
/// Timeout for a web request
/// </summary>
private const int webTimeout = 2000;
/// <summary>
/// API Key to use for the Web API
/// </summary>
/// <remarks>
/// https://steamcommunity.com/dev/apikey
/// </remarks>
private string apiKey;
/// <summary>
/// Broadcast kick via chat?
/// </summary>
private bool broadcastKick;
/// <summary>
/// Just log instead of actually kicking users?
/// </summary>
private bool logInsteadofKick;
/// <summary>
/// This message will be appended to all Kick-messages
/// </summary>
private string additionalKickMessage;
/// <summary>
/// Cache players, which joined and successfully completed the checks
/// </summary>
private bool cachePassedPlayers;
/// <summary>
/// Cache players, which joined and failed the checks
/// </summary>
private bool cacheDeniedPlayers;
/// <summary>
/// Kick when the user has a Steam Community ban
/// </summary>
private bool kickCommunityBan;
/// <summary>
/// Kick when the user has a Steam Trade ban
/// </summary>
private bool kickTradeBan;
/// <summary>
/// Kick when the user has a private profile
/// </summary>
/// <remarks>
/// Most checks depend on a public profile
/// </remarks>
private bool kickPrivateProfile;
/// <summary>
/// Kick when the user has a limited account
/// </summary>
private bool kickLimitedAccount;
/// <summary>
/// Kick when the user has not set up his steam profile yet
/// </summary>
private bool kickNoProfile;
/// <summary>
/// Kick when the user is using a lended game
/// </summary>
private bool kickFamilyShare;
/// <summary>
/// Kick user, when his hours are hidden
/// </summary>
/// <remarks>
/// A lot of steam users have their hours hidden
/// </remarks>
private bool forceHoursPlayedKick;
/// <summary>
/// Maximum amount of VAC bans, the user is allowed to have
/// </summary>
private int maxVACBans;
/// <summary>
/// How old the last VAC ban should minimally
/// </summary>
private int minDaysSinceLastBan;
/// <summary>
/// Maximum amount of game bans, the user is allowed to have
/// </summary>
private int maxGameBans;
/// <summary>
/// The minimum steam level, the user must have
/// </summary>
private int minSteamLevel;
/// <summary>
/// Minimum amount of rust played
/// </summary>
private int minRustHoursPlayed;
/// <summary>
/// Maximum amount of rust played
/// </summary>
private int maxRustHoursPlayed;
/// <summary>
/// Minimum amount of Steam games played - except Rust
/// </summary>
private int minOtherGamesPlayed;
/// <summary>
/// Minimum amount of Steam games played - including Rust
/// </summary>
private int minAllGamesHoursPlayed;
/// <summary>
/// Minimum amount of Steam games
/// </summary>
private int minGameCount;
/// <summary>
/// Unix-Time, if the account created by the user is newer/higher than it
/// he won't be allowed
/// </summary>
private long maxAccountCreationTime;
/// <summary>
/// Loads default configuration options
/// </summary>
protected override void LoadDefaultConfig()
{
Config["ApiKey"] = "";
Config["BroadcastKick"] = false;
Config["LogInsteadofKick"] = false;
Config["AdditionalKickMessage"] = "";
Config["CachePassedPlayers"] = true;
Config["CacheDeniedPlayers"] = false;
Config["Kicking"] = new Dictionary<string, bool>
{
["CommunityBan"] = true,
["TradeBan"] = true,
["PrivateProfile"] = true,
["LimitedAccount"] = true,
["NoProfile"] = true,
["FamilyShare"] = false,
["ForceHoursPlayedKick"] = false,
};
Config["Thresholds"] = new Dictionary<string, long>
{
["MaxVACBans"] = 1,
["MinDaysSinceLastBan"] = -1,
["MaxGameBans"] = 1,
["MinSteamLevel"] = 2,
["MaxAccountCreationTime"] = -1,
["MinGameCount"] = 3,
["MinRustHoursPlayed"] = -1,
["MaxRustHoursPlayed"] = -1,
["MinOtherGamesPlayed"] = 2,
["MinAllGamesHoursPlayed"] = -1
};
}
/// <summary>
/// Initializes config options, for every plugin start
/// </summary>
private void InitializeConfig()
{
apiKey = Config.Get<string>("ApiKey");
broadcastKick = Config.Get<bool>("BroadcastKick");
logInsteadofKick = Config.Get<bool>("LogInsteadofKick");
additionalKickMessage = Config.Get<string>("AdditionalKickMessage");
cachePassedPlayers = Config.Get<bool>("CachePassedPlayers");
cacheDeniedPlayers = Config.Get<bool>("CacheDeniedPlayers");
kickCommunityBan = Config.Get<bool>("Kicking", "CommunityBan");
kickTradeBan = Config.Get<bool>("Kicking", "TradeBan");
kickPrivateProfile = Config.Get<bool>("Kicking", "PrivateProfile");
kickLimitedAccount = Config.Get<bool>("Kicking", "LimitedAccount");
kickNoProfile = Config.Get<bool>("Kicking", "NoProfile");
kickFamilyShare = Config.Get<bool>("Kicking", "FamilyShare");
forceHoursPlayedKick = Config.Get<bool>("Kicking", "ForceHoursPlayedKick");
maxVACBans = Config.Get<int>("Thresholds", "MaxVACBans");
minDaysSinceLastBan = Config.Get<int>("Thresholds", "MinDaysSinceLastBan");
maxGameBans = Config.Get<int>("Thresholds", "MaxGameBans");
minSteamLevel = Config.Get<int>("Thresholds", "MinSteamLevel");
minRustHoursPlayed = Config.Get<int>("Thresholds", "MinRustHoursPlayed") * 60;
maxRustHoursPlayed = Config.Get<int>("Thresholds", "MaxRustHoursPlayed") * 60;
minOtherGamesPlayed = Config.Get<int>("Thresholds", "MinOtherGamesPlayed") * 60;
minAllGamesHoursPlayed = Config.Get<int>("Thresholds", "MinAllGamesHoursPlayed") * 60;
minGameCount = Config.Get<int>("Thresholds", "MinGameCount");
maxAccountCreationTime = Config.Get<long>("Thresholds", "MaxAccountCreationTime");
if (!kickPrivateProfile)
{
if (minRustHoursPlayed > 0 || maxRustHoursPlayed > 0 || minOtherGamesPlayed > 0 || minAllGamesHoursPlayed > 0)
LogWarning(Lang("WarningPrivateProfileHours"));
if (minGameCount > 1)
LogWarning(Lang("WarningPrivateProfileGames"));
if (maxAccountCreationTime > 0)
LogWarning(Lang("WarningPrivateProfileCreationTime"));
if (minSteamLevel > 0)
LogWarning(Lang("WarningPrivateProfileSteamLevel"));
}
}
/// <summary>
/// Load default language messages, for every plugin start
/// </summary>
protected override void LoadDefaultMessages()
{
lang.RegisterMessages(new Dictionary<string, string>
{
["Console"] = "Kicking {0}... ({1})",
["ErrorAPIConfig"] = "The API key you supplied in the config is empty.. register one here https://steamcommunity.com/dev/apikey",
["WarningPrivateProfileHours"] = "**** WARNING: Private profile-kick is off. However a option to kick for minimim amount of hours is on.",
["WarningPrivateProfileGames"] = "**** WARNING: Private profile-kick is off. However the option to kick for minimim amount of games is on (MinGameCount).",
["WarningPrivateProfileCreationTime"] = "**** WARNING: Private profile-kick is off. However the option to kick for account age is on (MinAccountCreationTime).",
["WarningPrivateProfileSteamLevel"] = "**** WARNING: Private profile-kick is off. However the option to kick for steam level is on (MinSteamLevel).",
["ErrorHttp"] = "Error while contacting the SteamAPI. Error: {0}.",
["ErrorPrivateProfile"] = "This player has a private profile, therefore SteamChecks cannot check their hours.",
["KickCommunityBan"] = "You have a Steam Community ban on record.",
["KickFamilyShare"] = "Please buy the game instead of lending it via family share.",
["KickVacBan"] = "You have too many VAC bans on record.",
["KickGameBan"] = "You have too many Game bans on record.",
["KickTradeBan"] = "You have a Steam Trade ban on record.",
["KickPrivateProfile"] = "Your Steam profile state is set to private.",
["KickLimitedAccount"] = "Your Steam account is limited.",
["KickNoProfile"] = "Set up your Steam community profile first.",
["KickMinSteamLevel"] = "Your Steam level is not high enough.",
["KickMinRustHoursPlayed"] = "You haven't played enough hours.",
["KickMaxRustHoursPlayed"] = "You have played too much Rust.",
["KickMinSteamHoursPlayed"] = "You didn't play enough Steam games (hours).",
["KickMinNonRustPlayed"] = "You didn't play enough Steam games besides Rust (hours).",
["KickHoursPrivate"] = "Your Steam profile is public, but the hours you played is hidden'.",
["KickGameCount"] = "You don't have enough Steam games.",
["KickMaxAccountCreationTime"] = "Your Steam account is too new.",
["KickGeneric"] = "Your Steam account fails our test.",
}, this);
}
/// <summary>
/// Called by Oxide when plugin starts
/// </summary>
private void Init()
{
InitializeConfig();
if (string.IsNullOrEmpty(apiKey))
{
LogError(Lang("ErrorAPIConfig"));
// Unload on next tick
timer.Once(1f, () =>
{
server.Command("oxide.unload SteamChecks");
});
return;
}
appId = covalence.ClientAppId;
passedList = new HashSet<string>();
failedList = new HashSet<string>();
permission.RegisterPermission(skipPermission, this);
}
/// <summary>
/// Called when a user connects (but before he is spawning)
/// </summary>
/// <param name="player"></param>
private void OnUserConnected(IPlayer player)
{
if (string.IsNullOrEmpty(apiKey))
return;
if (player.HasPermission(skipPermission))
{
Log("{0} / {1} in whitelist (via permission {2})", player.Name, player.Id, skipPermission);
return;
}
// Check temporary White/Blacklist if kicking is enabled
if (!logInsteadofKick)
{
// Player already passed the checks, since the plugin is active
if (cachePassedPlayers && passedList.Contains(player.Id))
{
Log("{0} / {1} passed all checks already previously", player.Name, player.Id);
return;
}
// Player already passed the checks, since the plugin is active
if (cacheDeniedPlayers && failedList.Contains(player.Id))
{
Log("{0} / {1} failed a check already previously", player.Name, player.Id);
player.Kick(Lang("KickGeneric", player.Id) + " " + additionalKickMessage);
return;
}
}
CheckPlayer(player.Id, (playerAllowed, reason) =>
{
if (playerAllowed)
{
Log("{0} / {1} passed all checks", player.Name, player.Id);
passedList.Add(player.Id);
}
else
{
if (logInsteadofKick)
{
Log("{0} / {1} would have been kicked. Reason: {2}", player.Name, player.Id, reason);
}
else
{
Log("{0} / {1} kicked. Reason: {2}", player.Name, player.Id, reason);
failedList.Add(player.Id);
player.Kick(reason + " " + additionalKickMessage);
if (broadcastKick)
{
foreach (IPlayer target in players.Connected)
{
target.Message(Lang("Console", player.Id), "", player.Name, reason);
}
}
}
}
});
}
/// <summary>
/// Checks a steamid, wether it would be allowed into the server
/// </summary>
/// <param name="steamid">steamid64 of the user</param>
/// <param name="callback">
/// First parameter is true, when the user is allowed, otherwise false
/// Second parameter is the reason why he is not allowed, filled out when first is false
/// </param>
/// <remarks>
/// Asynchrounously
/// Runs through all checks one-by-one
/// 1. Bans
/// 2. Player Summaries (Private profile, Creation time)
/// 3. Player Level
/// Via <see cref="CheckPlayerGameTime"></see>
/// 4. Game Hours and Count
/// 5. Game badges, to get amount of games if user has hidden Game Hours
/// </remarks>
private void CheckPlayer(string steamid, Action<bool, string> callback)
{
// Check Bans first, as they are also visible on private profiles
GetPlayerBans(steamid, (banStatusCode, banResponse) =>
{
if (banStatusCode != (int)SteamChecks.StatusCode.Success)
{
APIError(steamid, "GetPlayerBans", banStatusCode);
return;
}
if (banResponse.CommunityBan && kickCommunityBan)
{
callback(false, Lang("KickCommunityBan", steamid));
return;
}
if (banResponse.EconomyBan && kickTradeBan)
{
callback(false, Lang("KickTradeBan", steamid));
return;
}
if (banResponse.GameBanCount > maxGameBans && maxGameBans > -1)
{
callback(false, Lang("KickGameBan", steamid));
return;
}
if (banResponse.VacBanCount > maxVACBans && maxVACBans > -1)
{
callback(false, Lang("KickVacBan", steamid));
return;
}
if (banResponse.LastBan > 0 && banResponse.LastBan < minDaysSinceLastBan && minDaysSinceLastBan > 0)
{
callback(false, Lang("KickVacBan", steamid));
return;
}
// Check if the game is lended
GetIsSharedGame(steamid, (sharedStatuscode, sharedResult) =>
{
if (sharedStatuscode != (int)SteamChecks.StatusCode.Success)
{
APIError(steamid, "GetIsSharedGame", sharedStatuscode);
return;
}
if (sharedResult && kickFamilyShare)
{
callback(false, Lang("KickFamilyShare", steamid));
return;
}
else
{
// Next, get Player summaries - we have to check if the profile is public
GetSteamPlayerSummaries(steamid, (sumStatuscode, sumResult) =>
{
if (sumStatuscode != (int)SteamChecks.StatusCode.Success)
{
APIError(steamid, "GetSteamPlayerSummaries", sumStatuscode);
return;
}
if (sumResult.LimitedAccount && kickLimitedAccount)
{
callback(false, Lang("KickLimitedAccount", steamid));
return;
}
if (sumResult.NoProfile && kickNoProfile)
{
callback(false, Lang("KickNoProfile", steamid));
return;
}
// Is profile not public?
if (sumResult.Visibility != PlayerSummary.VisibilityType.Public)
{
if (kickPrivateProfile)
{
callback(false, Lang("KickPrivateProfile", steamid));
return;
}
else
{
// If it is not public, we can cancel checks here and allow the player in
callback(true, null);
return;
}
}
// Check how old the account is
if (maxAccountCreationTime > 0 && sumResult.Timecreated > maxAccountCreationTime)
{
callback(false, Lang("KickMaxAccountCreationTime", steamid));
return;
}
// Check Steam Level
if (minSteamLevel > 0)
{
GetSteamLevel(steamid, (steamLevelStatusCode, steamLevelResult) =>
{
if (steamLevelStatusCode != (int)SteamChecks.StatusCode.Success)
{
APIError(steamid, "GetSteamLevel", sumStatuscode);
return;
}
if (minSteamLevel > steamLevelResult)
{
callback(false, Lang("KickMinSteamLevel", steamid));
return;
}
else
{
// Check game time, and amount of games
if (minGameCount > 1 || minRustHoursPlayed > 0 || maxRustHoursPlayed > 0 ||
minOtherGamesPlayed > 0 || minAllGamesHoursPlayed > 0)
CheckPlayerGameTime(steamid, callback);
else // Player now already passed all checks
callback(true, null);
}
});
}
// Else, if level check not done, Check game time, and amount of games
else if (minGameCount > 1 || minRustHoursPlayed > 0 || maxRustHoursPlayed > 0 ||
minOtherGamesPlayed > 0 || minAllGamesHoursPlayed > 0)
{
CheckPlayerGameTime(steamid, callback);
}
else // Player now already passed all checks
{
callback(true, null);
}
});
}
});
});
}
/// <summary>
/// Checks a steamid, wether it would be allowed into the server
/// Called by <see cref="CheckPlayer"></see>
/// </summary>
/// <param name="steamid">steamid64 of the user</param>
/// <param name="callback">
/// First parameter is true, when the user is allowed, otherwise false
/// Second parameter is the reason why he is not allowed, filled out when first is false
/// </param>
/// <remarks>
/// Regards those specific parts:
/// - Game Hours and Count
/// - Game badges, to get amount of games if user has hidden Game Hours
/// </remarks>
void CheckPlayerGameTime(string steamid, Action<bool, string> callback)
{
GetPlaytimeInformation(steamid, (gameTimeStatusCode, gameTimeResult) =>
{
// Players can additionally hide their play time, check
bool gametimeHidden = false;
if (gameTimeStatusCode == (int)SteamChecks.StatusCode.GameInfoHidden)
{
gametimeHidden = true;
}
// Check if the request failed in general
else if (gameTimeStatusCode != (int)SteamChecks.StatusCode.Success)
{
APIError(steamid, "GetPlaytimeInformation", gameTimeStatusCode);
return;
}
// In rare cases, the SteamAPI returns all games, however with the gametime set to 0. (when the user has this info hidden)
if (gameTimeResult != null && (gameTimeResult.PlaytimeRust == 0 || gameTimeResult.PlaytimeAll == 0))
gametimeHidden = true;
// If the server owner really wants a hour check, we will kick
if (gametimeHidden && forceHoursPlayedKick)
{
if (minRustHoursPlayed > 0 || maxRustHoursPlayed > 0 ||
minOtherGamesPlayed > 0 || minAllGamesHoursPlayed > 0)
{
callback(false, Lang("KickHoursPrivate", steamid));
return;
}
}
// Check the times and game count now, when not hidden
else if (!gametimeHidden)
{
if (minRustHoursPlayed > 0 && gameTimeResult.PlaytimeRust < minRustHoursPlayed)
{
callback(false, Lang("KickMinRustHoursPlayed", steamid));
return;
}
if (maxRustHoursPlayed > 0 && gameTimeResult.PlaytimeRust > maxRustHoursPlayed)
{
callback(false, Lang("KickMaxRustHoursPlayed", steamid));
return;
}
if (minAllGamesHoursPlayed > 0 && gameTimeResult.PlaytimeAll < minAllGamesHoursPlayed)
{
callback(false, Lang("KickMinSteamHoursPlayed", steamid));
return;
}
if (minOtherGamesPlayed > 0 &&
(gameTimeResult.PlaytimeAll - gameTimeResult.PlaytimeRust) < minOtherGamesPlayed &&
gameTimeResult.GamesCount > 1) // it makes only sense to check, if there are other games in the result set
{
callback(false, Lang("KickMinNonRustPlayed", steamid));
return;
}
if (minGameCount > 1 && gameTimeResult.GamesCount < minGameCount)
{
callback(false, Lang("KickGameCount", steamid));
return;
}
}
// If the server owner wants to check minimum amount of games, but the user has hidden game time
// We will get the count over an additional API request via badges
if (gametimeHidden && minGameCount > 1)
{
GetSteamBadges(steamid, (badgeStatusCode, badgeResult) =>
{
// Check if the request failed in general
if (badgeStatusCode != (int)SteamChecks.StatusCode.Success)
{
APIError(steamid, "GetPlaytimeInformation", gameTimeStatusCode);
return;
}
int gamesOwned = ParseBadgeLevel(badgeResult, Badge.GamesOwned);
if (gamesOwned < minGameCount)
{
callback(false, Lang("KickGameCount", steamid));
return;
}
else
{
// Checks passed
callback(true, null);
return;
}
});
}
else
{
// Checks passed
callback(true, null);
}
});
}
#region WebAPI
/// <summary>
/// HTTP Status Codes (positive) and
/// custom status codes (negative)
///
/// 200 is successfull in all cases
/// </summary>
enum StatusCode
{
Success = 200,
BadRequest = 400,
Unauthorized = 401,
Forbidden = 403,
NotFound = 404,
MethodNotAllowed = 405,
TooManyRequests = 429,
InternalError = 500,
Unavailable = 503,
/// <summary>
/// User has is games and game hours hidden
/// </summary>
GameInfoHidden = -100,
/// <summary>
/// Invalid steamid
/// </summary>
PlayerNotFound = -101,
/// <summary>
/// Can also happen, when the SteamAPI returns something unexpected
/// </summary>
ParsingFailed = -102
}
/// <summary>
/// Type of Steam request
/// </summary>
enum SteamRequestType
{
/// <summary>
/// Allows to request only one SteamID
/// </summary>
IPlayerService,
/// <summary>
/// Allows to request multiple SteamID
/// But only one used
/// </summary>
ISteamUser
}
/// <summary>
/// Generic request to the Steam Web API
/// </summary>
/// <param name="steamRequestType"></param>
/// <param name="endpoint">The specific endpoint, e.g. GetSteamLevel/v1</param>
/// <param name="steamid64"></param>
/// <param name="callback">Callback returning the HTTP status code <see cref="StatusCode"></see> and a JSON JObject</param>
/// <param name="additionalArguments">Additional arguments, e.g. &foo=bar</param>
private void SteamWebRequest(SteamRequestType steamRequestType, string endpoint, string steamid64,
Action<int, JObject> callback, string additionalArguments = "")
{
string requestUrl = String.Format("{0}/{1}/{2}/?key={3}&{4}={5}{6}", apiURL, steamRequestType.ToString(),
endpoint, apiKey, steamRequestType == SteamRequestType.IPlayerService ? "steamid" : "steamids", steamid64, additionalArguments);
webrequest.Enqueue(requestUrl, "", (httpCode, response) =>
{
if (httpCode == (int)StatusCode.Success)
{
callback(httpCode, JObject.Parse(response));
}
else
{
callback(httpCode, null);
}
}, this, Core.Libraries.RequestMethod.GET, null, webTimeout);
}
/// <summary>
/// Get the Steam level of a user
/// </summary>
/// <param name="steamid64">The users steamid64</param>
/// <param name="callback">Callback with the statuscode <see cref="StatusCode"></see> and the steamlevel</param>
private void GetSteamLevel(string steamid64, Action<int, int> callback)
{
SteamWebRequest(SteamRequestType.IPlayerService, "GetSteamLevel/v1", steamid64,
(httpCode, jsonResponse) =>
{
if (httpCode == (int)StatusCode.Success)
{
JToken response = jsonResponse["response"]?["player_level"];
if (response == null)
callback((int)StatusCode.ParsingFailed, Int32.MaxValue);
else
callback(httpCode, (int)response);
}
else
{
callback(httpCode, -1);
}
});
}
/// <summary>
/// Struct for the GetOwnedGames API request
/// </summary>
class GameTimeInformation
{
/// <summary>
/// Amount of games the user has
/// </summary>
public int GamesCount { get; set; }
/// <summary>
/// Play time in rust
/// </summary>
public int PlaytimeRust { get; set; }
/// <summary>
/// Play time accross all Steam games
/// </summary>
public int PlaytimeAll { get; set; }
public GameTimeInformation(int gamesCount, int playtimeRust, int playtimeAll)
{
this.GamesCount = gamesCount;
this.PlaytimeRust = playtimeRust;
this.PlaytimeAll = playtimeAll;
}
public override string ToString()
{
return String.Format("Gamescount: {0} - Playtime in Rust: {1} - Playtime all Steam games: {2}", GamesCount, PlaytimeRust, PlaytimeAll);
}
}
/// <summary>
/// Get information about hours played in Steam
/// </summary>
/// <param name="steamid64">steamid64 of the user</param>
/// <param name="callback">Callback with the statuscode <see cref="StatusCode"></see> and the <see cref="GameTimeInformation"></see></param>
/// <remarks>
/// Even when the user has his profile public, this can be hidden. This seems to be often the case.
/// When hidden, the statuscode will be <see cref="StatusCode.GameInfoHidden"></see>
/// </remarks>
private void GetPlaytimeInformation(string steamid64, Action<int, GameTimeInformation> callback)
{
SteamWebRequest(SteamRequestType.IPlayerService, "GetOwnedGames/v1", steamid64,
(httpCode, jsonResponse) =>
{
if (httpCode == (int)StatusCode.Success)
{
// We need to check wether it is null, because the steam-user can hide game information
JToken gamesCountJSON = jsonResponse["response"]?["game_count"];
if (gamesCountJSON == null)
{
callback((int)StatusCode.GameInfoHidden, null);
return;
}
// Also do another null check
int gamescount = (int)gamesCountJSON;
JToken playtimeRustjson = jsonResponse.SelectToken("$...games[?(@.appid == 252490)].playtime_forever", false);
if (playtimeRustjson == null)
{
callback((int)StatusCode.GameInfoHidden, null);
return;
}
int playtimeRust = (int)playtimeRustjson;
int playtimeAll = (int)jsonResponse["response"]["games"].Sum(m => (int)m.SelectToken("playtime_forever"));
callback(httpCode, new GameTimeInformation(gamescount, playtimeRust, playtimeAll));
}
else
{
callback(httpCode, null);
}
}, "&include_appinfo=false"); // We dont need additional appinfos, like images
}
/// <summary>
/// Struct for the GetPlayerSummaries/v2 Web API request
/// </summary>
public class PlayerSummary
{
/// <summary>
/// How visible the Steam Profile is
/// </summary>
public enum VisibilityType
{
Private = 1,
Friend = 2,
Public = 3
}
public VisibilityType Visibility { get; set; }
/// <summary>
/// URL to his steam profile
/// </summary>
public string Profileurl { get; set; }
/// <summary>
/// When his account was created - in Unix time
/// </summary>
/// <remarks>
/// Will only be filled, if the users profile is public
/// </remarks>
public long Timecreated { get; set; }
/// <summary>
/// Is the account limited?
/// </summary>
/// <remarks>
/// Will be fulfilled by an additional request directly to the steamprofile with ?xml=1
/// </remarks>
public bool LimitedAccount { get; set; }
/// <summary>
/// Has the user set up his profile?
/// </summary>
/// <remarks>
/// Will be fulfilled by an additional request directly to the steamprofile with ?xml=1
/// </remarks>
public bool NoProfile { get; set; }
public override string ToString()
{
return String.Format("Steam profile visibility: {0} - Profile URL: {1} - Account created: {2} - Limited: {3} - NoProfile: {4}",
Visibility.ToString(), Profileurl, Timecreated.ToString(), LimitedAccount, NoProfile);
}
}
/// <summary>
/// Get Summary information about the player, like if his profile is visible
/// </summary>
/// <param name="steamid64">steamid64 of the user</param>
/// <param name="callback">Callback with the statuscode <see cref="StatusCode"></see> and the <see cref="PlayerSummary"></see></param>
private void GetSteamPlayerSummaries(string steamid64, Action<int, PlayerSummary> callback)
{
SteamWebRequest(SteamRequestType.ISteamUser, "GetPlayerSummaries/v2", steamid64,
(httpCode, jsonResponse) =>
{
if (httpCode == (int)StatusCode.Success)
{
if (jsonResponse["response"]["players"].Count() != 1)
{
callback((int)StatusCode.PlayerNotFound, null);
return;
}
PlayerSummary summary = new PlayerSummary();
summary.Visibility = (PlayerSummary.VisibilityType)(int)jsonResponse["response"]["players"][0]["communityvisibilitystate"];
summary.Profileurl = (string)jsonResponse["response"]["players"][0]["profileurl"];
// Account creation time can be only fetched, when the profile is public
if (summary.Visibility == PlayerSummary.VisibilityType.Public)
summary.Timecreated = (int)jsonResponse["response"]["players"][0]["timecreated"];
else
summary.Timecreated = -1;
// We have to to a seperate request to the steamcommunity profile to get infos about limited and wether their set up their profile
{
// Set defaults, which won't get the user kicked
summary.NoProfile = false;
summary.LimitedAccount = false;
webrequest.Enqueue(string.Format("https://steamcommunity.com/profiles/{0}/?xml=1", steamid64), "", (httpCodeCommunity, responseCommunity) =>
{
if (httpCodeCommunity == (int)StatusCode.Success)
{
// XML parser is disabled in umod, so have to use contains
// Has not set up their profile?
if (responseCommunity.Contains("This user has not yet set up their Steam Community profile."))
summary.NoProfile = true;
if (responseCommunity.Contains("<isLimitedAccount>1</isLimitedAccount>"))
summary.LimitedAccount = true;
callback(httpCode, summary);
}
else
{
APIError(steamid64, "GetSteamPlayerSummaries - community xml", httpCodeCommunity);
// We will send into the callback success, as the normal GetSteamPlayerSummaries worked in this case
// So it's information can be respected
callback((int)StatusCode.Success, summary);
}
}, this, Core.Libraries.RequestMethod.GET, null, webTimeout);
}
}
else
{
callback(httpCode, null);
}
});
}
/// <summary>
/// Is the player playing a lended game?
/// </summary>
/// <param name="steamid64">steamid64 of the user</param>
/// <param name="callback">Callback with the statuscode <see cref="StatusCode"></see> and bool which is true, if he is lending</param>
private void GetIsSharedGame(string steamid64, Action<int, bool> callback)
{
SteamWebRequest(SteamRequestType.IPlayerService, "IsPlayingSharedGame/v1", steamid64,
(httpCode, jsonResponse) =>
{
if (httpCode == (int)StatusCode.Success)
{
JToken gamesCountJSON = jsonResponse["response"]?["lender_steamid"];
if (gamesCountJSON == null)
{
callback((int)StatusCode.ParsingFailed, false);
return;
}
if ((string)gamesCountJSON != "0")
callback(httpCode, true);
else
callback(httpCode, false);
}
else
{
callback(httpCode, false);
}
}, "&appid_playing=" + appId);
}
/// <summary>
/// The badges we reference.
/// </summary>
/// <remarks>
/// Every badge comes with a level, and EXP gained
/// </remarks>
enum Badge
{
/// <summary>
/// Badge for the amount of games owned
/// </summary>
/// <remarks>
/// The level in this badge is exactly to the amount of games owned
/// E.g. 42 games == level 42 for badge 13
/// (so not the same as shown on the steam profiles)
/// </remarks>
GamesOwned = 13
}
/// <summary>
/// Get all Steam Badges
/// </summary>
/// <param name="steamid64">steamid64 of the user</param>
/// <param name="callback">Callback with the statuscode <see cref="StatusCode"></see> and the result as JSON</param>
private void GetSteamBadges(string steamid64, Action<int, JObject> callback)
{
SteamWebRequest(SteamRequestType.IPlayerService, "GetBadges/v1", steamid64,
(httpCode, jsonResponse) =>
{
callback(httpCode, jsonResponse);
});
}