-
-
Notifications
You must be signed in to change notification settings - Fork 41
/
ClientService.cs
954 lines (817 loc) · 39.3 KB
/
ClientService.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
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Data.Abstractions;
using Data.Context;
using Data.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Serilog.Context;
using SharedLibraryCore.Configuration;
using SharedLibraryCore.Database.Models;
using SharedLibraryCore.Dtos;
using SharedLibraryCore.Helpers;
using SharedLibraryCore.Interfaces;
using static Data.Models.Client.EFClient;
using ILogger = Microsoft.Extensions.Logging.ILogger;
namespace SharedLibraryCore.Services
{
public class ClientService : IEntityService<EFClient>, IResourceQueryHelper<FindClientRequest, FindClientResult>
{
private static readonly Func<DatabaseContext, long, Reference.Game, Task<EFClient>> GetUniqueQuery =
EF.CompileAsyncQuery((DatabaseContext context, long networkId, Reference.Game game) =>
context.Clients
.Select(client => new EFClient
{
ClientId = client.ClientId,
AliasLinkId = client.AliasLinkId,
Level = client.Level,
Connections = client.Connections,
FirstConnection = client.FirstConnection,
LastConnection = client.LastConnection,
Masked = client.Masked,
NetworkId = client.NetworkId,
TotalConnectionTime = client.TotalConnectionTime,
AliasLink = client.AliasLink,
Password = client.Password,
PasswordSalt = client.PasswordSalt,
GameName = client.GameName
})
.FirstOrDefault(client => client.NetworkId == networkId && client.GameName == game)
);
private readonly ApplicationConfiguration _appConfig;
private readonly IDatabaseContextFactory _contextFactory;
private readonly ILogger _logger;
private readonly IGeoLocationService _geoLocationService;
public ClientService(ILogger<ClientService> logger, IDatabaseContextFactory databaseContextFactory,
ApplicationConfiguration appConfig, IGeoLocationService geoLocationService)
{
_contextFactory = databaseContextFactory;
_logger = logger;
_appConfig = appConfig;
_geoLocationService = geoLocationService;
}
public async Task<EFClient> Create(EFClient entity)
{
entity.Name = entity.Name.CapClientName(EFAlias.MAX_NAME_LENGTH);
if (!_appConfig.EnableImplicitAccountLinking)
{
return await HandleNewCreate(entity);
}
await using var context = _contextFactory.CreateContext();
using (LogContext.PushProperty("Server", entity?.CurrentServer?.ToString()))
{
int? linkId = null;
int? aliasId = null;
if (entity.IPAddress != null)
{
var existingAliases = await context.Aliases
.Select(_alias => new { _alias.AliasId, _alias.LinkId, _alias.IPAddress, _alias.Name })
.Where(_alias => _alias.IPAddress == entity.IPAddress)
.ToListAsync();
if (existingAliases.Count > 0)
{
linkId = existingAliases.OrderBy(_alias => _alias.LinkId).First().LinkId;
_logger.LogDebug("[create] client with new GUID {entity} has existing link {linkId}",
entity.ToString(), linkId);
var existingExactAlias = existingAliases.FirstOrDefault(_alias => _alias.Name == entity.Name);
if (existingExactAlias != null)
{
_logger.LogDebug("[create] client with new GUID {entity} has existing alias {aliasId}",
entity.ToString(), existingExactAlias.AliasId);
aliasId = existingExactAlias.AliasId;
}
}
}
var client = new EFClient
{
Level = Permission.User,
FirstConnection = DateTime.UtcNow,
LastConnection = DateTime.UtcNow,
NetworkId = entity.NetworkId,
GameName = (Reference.Game)entity.CurrentServer.GameName
};
_logger.LogDebug("[create] adding {entity} to context", entity.ToString());
// they're just using a new GUID
if (aliasId.HasValue)
{
_logger.LogDebug("[create] setting {entity}'s alias id and linkid to ({aliasId}, {linkId})",
entity.ToString(), aliasId, linkId);
client.CurrentAliasId = aliasId.Value;
client.AliasLinkId = linkId.Value;
}
// link was found but they don't have an exact alias
else if (!aliasId.HasValue && linkId.HasValue)
{
_logger.LogDebug("[create] setting {entity}'s linkid to {linkId}, but creating new alias",
entity.ToString(), linkId);
client.AliasLinkId = linkId.Value;
client.CurrentAlias = new EFAlias
{
Name = entity.Name,
SearchableName = entity.Name.StripColors().ToLower(),
DateAdded = DateTime.UtcNow,
IPAddress = entity.IPAddress,
LinkId = linkId.Value
};
}
// brand new players (supposedly)
else
{
_logger.LogDebug("[create] creating new Link and Alias for {entity}", entity.ToString());
var link = new EFAliasLink();
var alias = new EFAlias
{
Name = entity.Name,
SearchableName = entity.Name.StripColors().ToLower(),
DateAdded = DateTime.UtcNow,
IPAddress = entity.IPAddress,
Link = link
};
client.AliasLink = link;
client.CurrentAlias = alias;
}
context.Clients.Add(client);
await context.SaveChangesAsync();
return client;
}
}
public Task<EFClient> Delete(EFClient entity)
{
throw new NotImplementedException();
}
public Task<IList<EFClient>> Find(Func<EFClient, bool> e)
{
throw new NotImplementedException();
}
public async Task<EFClient> Get(int entityId)
{
await using var context = _contextFactory.CreateContext(false);
var client = await context.Clients
.Select(_client => new EFClient
{
ClientId = _client.ClientId,
GameName = _client.GameName,
AliasLinkId = _client.AliasLinkId,
Level = _client.Level,
Connections = _client.Connections,
FirstConnection = _client.FirstConnection,
LastConnection = _client.LastConnection,
Masked = _client.Masked,
NetworkId = _client.NetworkId,
CurrentAlias = new EFAlias
{
Name = _client.CurrentAlias.Name,
IPAddress = _client.CurrentAlias.IPAddress
},
TotalConnectionTime = _client.TotalConnectionTime,
AliasLink = new EFAliasLink
{
AliasLinkId = _client.AliasLinkId,
Children = _client.AliasLink.Children
},
LinkedAccounts = new Dictionary<int, long>()
{
{_client.ClientId, _client.NetworkId}
}
})
.FirstOrDefaultAsync(_client => _client.ClientId == entityId);
if (client == null)
{
return null;
}
if (!_appConfig.EnableImplicitAccountLinking)
{
return client;
}
var foundClient = new
{
Client = client,
LinkedAccounts = await context.Clients.Where(_client => _client.AliasLinkId == client.AliasLinkId)
.Select(_linkedClient => new
{
_linkedClient.ClientId,
_linkedClient.NetworkId
})
.ToListAsync()
};
foundClient.Client.LinkedAccounts = new Dictionary<int, long>();
// todo: find out the best way to do this
// I'm doing this here because I don't know the best way to have multiple awaits in the query
foreach (var linked in foundClient.LinkedAccounts)
foundClient.Client.LinkedAccounts.Add(linked.ClientId, linked.NetworkId);
return foundClient.Client;
}
public virtual async Task<EFClient> GetUnique(long entityAttribute, object altKey = null)
{
await using var context = _contextFactory.CreateContext(false);
return await GetUniqueQuery(context, entityAttribute, (Reference.Game)altKey);
}
public async Task<EFClient> Update(EFClient temporalClient)
{
if (temporalClient.ClientId < 1)
{
_logger.LogDebug(
"[update] {client} needs to be updated but they do not have a valid client id, ignoring..",
temporalClient.ToString());
// note: we never do anything with the result of this so we can safely return null
return null;
}
await using var context = _contextFactory.CreateContext();
// grab the context version of the entity
var entity = context.Clients
.First(client => client.ClientId == temporalClient.ClientId);
if (temporalClient.LastConnection > entity.LastConnection)
{
entity.LastConnection = temporalClient.LastConnection;
}
if (temporalClient.Connections > entity.Connections)
{
entity.Connections = temporalClient.Connections;
}
entity.Masked = temporalClient.Masked;
if (temporalClient.TotalConnectionTime > entity.TotalConnectionTime)
{
entity.TotalConnectionTime = temporalClient.TotalConnectionTime;
}
if (temporalClient.Password != null)
{
entity.Password = temporalClient.Password;
}
if (temporalClient.PasswordSalt != null)
{
entity.PasswordSalt = temporalClient.PasswordSalt;
}
if (entity.GameName == Reference.Game.UKN && temporalClient.GameName != entity.GameName)
{
entity.GameName = temporalClient.GameName;
}
// update in database
await context.SaveChangesAsync();
return entity.ToPartialClient();
}
/// <summary>
/// find clients matching the given query
/// </summary>
/// <param name="query">query filters</param>
/// <returns></returns>
public async Task<ResourceQueryHelperResult<FindClientResult>> QueryResource(FindClientRequest query)
{
var result = new ResourceQueryHelperResult<FindClientResult>();
await using var context = _contextFactory.CreateContext(false);
IQueryable<Data.Models.Client.EFClient> iqClients = null;
if (!string.IsNullOrEmpty(query.Xuid))
{
var networkId = query.Xuid.ConvertGuidToLong(NumberStyles.HexNumber);
iqClients = context.Clients.Where(_client => _client.NetworkId == networkId);
}
else if (!string.IsNullOrEmpty(query.Name))
{
iqClients = context.Clients
.Where(_client =>
EF.Functions.Like(_client.CurrentAlias.Name.ToLower(), $"%{query.Name.ToLower()}%"));
}
if (query.Direction == SortDirection.Ascending)
{
iqClients = iqClients.OrderBy(_client => _client.LastConnection);
}
else
{
iqClients = iqClients.OrderByDescending(_client => _client.LastConnection);
}
var queryResults = await iqClients
.Select(_client => new FindClientResult
{
ClientId = _client.ClientId,
Xuid = _client.NetworkId.ToString("X"),
Name = _client.CurrentAlias.Name
})
.Skip(query.Offset)
.Take(query.Count)
.ToListAsync();
result.TotalResultCount = await iqClients.CountAsync();
result.Results = queryResults;
result.RetrievedResultCount = queryResults.Count;
return result;
}
private async Task<EFClient> HandleNewCreate(EFClient entity)
{
await using var context = _contextFactory.CreateContext();
using (LogContext.PushProperty("Server", entity.CurrentServer?.ToString()))
{
var existingAlias = await context.Aliases
.Select(alias => new { alias.AliasId, alias.LinkId, alias.IPAddress, alias.Name })
.Where(alias => alias.IPAddress != null && alias.IPAddress == entity.IPAddress &&
alias.Name == entity.Name)
.FirstOrDefaultAsync();
var client = new EFClient
{
Level = Permission.User,
FirstConnection = DateTime.UtcNow,
LastConnection = DateTime.UtcNow,
NetworkId = entity.NetworkId,
GameName = (Reference.Game)entity.CurrentServer.GameName
};
if (existingAlias == null)
{
_logger.LogDebug("[{Method}] creating new Link and Alias for {Entity}", nameof(HandleNewCreate),
entity.ToString());
var link = new EFAliasLink();
var alias = new EFAlias
{
Name = entity.Name,
SearchableName = entity.Name.StripColors().ToLower(),
DateAdded = DateTime.UtcNow,
IPAddress = entity.IPAddress,
Link = link
};
client.CurrentAlias = alias;
client.AliasLink = link;
}
else
{
_logger.LogDebug(
"[{Method}] associating new GUID {Guid} with new exact alias match with linkId {LinkId} for {Entity}",
nameof(HandleNewCreate), entity.GuidString, existingAlias.LinkId, entity.ToString());
var alias = new EFAlias
{
Name = existingAlias.Name,
SearchableName = entity.Name.StripColors().ToLower(),
DateAdded = DateTime.UtcNow,
IPAddress = entity.IPAddress,
LinkId = existingAlias.LinkId
};
client.CurrentAlias = alias;
client.AliasLinkId = existingAlias.LinkId;
}
context.Clients.Add(client);
await context.SaveChangesAsync();
return client;
}
}
private async Task UpdateAlias(string originalName, int? ip, Data.Models.Client.EFClient entity,
DatabaseContext context)
{
{
var name = originalName.CapClientName(EFAlias.MAX_NAME_LENGTH);
// entity is the tracked db context item
// get all aliases by IP address and LinkId
var iqAliases = context.Aliases
.Include(a => a.Link)
// we only want alias that have the same IP address or share a link
.Where(_alias => _alias.IPAddress == ip || _alias.LinkId == entity.AliasLinkId);
var aliases = await iqAliases.ToListAsync();
var currentIPs = aliases.Where(_a2 => _a2.IPAddress != null).Select(_a2 => _a2.IPAddress).Distinct();
var floatingIPAliases = await context.Aliases.Where(_alias => currentIPs.Contains(_alias.IPAddress))
.ToListAsync();
aliases.AddRange(floatingIPAliases);
// see if they have a matching IP + Name but new NetworkId
var existingExactAlias = aliases.OrderBy(_alias => _alias.LinkId)
.FirstOrDefault(a => a.Name == name && a.IPAddress == ip);
var hasExactAliasMatch = existingExactAlias != null;
// if existing alias matches link them
var newAliasLink = existingExactAlias?.Link;
// if no exact matches find the first IP or LinkId that matches
newAliasLink = newAliasLink ?? aliases.OrderBy(_alias => _alias.LinkId).FirstOrDefault()?.Link;
// if no matches are found, use our current one ( it will become permanent )
newAliasLink = newAliasLink ?? entity.AliasLink;
var hasExistingAlias = aliases.Count > 0;
var isAliasLinkUpdated = newAliasLink.AliasLinkId != entity.AliasLink.AliasLinkId;
await context.SaveChangesAsync();
var distinctLinkCount = aliases.Select(_alias => _alias.LinkId).Distinct().Count();
// this happens when the link we found is different than the one we create before adding an IP
if (isAliasLinkUpdated || distinctLinkCount > 1)
{
_logger.LogDebug(
"[updatealias] found a link for {entity} so we are updating link from {oldAliasLinkId} to {newAliasLinkId}",
entity.ToString(), entity.AliasLink.AliasLinkId, newAliasLink.AliasLinkId);
var completeAliasLinkIds = aliases.Select(_item => _item.LinkId)
.Append(entity.AliasLinkId)
.Distinct()
.ToList();
_logger.LogDebug("[updatealias] updating aliasLinks {links} for IP {ip} to {linkId}",
string.Join(',', completeAliasLinkIds), ip, newAliasLink.AliasLinkId);
// update all the clients that have the old alias link
await context.Clients
.Where(_client => completeAliasLinkIds.Contains(_client.AliasLinkId))
.ForEachAsync(_client => _client.AliasLinkId = newAliasLink.AliasLinkId);
// we also need to update all the penalties or they get deleted
// scenario
// link1 joins with ip1
// link2 joins with ip2,
// link2 receives penalty
// link2 joins with ip1
// pre existing link for link2 detected
// link2 is deleted
// link2 penalties are orphaned
await context.Penalties
.Where(_penalty => completeAliasLinkIds.Contains(_penalty.LinkId ?? -1))
.ForEachAsync(_penalty => _penalty.LinkId = newAliasLink.AliasLinkId);
entity.AliasLink = newAliasLink;
entity.AliasLinkId = newAliasLink.AliasLinkId;
// update all previous aliases
await context.Aliases
.Where(_alias => completeAliasLinkIds.Contains(_alias.LinkId))
.ForEachAsync(_alias => _alias.LinkId = newAliasLink.AliasLinkId);
await context.SaveChangesAsync();
// we want to delete the now inactive alias
if (newAliasLink.AliasLinkId != entity.AliasLinkId)
{
context.AliasLinks.Remove(entity.AliasLink);
await context.SaveChangesAsync();
}
}
// the existing alias matches ip and name, so we can just ignore the temporary one
if (hasExactAliasMatch)
{
_logger.LogDebug("[updatealias] {entity} has exact alias match", entity.ToString());
var oldAlias = entity.CurrentAlias;
entity.CurrentAliasId = existingExactAlias.AliasId;
entity.CurrentAlias = existingExactAlias;
await context.SaveChangesAsync();
// the alias is the same so we can just remove it
if (oldAlias.AliasId != existingExactAlias.AliasId && oldAlias.AliasId > 0)
{
await context.Clients
.Where(_client => _client.CurrentAliasId == oldAlias.AliasId)
.ForEachAsync(_client => _client.CurrentAliasId = existingExactAlias.AliasId);
await context.SaveChangesAsync();
if (context.Entry(oldAlias).State != EntityState.Deleted)
{
_logger.LogDebug(
"[updatealias] {entity} has exact alias match, so we're going to try to remove aliasId {aliasId} with linkId {linkId}",
entity.ToString(), oldAlias.AliasId, oldAlias.LinkId);
context.Aliases.Remove(oldAlias);
await context.SaveChangesAsync();
}
}
}
// theres no exact match, but they've played before with the GUID or IP
else
{
_logger.LogDebug("[updatealias] {entity} is using a new alias", entity.ToString());
var newAlias = new EFAlias
{
DateAdded = DateTime.UtcNow,
IPAddress = ip,
LinkId = newAliasLink.AliasLinkId,
Name = name,
SearchableName = name.StripColors().ToLower(),
Active = true
};
entity.CurrentAlias = newAlias;
entity.CurrentAliasId = 0;
await context.SaveChangesAsync();
}
}
}
private async Task UpdateAliasNew(string originalName, int? ip, Data.Models.Client.EFClient entity,
DatabaseContext context)
{
var name = originalName.CapClientName(EFAlias.MAX_NAME_LENGTH);
var existingAliases = await context.Aliases
.Where(alias => alias.Name == name && alias.LinkId == entity.AliasLinkId ||
alias.Name == name && alias.IPAddress != null && alias.IPAddress == ip)
.ToListAsync();
var defaultAlias = existingAliases.FirstOrDefault(alias => alias.IPAddress == null);
var existingExactAlias =
existingAliases.FirstOrDefault(alias => alias.IPAddress != null && alias.IPAddress == ip);
if (defaultAlias != null && existingExactAlias == null)
{
defaultAlias.IPAddress = ip;
entity.CurrentAlias = defaultAlias;
entity.CurrentAliasId = defaultAlias.AliasId;
await context.SaveChangesAsync();
return;
}
if (existingExactAlias != null && entity.AliasLinkId == existingExactAlias.LinkId)
{
entity.CurrentAlias = existingExactAlias;
entity.CurrentAliasId = existingExactAlias.AliasId;
await context.SaveChangesAsync();
_logger.LogDebug(
"[{Method}] client {Client} already has an existing exact alias, so we are not making changes",
nameof(UpdateAliasNew), entity.ToString());
return;
}
_logger.LogDebug("[{Method}] {Entity} is using a new alias", nameof(UpdateAliasNew), entity.ToString());
var newAlias = new EFAlias
{
DateAdded = DateTime.UtcNow,
IPAddress = ip,
LinkId = entity.AliasLinkId,
Name = name,
SearchableName = name.StripColors().ToLower(),
Active = true
};
entity.CurrentAlias = newAlias;
await context.SaveChangesAsync();
entity.CurrentAliasId = newAlias.AliasId;
}
/// <summary>
/// updates the permission level of the given target to the given permission level
/// </summary>
/// <param name="newPermission"></param>
/// <param name="temporalClient"></param>
/// <param name="origin"></param>
/// <returns></returns>
public virtual async Task UpdateLevel(Permission newPermission, EFClient temporalClient, EFClient origin)
{
await using var context = _contextFactory.CreateContext();
var entity = await context.Clients
.Where(client => client.ClientId == temporalClient.ClientId)
.FirstAsync();
_logger.LogInformation("Updating {ClientId} from {OldPermission} to {NewPermission} ",
temporalClient.ClientId, entity.Level, newPermission);
entity.Level = newPermission;
await context.SaveChangesAsync();
temporalClient.Level = newPermission;
}
public async Task UpdateAlias(EFClient temporalClient)
{
await using var context = _contextFactory.CreateContext();
var entity = context.Clients
.Include(c => c.AliasLink)
.Include(c => c.CurrentAlias)
.First(e => e.ClientId == temporalClient.ClientId);
if (_appConfig.EnableImplicitAccountLinking)
{
await UpdateAlias(temporalClient.Name, temporalClient.IPAddress, entity, context);
}
else
{
await UpdateAliasNew(temporalClient.Name, temporalClient.IPAddress, entity, context);
}
temporalClient.CurrentAlias = entity.CurrentAlias;
temporalClient.CurrentAliasId = entity.CurrentAliasId;
temporalClient.AliasLink = entity.AliasLink;
temporalClient.AliasLinkId = entity.AliasLinkId;
}
/// <summary>
/// retrieves the number of times the given client id has been reported
/// </summary>
/// <param name="clientId">client id to search for report counts of</param>
/// <returns></returns>
public async Task<int> GetClientReportCount(int clientId)
{
await using var context = _contextFactory.CreateContext(false);
return await context.Penalties
.Where(_penalty => _penalty.Active)
.Where(_penalty => _penalty.OffenderId == clientId)
.Where(_penalty => _penalty.Type == EFPenalty.PenaltyType.Report)
.CountAsync();
}
/// <summary>
/// indicates if the given clientid can be autoflagged
/// </summary>
/// <param name="clientId"></param>
/// <returns></returns>
public async Task<bool> CanBeAutoFlagged(int clientId)
{
await using var context = _contextFactory.CreateContext(false);
var now = DateTime.UtcNow;
var hasExistingAutoFlag = await context.Penalties
.Where(_penalty => _penalty.Active)
.Where(_penalty => _penalty.OffenderId == clientId)
.Where(_penalty => _penalty.Type == EFPenalty.PenaltyType.Flag)
.Where(_penalty => _penalty.PunisherId == 1)
.Where(_penalty => _penalty.Expires == null || _penalty.Expires > now)
.AnyAsync();
var hasUnflag = await context.Penalties
.Where(_penalty => _penalty.Active)
.Where(_penalty => _penalty.OffenderId == clientId)
.Where(_penalty => _penalty.Type == EFPenalty.PenaltyType.Unflag)
.AnyAsync();
return !hasExistingAutoFlag && !hasUnflag;
}
/// <summary>
/// Unlinks shared GUID account into its own separate account
/// </summary>
/// <param name="clientId"></param>
/// <returns></returns>
public async Task UnlinkClient(int clientId)
{
await using var ctx = _contextFactory.CreateContext();
var newLink = new EFAliasLink { Active = true };
ctx.AliasLinks.Add(newLink);
await ctx.SaveChangesAsync();
var client = await ctx.Clients.Include(_client => _client.CurrentAlias)
.FirstAsync(_client => _client.ClientId == clientId);
client.AliasLinkId = newLink.AliasLinkId;
client.Level = Permission.User;
await ctx.Aliases.Where(_alias =>
_alias.IPAddress == client.CurrentAlias.IPAddress && _alias.IPAddress != null)
.ForEachAsync(_alias => _alias.LinkId = newLink.AliasLinkId);
if (!_appConfig.EnableImplicitAccountLinking)
{
var clientIdsByIp = await ctx.Clients.Where(c =>
client.CurrentAlias.IPAddress != null &&
c.CurrentAlias.IPAddress == client.CurrentAlias.IPAddress)
.Select(c => c.ClientId)
.ToListAsync();
await ctx.Penalties.Where(penalty =>
clientIdsByIp.Contains(penalty.OffenderId)
&& new[]
{
EFPenalty.PenaltyType.Ban, EFPenalty.PenaltyType.TempBan, EFPenalty.PenaltyType.Flag
}.Contains(penalty.Type)
&& penalty.Expires == null)
.ForEachAsync(penalty => penalty.Expires = DateTime.UtcNow);
}
await ctx.SaveChangesAsync();
}
#region ServiceSpecific
public async Task<IList<EFClient>> GetOwners()
{
await using var context = _contextFactory.CreateContext(false);
return await context.Clients
.Where(c => c.Level == Permission.Owner)
.Select(c => c.ToPartialClient())
.ToListAsync();
}
public async Task<bool> HasOwnerAsync(CancellationToken token)
{
await using var context = _contextFactory.CreateContext(false);
return await context.Clients.AnyAsync(client => client.Level == Permission.Owner, token);
}
/// <summary>
/// retrieves the number of owners
/// (client level is owner)
/// </summary>
/// <returns></returns>
public virtual async Task<int> GetOwnerCount()
{
await using var context = _contextFactory.CreateContext(false);
return await context.Clients
.CountAsync(_client => _client.Level == Permission.Owner);
}
public async Task<EFClient> GetClientForLogin(int clientId)
{
await using var context = _contextFactory.CreateContext(false);
return await context.Clients
.Select(client => new EFClient
{
NetworkId = client.NetworkId,
ClientId = client.ClientId,
CurrentAlias = new EFAlias
{
Name = client.CurrentAlias.Name
},
Password = client.Password,
PasswordSalt = client.PasswordSalt,
GameName = client.GameName,
Level = client.Level
})
.FirstAsync(client => client.ClientId == clientId);
}
public async Task<List<EFClient>> GetPrivilegedClients(bool includeName = true)
{
await using var context = _contextFactory.CreateContext(false);
var iqClients = from client in context.Clients.AsNoTracking()
where client.Level >= Permission.Trusted
where client.Active
select new EFClient
{
AliasLinkId = client.AliasLinkId,
CurrentAlias = client.CurrentAlias,
ClientId = client.ClientId,
Level = client.Level,
Password = client.Password,
PasswordSalt = client.PasswordSalt,
NetworkId = client.NetworkId,
LastConnection = client.LastConnection,
Masked = client.Masked,
GameName = client.GameName
};
return await iqClients.ToListAsync();
}
public async Task<IList<PlayerInfo>> FindClientsByIdentifier(string identifier)
{
var trimmedIdentifier = identifier?.Trim();
if (trimmedIdentifier == null || trimmedIdentifier.Length < _appConfig.MinimumNameLength)
{
return new List<PlayerInfo>();
}
await using var context = _contextFactory.CreateContext(false);
long? networkId = null;
try
{
networkId = trimmedIdentifier.ConvertGuidToLong(NumberStyles.HexNumber);
}
catch
{
// ignored
}
var ipAddress = trimmedIdentifier.ConvertToIP();
var iqLinkIds = context.Aliases.Where(_alias => _alias.Active);
// we want to query for the IP Address
if (ipAddress != null && trimmedIdentifier.Split('.').Length == 3)
{
iqLinkIds = iqLinkIds.Where(_alias => _alias.IPAddress == ipAddress);
}
// want to find them by name (wildcard)
else
{
iqLinkIds = iqLinkIds.Where(_alias => EF.Functions.Like(_alias.SearchableName ?? _alias.Name.ToLower(),
$"%{trimmedIdentifier.ToLower()}%") || EF.Functions.Like(_alias.SearchableIPAddress, $"{trimmedIdentifier}%"));
}
var linkIds = await iqLinkIds
.Select(_alias => _alias.LinkId)
.ToListAsync();
// get all the clients that match the alias link or the network id
var iqClients = context.Clients
.Where(_client => _client.Active);
var match = Regex.Match(trimmedIdentifier ?? "", "\"(.+)\"");
if (match.Success)
{
iqClients = iqClients.Where(client =>
client.CurrentAlias.SearchableName.ToLower().Equals(match.Groups[1].ToString().ToLower()));
}
else
{
iqClients = iqClients.Where(client => networkId == client.NetworkId || linkIds.Contains(client.AliasLinkId));
}
if (ipAddress is not null && !_appConfig.EnableImplicitAccountLinking)
{
iqClients = iqClients.Union(context.Clients.Where(client => client.CurrentAlias.IPAddress == ipAddress));
}
// we want to project our results
var iqClientProjection = iqClients.OrderByDescending(client => client.LastConnection)
.Select(client => new PlayerInfo
{
Name = client.CurrentAlias.Name,
LevelInt = (int)client.Level,
LastConnection = client.LastConnection,
ClientId = client.ClientId,
IPAddress = client.CurrentAlias.IPAddress.HasValue
? client.CurrentAlias.SearchableIPAddress
: "",
Game = client.GameName
});
var clients = await iqClientProjection.ToListAsync();
// this is so we don't try to evaluate this in the linq to entities query
foreach (var client in clients)
{
client.Level = ((Permission)client.LevelInt).ToLocalizedLevelName();
}
return clients;
}
public async Task<int> GetTotalClientsAsync()
{
await using var context = _contextFactory.CreateContext(false);
return await context.Clients
.CountAsync();
}
/// <summary>
/// Returns the number of clients seen today
/// </summary>
/// <returns></returns>
public async Task<int> GetRecentClientCount()
{
await using var context = _contextFactory.CreateContext(false);
var startOfPeriod = DateTime.UtcNow.AddHours(-24);
var iqQuery = context.Clients.Where(_client => _client.LastConnection >= startOfPeriod);
return await iqQuery.CountAsync();
}
/// <summary>
/// gets the 10 most recently added clients to IW4MAdmin
/// </summary>
/// <returns></returns>
public async Task<IList<PlayerInfo>> GetRecentClients(PaginationRequest request)
{
var startOfPeriod = DateTime.UtcNow.AddHours(-24);
await using var context = _contextFactory.CreateContext(false);
var iqClients = context.Clients
.Where(client => client.CurrentAlias.IPAddress != null)
.Where(client => client.FirstConnection >= startOfPeriod)
.OrderByDescending(client => client.FirstConnection)
.Select(client => new PlayerInfo
{
ClientId = client.ClientId,
Name = client.CurrentAlias.Name,
IPAddress = client.CurrentAlias.IPAddress.ConvertIPtoString(),
LastConnection = client.FirstConnection
})
.Skip(request.Offset)
.Take(request.Count);
var clientList = await iqClients.ToListAsync();
foreach (var client in clientList)
{
client.GeoLocationInfo = await _geoLocationService.Locate(client.IPAddress);
}
return clientList;
}
public async Task<string> GetClientNameById(int clientId)
{
await using var context = _contextFactory.CreateContext();
var match = await context.Clients.Select(client => new { client.CurrentAlias.Name, client.ClientId })
.FirstOrDefaultAsync(client => client.ClientId == clientId);
return match?.Name;
}
#endregion
}
}