-
-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathUtilities.cs
1432 lines (1226 loc) · 51.8 KB
/
Utilities.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.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Data.Models;
using Humanizer;
using Humanizer.Localisation;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using SharedLibraryCore.Configuration;
using SharedLibraryCore.Database.Models;
using SharedLibraryCore.Dtos.Meta;
using SharedLibraryCore.Events.Game;
using SharedLibraryCore.Events.Server;
using SharedLibraryCore.Exceptions;
using SharedLibraryCore.Helpers;
using SharedLibraryCore.Interfaces;
using SharedLibraryCore.Interfaces.Events;
using SharedLibraryCore.Localization;
using SharedLibraryCore.RCon;
using static System.Threading.Tasks.Task;
using static SharedLibraryCore.Server;
using static Data.Models.Client.EFClient;
using static Data.Models.EFPenalty;
using ILogger = Microsoft.Extensions.Logging.ILogger;
namespace SharedLibraryCore
{
public static class Utilities
{
// note: this is only to be used by classes not created by dependency injection
public static ILogger DefaultLogger { get; set; }
#if DEBUG == true
public static string OperatingDirectory => $"{Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)}{Path.DirectorySeparatorChar}";
#else
public static string OperatingDirectory =>
$"{Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)}{Path.DirectorySeparatorChar}..{Path.DirectorySeparatorChar}";
#endif
public static Encoding EncodingType;
public static Layout CurrentLocalization = new Layout(new Dictionary<string, string>());
public static TimeSpan DefaultCommandTimeout { get; set; } = new(0, 0, IsDevelopment ? 360 : 25);
public static char[] DirectorySeparatorChars = { '\\', '/' };
public static char CommandPrefix { get; set; } = '!';
public static string ToStandardFormat(this DateTime? time) => time?.ToString("yyyy-MM-dd HH:mm:ss UTC");
public static string ToStandardFormat(this DateTime time) => time.ToString("yyyy-MM-dd HH:mm:ss UTC");
public static EFClient IW4MAdminClient(Server server = null)
{
return new EFClient
{
ClientId = 1,
State = EFClient.ClientState.Connected,
Level = Permission.Console,
CurrentServer = server,
CurrentAlias = new EFAlias
{
Name = "IW4MAdmin"
},
AdministeredPenalties = new List<EFPenalty>()
};
}
public static EFClient AsConsoleClient(this IGameServer server)
{
return new EFClient
{
ClientId = 1,
State = EFClient.ClientState.Connected,
Level = Permission.Console,
CurrentServer = server as Server,
CurrentAlias = new EFAlias
{
Name = "IW4MAdmin"
},
AdministeredPenalties = new List<EFPenalty>()
};
}
/// <summary>
/// fallback id for world events
/// </summary>
public const long WORLD_ID = -1;
public static Dictionary<Permission, string> PermissionLevelOverrides { get; } = new ();
//Remove words from a space delimited string
public static string RemoveWords(this string str, int num)
{
if (str == null || str.Length == 0)
{
return "";
}
var newStr = string.Empty;
var tmp = str.Split(' ');
for (var i = 0; i < tmp.Length; i++)
if (i >= num)
{
newStr += tmp[i] + ' ';
}
return newStr;
}
/// <summary>
/// caps client name to the specified character length - 3
/// and adds ellipses to the end of the remaining client name
/// </summary>
/// <param name="name">client name</param>
/// <param name="maxLength">max number of characters for the name</param>
/// <returns></returns>
public static string CapClientName(this string name, int maxLength)
{
if (string.IsNullOrWhiteSpace(name))
{
return "-";
}
return name.Length > maxLength ? $"{name[..(maxLength - 3)]}..." : name;
}
public static Permission MatchPermission(string str)
{
var lookingFor = str.ToLower();
for (var perm = Permission.User; perm < Permission.Console; perm++)
if (lookingFor.Contains(perm.ToString().ToLower())
|| lookingFor.Contains(CurrentLocalization
.LocalizationIndex[$"GLOBAL_PERMISSION_{perm.ToString().ToUpper()}"].ToLower()))
{
return perm;
}
return Permission.Banned;
}
/// <summary>
/// Remove all IW Engine color codes
/// </summary>
/// <param name="str">String containing color codes</param>
/// <returns></returns>
public static string StripColors(this string str)
{
if (str == null)
{
return "";
}
str = Regex.Replace(str, @"(\^+((?![a-z]|[A-Z]).){0,1})+", "");
str = Regex.Replace(str, @"\(Color::(.{1,16})\)", "");
return str;
}
/// <summary>
/// returns a "fixed" string that prevents message truncation in IW4 (and probably other Q3 clients)
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string FixIW4ForwardSlash(this string str)
{
return str.Replace("//", "/ /");
}
public static string RemoveDiacritics(this string text)
{
var normalizedString = text.Normalize(NormalizationForm.FormD);
var stringBuilder = new StringBuilder();
foreach (var c in from c in normalizedString.EnumerateRunes()
let unicodeCategory = Rune.GetUnicodeCategory(c)
where unicodeCategory != UnicodeCategory.NonSpacingMark
select c)
{
stringBuilder.Append(c);
}
return stringBuilder.ToString().Normalize(NormalizationForm.FormC);
}
public static string FormatMessageForEngine(this string str, IRConParserConfiguration config)
{
if (config == null || string.IsNullOrEmpty(str))
{
return str;
}
var output = str;
var colorCodeMatches = Regex.Matches(output, @"\(Color::(\w{1,16})\)",
RegexOptions.IgnoreCase | RegexOptions.Compiled);
foreach (var match in colorCodeMatches.Where(m => m.Success))
{
var key = match.Groups[1].ToString();
output = output.Replace(match.Value, config.ColorCodeMapping.TryGetValue(key, out var code) ? code : "");
}
if (config.ShouldRemoveDiacritics)
{
output = output.RemoveDiacritics();
}
return output.FixIW4ForwardSlash();
}
private static readonly IList<string> ZmGameTypes = new[]
{ "zclassic", "zstandard", "zcleansed", "zgrief", "zom", "cmp" };
/// <summary>
/// indicates if the given server is running a zombie game mode
/// </summary>
/// <param name="server"></param>
/// <returns></returns>
public static bool IsZombieServer(this Server server)
{
return new[] { Game.T4, Game.T5, Game.T6 }.Contains(server.GameName) &&
ZmGameTypes.Contains(server.Gametype.ToLower());
}
public static bool IsCodGame(this Server server)
{
return server.RconParser?.RConEngine == "COD";
}
/// <summary>
/// Get the color key corresponding to a given user level
/// </summary>
/// <param name="level">Specified player level</param>
/// <param name="localizedLevel"></param>
/// <returns></returns>
public static string ConvertLevelToColor(Permission level, string localizedLevel)
{
// todo: make configurable
var colorCode = level switch
{
Permission.Banned => "Red",
Permission.Flagged => "Map",
Permission.Owner => "Accent",
Permission.User => "Yellow",
Permission.Trusted => "Green",
_ => "Pink"
};
return $"(Color::{colorCode}){localizedLevel ?? level.ToString()}";
}
public static string ToLocalizedLevelName(this Permission permission)
{
var localized =
CurrentLocalization.LocalizationIndex[$"GLOBAL_PERMISSION_{permission.ToString().ToUpper()}"];
return PermissionLevelOverrides.ContainsKey(permission) && PermissionLevelOverrides[permission] != permission.ToString()
? PermissionLevelOverrides[permission]
: localized;
}
public static async Task<string> ProcessMessageToken(this Server server, IList<MessageToken> tokens, string str)
{
var RegexMatches = Regex.Matches(str, @"\{\{[A-Z]+\}\}", RegexOptions.IgnoreCase);
foreach (Match M in RegexMatches)
{
var Match = M.Value;
var Identifier = M.Value.Substring(2, M.Length - 4);
var found = tokens.FirstOrDefault(t => t.Name.ToLower() == Identifier.ToLower());
if (found != null)
{
str = str.Replace(Match, await found.ProcessAsync(server));
}
}
return str;
}
public static bool IsBroadcastCommand(this string str, string broadcastCommandPrefix)
{
return str.StartsWith(broadcastCommandPrefix);
}
/// <summary>
/// Get the full gametype name
/// </summary>
/// <param name="input">Shorthand gametype reported from server</param>
/// <returns></returns>
public static string GetLocalizedGametype(string input)
{
switch (input)
{
case "dm":
return "Deathmatch";
case "war":
return "Team Deathmatch";
case "koth":
return "Headquarters";
case "ctf":
return "Capture The Flag";
case "dd":
return "Demolition";
case "dom":
return "Domination";
case "sab":
return "Sabotage";
case "sd":
return "Search & Destroy";
case "vip":
return "Very Important Person";
case "gtnw":
return "Global Thermonuclear War";
case "oitc":
return "One In The Chamber";
case "arena":
return "Arena";
case "dzone":
return "Drop Zone";
case "gg":
return "Gun Game";
case "snipe":
return "Sniping";
case "ss":
return "Sharp Shooter";
case "m40a3":
return "M40A3";
case "fo":
return "Face Off";
case "dmc":
return "Deathmatch Classic";
case "killcon":
return "Kill Confirmed";
case "oneflag":
return "One Flag CTF";
default:
return input;
}
}
public static long ConvertGuidToLong(this string str, NumberStyles numberStyle, long? fallback = null)
{
return ConvertGuidToLong(str, numberStyle, true, fallback);
}
/// <summary>
/// converts a string to numerical guid
/// </summary>
/// <param name="str">source string for guid</param>
/// <param name="numberStyle">how to parse the guid</param>
/// <param name="fallback">value to use if string is empty</param>
/// <param name="convertSigned">convert signed values to unsigned</param>
/// <returns></returns>
public static long ConvertGuidToLong(this string str, NumberStyles numberStyle, bool convertSigned, long? fallback = null)
{
// added for source games that provide the steam ID
var match = Regex.Match(str, @"^STEAM_(\d):(\d):(\d+)$");
if (match.Success)
{
var x = int.Parse(match.Groups[1].ToString());
var y = int.Parse(match.Groups[2].ToString());
var z = long.Parse(match.Groups[3].ToString());
return z * 2 + 0x0110000100000000 + y;
}
str = str.Substring(0, Math.Min(str.Length, str.StartsWith("-") ? 20 : 19));
var parsableAsNumber = Regex.Match(str, @"([A-F]|[a-f]|[0-9])+").Value;
if (string.IsNullOrWhiteSpace(str) && fallback.HasValue)
{
return fallback.Value;
}
long id;
if (!string.IsNullOrEmpty(parsableAsNumber))
{
if (numberStyle == NumberStyles.Integer)
{
long.TryParse(str, numberStyle, CultureInfo.InvariantCulture, out id);
if (id < 0 && convertSigned)
{
id = (uint)id;
}
}
else
{
long.TryParse(str.Length > 16 ? str.Substring(0, 16) : str, numberStyle,
CultureInfo.InvariantCulture, out id);
}
}
else
{
// this is a special case for when a real guid is not provided, so we generated it from another source
id = str.GenerateGuidFromString();
}
if (id == 0)
{
throw new FormatException($"Could not parse client GUID - {str}");
}
return id;
}
/// <summary>
/// determines if the guid provided appears to be a bot guid
/// "1277538174" - (Pluto?)WaW (T4)
/// </summary>
/// <param name="guid">value of the guid</param>
/// <returns>true if is bot guid, otherwise false</returns>
public static bool IsBotGuid(this string guid)
{
return guid.Contains("bot") || guid == "0" || guid == "1277538174";
}
/// <summary>
/// generates a numerical hashcode from a string value
/// </summary>
/// <param name="value">value string</param>
/// <returns></returns>
public static long GenerateGuidFromString(this string value)
{
return string.IsNullOrEmpty(value) ? -1 : GetStableHashCode(value.StripColors());
}
/// https://stackoverflow.com/questions/36845430/persistent-hashcode-for-strings
public static int GetStableHashCode(this string str)
{
unchecked
{
var hash1 = 5381;
var hash2 = hash1;
for (var i = 0; i < str.Length && str[i] != '\0'; i += 2)
{
hash1 = ((hash1 << 5) + hash1) ^ str[i];
if (i == str.Length - 1 || str[i + 1] == '\0')
{
break;
}
hash2 = ((hash2 << 5) + hash2) ^ str[i + 1];
}
return hash1 + hash2 * 1566083941;
}
}
public static int? ConvertToIP(this string str)
{
var success = IPAddress.TryParse(str, out var ip);
return success && ip.GetAddressBytes().Count(_byte => _byte == 0) != 4
? BitConverter.ToInt32(ip.GetAddressBytes(), 0)
: null;
}
public static string ConvertIPtoString(this int? ip)
{
return !ip.HasValue ? "" : new IPAddress(BitConverter.GetBytes(ip.Value)).ToString();
}
public static Game GetGame(string gameName)
{
if (string.IsNullOrEmpty(gameName))
{
return Game.UKN;
}
if (gameName.Contains("IW4"))
{
return Game.IW4;
}
if (gameName.Contains("CoD4"))
{
return Game.IW3;
}
if (gameName.Contains("COD_WaW"))
{
return Game.T4;
}
if (gameName.Contains("T5"))
{
return Game.T5;
}
if (gameName.Contains("IW5"))
{
return Game.IW5;
}
if (gameName.Contains("COD_T6_S"))
{
return Game.T6;
}
return Game.UKN;
}
public static TimeSpan ParseTimespan(this string input)
{
var expressionMatch = Regex.Match(input, @"([0-9]+)(\w+)");
if (!expressionMatch.Success) // fallback to default tempban length of 1 hour
{
return new TimeSpan(1, 0, 0);
}
var lengthDenote = expressionMatch.Groups[2].ToString()[0];
var length = int.Parse(expressionMatch.Groups[1].ToString());
var loc = CurrentLocalization.LocalizationIndex;
if (lengthDenote == char.ToLower(loc["GLOBAL_TIME_MINUTES"][0]))
{
return new TimeSpan(0, length, 0);
}
if (lengthDenote == char.ToLower(loc["GLOBAL_TIME_HOURS"][0]))
{
return new TimeSpan(length, 0, 0);
}
if (lengthDenote == char.ToLower(loc["GLOBAL_TIME_DAYS"][0]))
{
return new TimeSpan(length, 0, 0, 0);
}
if (lengthDenote == char.ToLower(loc["GLOBAL_TIME_WEEKS"][0]))
{
return new TimeSpan(length * 7, 0, 0, 0);
}
if (lengthDenote == char.ToLower(loc["GLOBAL_TIME_YEARS"][0]))
{
return new TimeSpan(length * 365, 0, 0, 0);
}
return new TimeSpan(1, 0, 0);
}
public static bool HasPermission<TEntity, TPermission>(this IEnumerable<string> permissionsSet, TEntity entity,
TPermission permission) where TEntity : Enum where TPermission : Enum
{
if (permissionsSet == null)
{
return false;
}
var requiredPermission = $"{entity.ToString()}.{permission.ToString()}";
var hasAllPermissions = permissionsSet.Any(p => p.Equals("*"));
var permissionCheckResult = permissionsSet.Select(p =>
{
if (p.Equals(requiredPermission, StringComparison.InvariantCultureIgnoreCase))
{
return true;
}
if (p.Equals($"-{requiredPermission}", StringComparison.InvariantCultureIgnoreCase))
{
return false;
}
return (bool?)null;
}).ToList();
var permissionNegated = permissionCheckResult.Any(result => result.HasValue && !result.Value);
if (permissionNegated)
{
return false;
}
return hasAllPermissions || permissionCheckResult.Any(result => result.HasValue && result.Value);
}
public static bool HasPermission<TEntity, TPermission>(this ApplicationConfiguration appConfig,
Permission permissionLevel, TEntity entity,
TPermission permission) where TEntity : Enum where TPermission : Enum
{
return appConfig.PermissionSets.ContainsKey(permissionLevel.ToString()) &&
HasPermission(appConfig.PermissionSets[permissionLevel.ToString()], entity, permission);
}
/// <summary>
/// returns a list of penalty types that should be shown across all profiles
/// </summary>
/// <returns></returns>
public static PenaltyType[] LinkedPenaltyTypes()
{
return new[]
{
PenaltyType.Ban,
PenaltyType.Unban,
PenaltyType.TempBan,
PenaltyType.Flag,
PenaltyType.Unflag
};
}
/// <summary>
/// Helper extension that determines if a user is a privileged client
/// </summary>
/// <param name="p"></param>
/// <returns></returns>
public static bool IsPrivileged(this EFClient p)
{
return p.Level > Permission.Flagged;
}
/// <summary>
/// prompt user to answer a yes/no question
/// </summary>
/// <param name="question">question to prompt the user with</param>
/// <param name="description">description of the question's value</param>
/// <param name="defaultValue">default value to set if no input is entered</param>
/// <returns></returns>
public static bool PromptBool(this string question, string description = null, bool defaultValue = true)
{
Console.Write($"{question}?{(string.IsNullOrEmpty(description) ? " " : $" ({description}) ")}[y/n]: ");
var response = Console.ReadLine()?.ToLower().FirstOrDefault();
return response != 0 ? response == 'y' : defaultValue;
}
/// <summary>
/// prompt user to make a selection
/// </summary>
/// <typeparam name="T">type of selection</typeparam>
/// <param name="question">question to prompt the user with</param>
/// <param name="defaultValue">default value to set if no input is entered</param>
/// <param name="description">description of the question's value</param>
/// <param name="selections">array of possible selections (should be able to convert to string)</param>
/// <returns></returns>
public static Tuple<int, T> PromptSelection<T>(this string question, T defaultValue, string description = null,
params T[] selections)
{
var hasDefault = false;
if (defaultValue != null)
{
hasDefault = true;
selections = new[] { defaultValue }.Union(selections).ToArray();
}
Console.WriteLine($"{question}{(string.IsNullOrEmpty(description) ? "" : $" [{description}:]")}");
Console.WriteLine(new string('=', 52));
for (var index = 0; index < selections.Length; index++)
Console.WriteLine($"{(hasDefault ? index : index + 1)}] {selections[index]}");
Console.WriteLine(new string('=', 52));
var selectionIndex = PromptInt(CurrentLocalization.LocalizationIndex["SETUP_PROMPT_MAKE_SELECTION"], null,
hasDefault ? 0 : 1, selections.Length, hasDefault ? 0 : null);
if (!hasDefault)
{
selectionIndex--;
}
var selection = selections[selectionIndex];
return Tuple.Create(selectionIndex, selection);
}
/// <summary>
/// prompt user to enter a number
/// </summary>
/// <param name="question">question to prompt with</param>
/// <param name="maxValue">maximum value to allow</param>
/// <param name="minValue">minimum value to allow</param>
/// <param name="defaultValue">default value to set the return value to</param>
/// <param name="description">a description of the question's value</param>
/// <returns>integer from user's input</returns>
public static int PromptInt(this string question, string description = null, int minValue = 0,
int maxValue = int.MaxValue, int? defaultValue = null)
{
Console.Write(
$"{question}{(string.IsNullOrEmpty(description) ? "" : $" ({description})")}{(defaultValue == null ? "" : $" [{CurrentLocalization.LocalizationIndex["SETUP_PROMPT_DEFAULT"]} {defaultValue.Value.ToString()}]")}: ");
int response;
string InputOrDefault()
{
var input = Console.ReadLine();
return string.IsNullOrEmpty(input) && defaultValue != null ? defaultValue.ToString() : input;
}
while (!int.TryParse(InputOrDefault(), out response) ||
response < minValue ||
response > maxValue)
{
var range = "";
if (minValue != 0 || maxValue != int.MaxValue)
{
range = $" [{minValue}-{maxValue}]";
}
Console.Write($"{CurrentLocalization.LocalizationIndex["SETUP_PROMPT_INT"]}{range}: ");
}
return response;
}
/// <summary>
/// prompt use to enter a string response
/// </summary>
/// <param name="question">question to prompt with</param>
/// <param name="description">description of the question's value</param>
/// <param name="defaultValue">default value to set the return value to</param>
/// <returns></returns>
public static string PromptString(this string question, string description = null, string defaultValue = null)
{
string InputOrDefault()
{
var input = Console.ReadLine();
return string.IsNullOrEmpty(input) && defaultValue != null ? defaultValue : input;
}
string response;
do
{
Console.Write(
$"{question}{(string.IsNullOrEmpty(description) ? "" : $" ({description})")}{(defaultValue == null ? "" : $" [{CurrentLocalization.LocalizationIndex["SETUP_PROMPT_DEFAULT"]} {defaultValue}]")}: ");
response = InputOrDefault();
} while (string.IsNullOrWhiteSpace(response) && response != defaultValue);
return response;
}
public static Dictionary<string, string> DictionaryFromKeyValue(this string eventLine)
{
var values = eventLine[1..].Split('\\');
Dictionary<string, string> dict = new();
if (values.Length <= 1)
{
return dict;
}
for (var i = values.Length % 2 == 0 ? 0 : 1; i < values.Length; i += 2)
{
if (!dict.ContainsKey(values[i]))
{
dict.Add(values[i], values[i + 1]);
}
}
return dict;
}
/* https://loune.net/2017/06/running-shell-bash-commands-in-net-core/ */
public static string GetCommandLine(int pId)
{
var cmdProcess = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = $"/c wmic process where processid={pId} get CommandLine",
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
}
};
cmdProcess.Start();
cmdProcess.WaitForExit();
var cmdLine = cmdProcess.StandardOutput.ReadToEnd().Split("\r\n", StringSplitOptions.RemoveEmptyEntries);
cmdProcess.Dispose();
return cmdLine.Length > 1 ? cmdLine[1] : cmdLine[0];
}
/// <summary>
/// indicates if the given log path is a remote (http) uri
/// </summary>
/// <param name="log"></param>
/// <returns></returns>
public static bool IsRemoteLog(this string log)
{
return (log ?? "").StartsWith("http");
}
public static string ToBase64UrlSafeString(this string src)
{
return Convert.ToBase64String(src.Select(c => Convert.ToByte(c)).ToArray()).Replace('+', '-')
.Replace('/', '_');
}
public static async Task<Dvar<T>> GetDvarAsync<T>(this Server server, string dvarName,
T fallbackValue = default, CancellationToken token = default)
{
return await server.RconParser.GetDvarAsync(server.RemoteConnection, dvarName, fallbackValue, token);
}
public static async Task<Dvar<T>> GetDvarAsync<T>(this Server server, string dvarName,
T fallbackValue = default)
{
return await GetDvarAsync(server, dvarName, fallbackValue, default);
}
public static async Task<Dvar<T>> GetMappedDvarValueOrDefaultAsync<T>(this Server server, string dvarName,
string infoResponseName = null, IDictionary<string, string> infoResponse = null,
T overrideDefault = default, CancellationToken token = default)
{
// todo: unit test this
var mappedKey = server.RconParser.GetOverrideDvarName(dvarName);
var defaultValue = server.RconParser.GetDefaultDvarValue<T>(mappedKey) ?? overrideDefault;
var foundKey = infoResponse?.Keys
.Where(_key => new[] { mappedKey, dvarName, infoResponseName ?? dvarName }.Contains(_key))
.FirstOrDefault();
if (!string.IsNullOrEmpty(foundKey))
{
return new Dvar<T>
{
Value = (T)Convert.ChangeType(infoResponse[foundKey], typeof(T)),
Name = foundKey
};
}
return await server.GetDvarAsync(mappedKey, defaultValue, token: token);
}
public static async Task SetDvarAsync(this Server server, string dvarName, object dvarValue,
CancellationToken token)
{
await server.RconParser.SetDvarAsync(server.RemoteConnection, dvarName, dvarValue, token);
}
public static async Task SetDvarAsync(this Server server, string dvarName, object dvarValue)
{
await SetDvarAsync(server, dvarName, dvarValue, default);
}
public static async Task<string[]> ExecuteCommandAsync(this Server server, string commandName,
CancellationToken token)
{
var response = await server.RconParser.ExecuteCommandAsync(server.RemoteConnection, commandName, token);
server.Manager.QueueEvent(new ServerCommandExecuteEvent
{
Server = server,
Source = server,
Command = commandName,
Output = response
});
return response;
}
public static async Task<string[]> ExecuteCommandAsync(this Server server, string commandName)
{
return await ExecuteCommandAsync(server, commandName, default);
}
public static async Task<IStatusResponse> GetStatusAsync(this Server server, CancellationToken token)
{
try
{
var response = await server.RconParser.GetStatusAsync(server.RemoteConnection, token);
server.Manager.QueueEvent(new ServerStatusReceiveEvent
{
Response = response
});
return response;
}
catch (TaskCanceledException)
{
return null;
}
}
/// <summary>
/// Retrieves the key value pairs for server information usually checked after map rotation
/// </summary>
/// <param name="server"></param>
/// <param name="delay">How long to wait after the map has rotated to query</param>
/// <returns></returns>
public static async Task<IDictionary<string, string>> GetInfoAsync(this Server server, TimeSpan? delay = null)
{
if (delay != null)
{
await Delay(delay.Value);
}
var response = await server.RemoteConnection.SendQueryAsync(StaticHelpers.QueryType.GET_INFO);
var combinedResponse = response.Length > 1
? string.Join('\\', response.Where(r => r.Length > 0 && r[0] == '\\'))
: response[0];
return combinedResponse.DictionaryFromKeyValue();
}
public static double GetVersionAsDouble()
{
var version = Assembly.GetCallingAssembly().GetName().Version.ToString();
version = version.Replace(".", "");
return double.Parse(version) / 1000.0;
}
public static string GetVersionAsString()
{
return Assembly.GetCallingAssembly().GetName().Version.ToString();
}
public static string FormatExt(this string input, params object[] values)
{
var matches = Regex.Matches(Regex.Unescape(input), @"{{\w+}}");
var output = input;
var index = 0;
foreach (Match match in matches)
{
output = output.Replace(match.Value, $"{{{index.ToString()}}}");
index++;
}
try
{
return string.Format(output, values);
}
catch
{
return input;
}
}
/// <summary>
/// https://stackoverflow.com/questions/8113546/how-to-determine-whether-an-ip-address-in-private/39120248
/// An extension method to determine if an IP address is internal, as specified in RFC1918
/// </summary>
/// <param name="toTest">The IP address that will be tested</param>
/// <returns>Returns true if the IP is internal, false if it is external</returns>
public static bool IsInternal(this IPAddress toTest)
{
if (toTest.ToString().StartsWith("127.0.0"))
{
return true;
}
var bytes = toTest.GetAddressBytes();
switch (bytes[0])
{
case 0:
return bytes[1] == 0 && bytes[2] == 0 && bytes[3] == 0;
case 10:
return true;
case 172:
return bytes[1] < 32 && bytes[1] >= 16;
case 192:
return bytes[1] == 168;
default:
return false;
}
}
/// <summary>
/// retrieves the external IP address of the current running machine
/// </summary>
/// <returns></returns>
public static async Task<string> GetExternalIP()
{
try
{
using var wc = new HttpClient();
return await wc.GetStringAsync("https://api.ipify.org");
}
catch
{
return null;
}
}
/// <summary>
/// Determines if the given message is a quick message
/// </summary>
/// <param name="message"></param>
/// <returns>true if the </returns>
public static bool IsQuickMessage(this string message)
{
return Regex.IsMatch(message, @"^\u0014(?:\w|_|!|\s)+$");
}
/// <summary>
/// trims new line and whitespace from string