-
Notifications
You must be signed in to change notification settings - Fork 90
Expand file tree
/
Copy pathDataProviderService.cs
More file actions
811 lines (691 loc) · 36.7 KB
/
DataProviderService.cs
File metadata and controls
811 lines (691 loc) · 36.7 KB
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
using EddiConfigService;
using EddiDataDefinitions;
using EddiSpanshService;
using EddiStarMapService;
using JetBrains.Annotations;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Utilities;
[assembly: InternalsVisibleTo( "Tests" )]
namespace EddiDataProviderService
{
//github.com/ <summary>Access data services. Prefer our cache and local database wherever possible.</summary>
public class DataProviderService
{
private readonly StarMapService edsmService;
internal readonly SpanshService spanshService;
internal readonly StarSystemSqLiteRepository starSystemRepository;
private readonly FactionCache factionCache;
private readonly StarSystemCache starSystemCache;
public readonly CancellationTokenSource cts = new CancellationTokenSource();
public static bool unitTesting;
private DataProviderService ( StarMapService edsmService = null,
SpanshService spanshService = null, StarSystemSqLiteRepository starSystemRepository = null )
{
factionCache = new FactionCache( 3600 ); // Keep a cache of factions for 1 hour
starSystemCache = new StarSystemCache( 300 ); // Keep a cache of star systems for 5 minutes
this.edsmService = edsmService;
this.spanshService = spanshService;
this.starSystemRepository = starSystemRepository;
}
public static DataProviderService Create ( StarMapService newEdsmService = null,
SpanshService newSpanshService = null, StarSystemSqLiteRepository newStarSystemRepository = null )
{
return new DataProviderService(
newEdsmService ?? new StarMapService(),
newSpanshService ?? new SpanshService(),
newStarSystemRepository ?? StarSystemSqLiteRepository.Create( unitTesting )
);
}
public async Task<List<string>> GetTypeAheadSystemsAsync ( string input, CancellationToken cancellationToken )
{
// Prefer type ahead system names for star systems we've visited
var localSystemNames = await starSystemRepository.GetStarSystemNamesAsync( input, cancellationToken ).ConfigureAwait( false );
localSystemNames = localSystemNames
.OrderBy( k => k.LevenshteinDistance( input, StringComparison.CurrentCultureIgnoreCase ) )
.ToList();
if ( localSystemNames.Count >= 10 )
{
// Return no more than 10 local results
return localSystemNames.Take(10).ToList();
}
// Insufficient local results, use Spansh for a more comprehensive search (this also returns no more than 10 results)
return await spanshService.GetTypeAheadSystemNamesAsync( input, cancellationToken ).ConfigureAwait( false );
}
[NotNull]
public async Task<StarSystem> GetOrCreateStarSystemAsync ( ulong systemAddress, string systemName, bool fetchIfMissing = true, bool refreshIfOutdated = true, bool showMarketDetails = false )
{
var starSystems = await GetOrCreateStarSystemsAsync( new Dictionary<ulong, string> { { systemAddress, systemName } }, fetchIfMissing, refreshIfOutdated, showMarketDetails ).ConfigureAwait(false);
return starSystems.First();
}
[ItemNotNull]
private async Task<List<StarSystem>> GetOrCreateStarSystemsAsync ( Dictionary<ulong, string> requestedSystems,
bool fetchIfMissing = true, bool refreshIfOutdated = true, bool showMarketDetails = false, bool fetchEdsmVisitsAndComments = true )
{
var results = new List<StarSystem>();
if ( !requestedSystems.Any() ) { return results; }
Dictionary<ulong, string> missingSystems () => requestedSystems
.Where( k => results.All( s => s.systemAddress != k.Key ) )
.ToDictionary( k => k.Key, v => v.Value );
results = await GetOrFetchStarSystemsAsync( missingSystems().Keys.ToArray(), fetchIfMissing, refreshIfOutdated, showMarketDetails, fetchEdsmVisitsAndComments ).ConfigureAwait(false) ?? new List<StarSystem>();
// Create a new system object for each name that isn't in the database and couldn't be fetched from a server
var createdStarSystems = missingSystems()
.Select( s => new StarSystem { systemname = s.Value, systemAddress = s.Key } )
.ToList();
results.AddRange( createdStarSystems );
await SaveStarSystemsAsync( createdStarSystems, cts.Token ).ConfigureAwait(false);
return results;
}
public async Task<StarSystem> GetOrFetchStarSystemAsync ( ulong systemAddress, bool fetchIfMissing = true, bool refreshIfOutdated = true, bool showMarketDetails = false, bool fetchEdsmVisitsAndComments = true )
{
if ( systemAddress <= 0 ) { return null; }
var starSystems = await GetOrFetchStarSystemsAsync( new[] { systemAddress }, fetchIfMissing,
refreshIfOutdated, showMarketDetails, fetchEdsmVisitsAndComments ).ConfigureAwait(false);
return starSystems?.FirstOrDefault();
}
//github.com/ <summary>
//github.com/
//github.com/ </summary>
//github.com/ <param name="systemName"></param>
//github.com/ <param name="fetchIfMissing"></param>
//github.com/ <param name="refreshIfOutdated"></param>
//github.com/ <param name="showMarketDetails"></param>
//github.com/ <param name="fetchEdsmVisitsAndComments"></param>
//github.com/ <returns></returns>
public async Task<StarSystem> GetOrFetchStarSystemAsync ( string systemName, bool fetchIfMissing = true, bool refreshIfOutdated = true, bool showMarketDetails = false, bool fetchEdsmVisitsAndComments = true )
{
if ( string.IsNullOrEmpty( systemName ) ) { return null; }
// Fetch from cached systems
if ( starSystemCache.TryGet( systemName, out var cachedSystem ) ) { return cachedSystem; }
// Fetch from the local database. If there is more than one result, return the most recent result (by visits and then by update time)
var sqlStarSystems = await GetSqlStarSystemsAsync( new[] { systemName }, cts.Token, refreshIfOutdated ).ConfigureAwait(false);
if ( sqlStarSystems.Any() )
{
return sqlStarSystems
.OrderByDescending( s => s.lastVisitSeconds ?? 0 )
.ThenByDescending( s => s.updatedat ?? 0 )
.FirstOrDefault();
}
// Fetch from external data sources (when so instructed)
var fetchedWaypoint = await GetOrFetchSystemWaypointAsync( systemName ).ConfigureAwait(false);
if ( fetchedWaypoint is null ) { return null; }
var starSystems = await GetOrFetchStarSystemsAsync( new[] { fetchedWaypoint.systemAddress }, fetchIfMissing,
refreshIfOutdated, showMarketDetails, fetchEdsmVisitsAndComments ).ConfigureAwait(false);
return starSystems?.FirstOrDefault();
}
private async Task<List<StarSystem>> GetOrFetchStarSystemsAsync ( ulong[] systemAddresses, bool fetchIfMissing = true, bool refreshIfOutdated = true, bool showMarketDetails = false, bool fetchEdsmVisitsAndComments = true )
{
var results = new List<StarSystem>();
if ( systemAddresses is null || !systemAddresses.Any() ) { return results; }
ulong[] missingSystems () => systemAddresses.Where( k => results.All( s => s.systemAddress != k ) ).Distinct().ToArray();
// Fetch from cached systems
results.AddRange( starSystemCache.GetRange( missingSystems() ) );
// Fetch from the local database
var localDbSystems = await GetSqlStarSystemsAsync( missingSystems(), refreshIfOutdated ).ConfigureAwait( false );
results.AddRange( localDbSystems );
// Fetch from external data providers (when so instructed)
if ( missingSystems().Any() && fetchIfMissing )
{
var fetchedSystems = await FetchSystemsDataAsync( missingSystems(), showMarketDetails ).ConfigureAwait( false ) ?? new List<StarSystem>();
if ( fetchedSystems.Count > 0 )
{
if ( fetchEdsmVisitsAndComments )
{
// Synchronize EDSM visits and comments
fetchedSystems = await SyncFromStarMapServiceAsync( fetchedSystems ).ConfigureAwait(false);
}
// Update properties that aren't synced from the server and that we want to preserve
fetchedSystems = PreserveUnsyncedProperties( fetchedSystems, localDbSystems );
// Update the `lastupdated` timestamps for the systems we have updated
foreach ( var starSystem in fetchedSystems ) { starSystem.lastupdated = DateTime.UtcNow; }
// Add the external data to our results
results.AddRange( fetchedSystems );
// Save changes to our star systems
await SaveStarSystemsAsync( fetchedSystems, cts.Token ).ConfigureAwait(false);
}
if ( missingSystems().Any() )
{
Logging.Warn( "Unable to retrieve data on all requested star systems.", missingSystems() );
}
}
return results;
}
public async Task<StarSystem> GetOrFetchQuickStarSystemAsync ( ulong systemAddress, bool fetchIfMissing = true )
{
if ( systemAddress <= 0 ) { return null; }
return (await GetOrFetchQuickStarSystemsAsync( new[] { systemAddress }, fetchIfMissing ).ConfigureAwait(false))?.FirstOrDefault();
}
private async Task<List<StarSystem>> GetOrFetchQuickStarSystemsAsync ( ulong[] systemAddresses, bool fetchIfMissing = true )
{
var results = new List<StarSystem>();
if ( systemAddresses is null || !systemAddresses.Any() ) { return results; }
ulong[] missingSystems () => systemAddresses.Where( k => results.All( s => s.systemAddress != k ) ).Distinct().ToArray();
// Fetch from cached systems
results.AddRange( starSystemCache.GetRange( missingSystems() ) );
// Fetch from the local database
results.AddRange( await GetSqlStarSystemsAsync( missingSystems(), false ).ConfigureAwait(false) );
// Fetch from external data providers (when so instructed)
if ( missingSystems().Any() && fetchIfMissing )
{
// Add the external data to our results
results.AddRange( await spanshService.GetQuickStarSystemsAsync( missingSystems(), cts.Token ).ConfigureAwait( false ) );
}
if ( missingSystems().Any() )
{
Logging.Warn( "Unable to retrieve data on all requested star systems.", missingSystems() );
}
return results;
}
public async Task<List<StarSystem>> GetOrFetchQuickStarSystemsAsync ( string[] systemNames, bool fetchIfMissing = true )
{
var waypointTasks = systemNames.AsParallel().Select( GetOrFetchSystemWaypointAsync );
var waypoints = await Task.WhenAll(waypointTasks).ConfigureAwait(false);
var systemAddresses = waypoints.Where( wp => wp != null ).Select( wp => wp.systemAddress ).ToArray();
return await GetOrFetchQuickStarSystemsAsync( systemAddresses.ToArray(), fetchIfMissing ).ConfigureAwait(false);
}
public async Task<NavWaypoint> GetOrFetchSystemWaypointAsync ( string systemName )
{
if ( string.IsNullOrEmpty(systemName) ) { return null; }
var wp = await GetOrFetchSystemWaypointsAsync( new[] { systemName } ).ConfigureAwait(false);
return wp.FirstOrDefault();
}
public async Task<List<NavWaypoint>> GetOrFetchSystemWaypointsAsync ( string[] systemNames )
{
var results = new List<NavWaypoint>();
if ( systemNames is null || !systemNames.Any() ) { return results; }
string[] missingSystems () => systemNames.Where( k => results.All( s => s.systemName != k ) ).Distinct().ToArray();
// Fetch from cached systems
results.AddRange( starSystemCache.GetRange( missingSystems() ).Select( s => new NavWaypoint( s ) ) );
// Fetch from Spansh
var waypoints = missingSystems().AsParallel().Select( async systemName =>
{
var wp = await spanshService.GetWaypointsBySystemNameAsync( systemName.Trim(), cts.Token ).ConfigureAwait(false);
return wp.FirstOrDefault( s => s.systemName.Equals( systemName, StringComparison.InvariantCultureIgnoreCase ) );
} ).ToList();
results.AddRange( await Task.WhenAll( waypoints ).ConfigureAwait(false) );
return results;
}
//github.com/ <summary>
//github.com/ Find the station with the given system and station names from the Spansh Station Search API.
//github.com/ </summary>
//github.com/ <param name="fromSystemAddress"></param>
//github.com/ <param name="fromMarketId"></param>
//github.com/ <returns></returns>
public async Task<NavWaypoint> GetOrFetchStationWaypointAsync ( ulong fromSystemAddress, long fromMarketId )
{
// Try to fetch from cached systems
if ( starSystemCache.TryGet( fromSystemAddress, out var cachedStarSystem ) )
{
var cachedStation = cachedStarSystem.stations.FirstOrDefault( s => s.marketId == fromMarketId );
if ( cachedStation != null )
{
return new NavWaypoint( cachedStarSystem )
{
stationName = cachedStation.name,
marketID = cachedStation.marketId
};
}
}
var system = await GetOrFetchQuickStarSystemAsync( fromSystemAddress ).ConfigureAwait(false);
var station = system?.stations.FirstOrDefault( s => s.marketId == fromMarketId );
if ( station != null )
{
return new NavWaypoint( system )
{
stationName = station.name,
marketID = station.marketId
};
}
return null;
}
//github.com/ <summary>
//github.com/ Find the station with the given system and station names from the Spansh Station Search API.
//github.com/ </summary>
//github.com/ <param name="fromSystemName"></param>
//github.com/ <param name="fromMarketId"></param>
//github.com/ <returns></returns>
public async Task<NavWaypoint> GetOrFetchStationWaypointAsync ( string fromSystemName, long fromMarketId )
{
// Try to fetch from cached systems
if ( !string.IsNullOrEmpty( fromSystemName ) && starSystemCache.TryGet( fromSystemName, out var cachedStarSystem ) )
{
var cachedStation = cachedStarSystem.stations.FirstOrDefault( s => s.marketId == fromMarketId );
if ( cachedStation != null )
{
return new NavWaypoint( cachedStarSystem )
{
stationName = cachedStation.name,
marketID = cachedStation.marketId
};
}
}
// Fetch from Spansh
var wp = await GetOrFetchSystemWaypointAsync( fromSystemName ).ConfigureAwait(false);
if ( wp?.systemAddress != null )
{
var system = await GetOrFetchQuickStarSystemAsync( wp.systemAddress ).ConfigureAwait(false);
var station = system?.stations.FirstOrDefault( s => s.marketId == fromMarketId );
return new NavWaypoint( system )
{
stationName = station?.name,
marketID = station?.marketId
};
}
return null;
}
#region StarSystemSqlLiteRepository
private async Task<List<StarSystem>> GetSqlStarSystemsAsync ( ulong[] systemAddresses, bool refreshIfOutdated = true )
{
var dbStarSystems = await starSystemRepository.GetSqlStarSystemsAsync( systemAddresses, cts.Token ).ConfigureAwait(false);
return DeserializeSqlStarSystems( dbStarSystems, refreshIfOutdated );
}
private async Task<List<StarSystem>> GetSqlStarSystemsAsync ( string[] systemNames, CancellationToken cancellationToken, bool refreshIfOutdated = true )
{
var dbStarSystems = await starSystemRepository.GetSqlStarSystemsAsync( systemNames, cancellationToken ).ConfigureAwait(false);
return DeserializeSqlStarSystems( dbStarSystems, refreshIfOutdated );
}
private List<StarSystem> DeserializeSqlStarSystems ( List<DatabaseStarSystem> dbStarSystems, bool refreshIfOutdated )
{
var results = new List<StarSystem>();
foreach ( var dbStarSystem in dbStarSystems )
{
if ( HasKeyFields( dbStarSystem ) && IsRecent( refreshIfOutdated, dbStarSystem ) )
{
// Deserialize the result
var result = DeserializeStarSystem( dbStarSystem.systemAddress, dbStarSystem.systemJson );
// Exclude null results and results with missing bodies or coordinates (forcing a refresh from another source)
if ( result?.x == null || result.y == null || result.z == null || result.bodies.Count < 1)
{
continue;
}
results.Add( result );
}
}
return results;
// Consider a star system to be recent if it has been updated within the last hour
// (for populated systems) or the last month (for unpopulated systems, which are
// less likely to have changed)
bool IsRecent ( bool isRecencyImportant, DatabaseStarSystem dbStarSystem )
{
if ( isRecencyImportant )
{
return dbStarSystem.population > 0
? dbStarSystem.lastUpdated >= DateTime.UtcNow.AddHours( -1 )
: dbStarSystem.lastUpdated >= DateTime.UtcNow.AddMonths( -1 );
}
return true;
}
bool HasKeyFields ( DatabaseStarSystem dbStarSystem )
{
return dbStarSystem.systemAddress > 0 &&
dbStarSystem.x != null &&
dbStarSystem.y != null &&
dbStarSystem.z != null;
}
}
internal static IList<StarSystem> PreserveUnsyncedProperties ( IList<StarSystem> updatedSystems, IList<StarSystem> databaseStarSystems )
{
foreach ( var updatedSystem in updatedSystems ?? new List<StarSystem>() )
{
foreach ( var oldStarSystem in databaseStarSystems ?? new List<StarSystem>() )
{
if ( updatedSystem.systemAddress == oldStarSystem.systemAddress )
{
PreserveSystemProperties( updatedSystem, oldStarSystem );
PreserveBodyProperties( updatedSystem, oldStarSystem );
PreserveFactionProperties( updatedSystem, oldStarSystem );
// No station data needs to be carried over at this time.
}
}
}
return updatedSystems ?? new List<StarSystem>();
}
private static void PreserveSystemProperties ( StarSystem updatedSystem, StarSystem oldStarSystem )
{
// Carry over StarSystem properties that we want to preserve
updatedSystem.totalbodies = oldStarSystem.totalbodies;
// Visits should sync from EDSM, but in case there is a problem with the connection we will also seed back in our old star system visit data
foreach ( var visit in oldStarSystem.visitLog)
{
// The SortedSet<T> class does not accept duplicate elements so we can safely add timestamps which may be duplicates of visits already reported from EDSM.
// If an item is already in the set, processing continues and no exception is thrown.
updatedSystem.visitLog.Add( visit );
}
}
private static void PreserveBodyProperties ( StarSystem updatedSystem, StarSystem oldStarSystem )
{
// Carry over Body properties that we want to preserve (e.g. exploration data)
updatedSystem.PreserveBodyData( oldStarSystem.bodies.ToList(), updatedSystem.bodies );
}
private static void PreserveFactionProperties ( StarSystem updatedSystem, StarSystem oldStarSystem )
{
// Carry over Faction properties that we want to preserve (e.g. reputation data)
foreach ( var oldFaction in oldStarSystem.factions )
{
foreach ( var updatedFaction in updatedSystem.factions )
{
if ( updatedFaction.name == oldFaction.name )
{
updatedFaction.myreputation = oldFaction.myreputation;
}
}
}
}
private StarSystem DeserializeStarSystem ( ulong systemAddress, string data )
{
if ( systemAddress == 0 || data == string.Empty )
{ return null; }
// Check our short term star system cache for a previously deserialized star system and return that if it is available.
if ( starSystemCache.TryGet( systemAddress, out var cachedStarSystem ) )
{
return cachedStarSystem;
}
// Not found in memory, proceed with deserialization
try
{
var result = JsonConvert.DeserializeObject<StarSystem>( data );
if ( result == null )
{
Logging.Info( "Failed to obtain system for address " + systemAddress + " from the SQLiteRepository" );
}
// Save the deserialized star system to our short term star system cache for reference
if ( result != null )
{
factionCache.AddOrUpdate(result.factions);
starSystemCache.AddOrUpdate( result );
}
return result;
}
catch ( Exception ex )
{
Logging.Warn( $"Problem reading data for star system address {systemAddress} from database.", ex );
}
return null;
}
public async Task SaveStarSystemAsync ( StarSystem starSystem )
{
if ( starSystem == null ) { return; }
await SaveStarSystemsAsync( new List<StarSystem> { starSystem }, cts.Token ).ConfigureAwait(false);
}
private async Task SaveStarSystemsAsync ( IList<StarSystem> starSystems, CancellationToken cancellationToken )
{
if ( !starSystems.Any() ) { return; }
// Update any faction and star systems in our short term faction and star system caches to minimize repeat deserialization
foreach ( var starSystem in starSystems )
{
factionCache.AddOrUpdate( starSystem.factions );
starSystemCache.AddOrUpdate( starSystem );
}
if ( unitTesting ) { return; }
await starSystemRepository.SaveStarSystemsAsync( starSystems, cancellationToken ).ConfigureAwait(false);
}
#endregion
#region Spansh Endpoints
public Task<NavWaypointCollection> FetchCarrierRouteAsync ( string currentSystem, string[] targetSystems, long usedCarrierCapacity,
bool calculateTotalFuelRequired = true, string[] refuelDestinations = null, bool fromUIquery = false )
{
return spanshService.GetCarrierRouteAsync( currentSystem, targetSystems, usedCarrierCapacity,
calculateTotalFuelRequired, refuelDestinations, fromUIquery );
}
public Task<NavWaypointCollection> FetchGalaxyRouteAsync ( string currentSystem, string targetSystem, Ship ship,
int? cargoCarriedTons = null, bool isSupercharged = false, bool useSupercharge = true,
bool useInjections = false, bool excludeSecondary = false, bool fromUIquery = false )
{
return spanshService.GetGalaxyRouteAsync( currentSystem, targetSystem, ship, cargoCarriedTons, isSupercharged,
useSupercharge, useInjections, excludeSecondary, fromUIquery );
}
private async Task<IList<StarSystem>> FetchSystemsDataAsync ( ulong[] systemAddresses, bool showMarketDetails )
{
if ( systemAddresses == null || systemAddresses.Length == 0 ) { return new List<StarSystem>(); }
return await spanshService.GetStarSystemsAsync( systemAddresses, showMarketDetails, cts.Token ).ConfigureAwait( false );
}
//github.com/ <summary>
//github.com/ Find the nearest station with specific station services from the Spansh Station Search API.
//github.com/ </summary>
//github.com/ <param name="fromX"></param>
//github.com/ <param name="fromY"></param>
//github.com/ <param name="fromZ"></param>
//github.com/ <param name="filters"></param>
//github.com/ <returns></returns>
public async Task<NavWaypoint> FetchStationWaypointAsync ( decimal fromX, decimal fromY, decimal fromZ, Dictionary<string, object> filters )
{
var data = await spanshService.DistanceOrderedQueryAsync( SpanshService.QueryGroup.stations, fromX, fromY, fromZ, filters, cts.Token ).ConfigureAwait(false);
if ( data?[ "error" ] != null )
{
Logging.Warn( "Spansh API responded with: " + data[ "error" ] );
return null;
}
return spanshService.ParseQuickStationWaypoint( data?[ "results" ]?.FirstOrDefault() );
}
//github.com/ <summary>
//github.com/ Find the nearest body with specific parameters from the Spansh Station Search API.
//github.com/ </summary>
//github.com/ <param name="fromX"></param>
//github.com/ <param name="fromY"></param>
//github.com/ <param name="fromZ"></param>
//github.com/ <param name="filters"></param>
//github.com/ <returns></returns>
public async Task<NavWaypoint> FetchBodyWaypointAsync ( decimal fromX, decimal fromY, decimal fromZ, Dictionary<string, object> filters )
{
var data = await spanshService.DistanceOrderedQueryAsync( SpanshService.QueryGroup.bodies, fromX, fromY, fromZ, filters, cts.Token ).ConfigureAwait(false);
if ( data?[ "error" ] != null )
{
Logging.Warn( "Spansh API responded with: " + data[ "error" ] );
return null;
}
return ParseQuickBody( data?[ "results" ]?.FirstOrDefault() );
NavWaypoint ParseQuickBody ( JToken bodyData )
{
if ( bodyData is null ) { return null; }
var systemName = bodyData[ "system_name" ]?.ToString();
var systemAddress = bodyData[ "system_id64" ]?.ToObject<ulong>() ?? 0;
var systemX = bodyData[ "system_x" ]?.ToObject<decimal>() ?? 0;
var systemY = bodyData[ "system_y" ]?.ToObject<decimal>() ?? 0;
var systemZ = bodyData[ "system_z" ]?.ToObject<decimal>() ?? 0;
return new NavWaypoint( systemName, systemAddress, systemX, systemY, systemZ );
}
}
public async Task<Faction> FetchFactionByNameAsync ( string factionName, string presenceSystemName = null )
{
if ( string.IsNullOrEmpty( factionName ) ) { return null; }
// First try to fetch the faction from the cache
if ( factionCache.TryGet( factionName, out var faction ) )
{
return faction;
}
// Next, try to fetch the faction from Spansh
faction = await spanshService.GetFactionByNameAsync( factionName, cts.Token, presenceSystemName ).ConfigureAwait(false);
// If we've successfully retrieved the faction then update our cache
if ( faction != null )
{
factionCache.AddOrUpdate( faction );
}
return faction;
}
#endregion
#region EDSM Endpoints
[CanBeNull]
public async Task<Traffic> GetSystemTrafficAsync ( string systemName, long? edsmId = null )
{
if (string.IsNullOrEmpty(systemName)) { return null; }
return await edsmService.GetStarMapTrafficAsync(systemName, edsmId).ConfigureAwait(false) ?? new Traffic();
}
[CanBeNull]
public async Task<Traffic> GetSystemDeathsAsync ( string systemName, long? edsmId = null )
{
if (string.IsNullOrEmpty(systemName)) { return null; }
return await edsmService.GetStarMapDeathsAsync(systemName, edsmId).ConfigureAwait(false) ?? new Traffic();
}
[CanBeNull]
public async Task<Traffic> GetSystemHostilityAsync( string systemName, long? edsmId = null )
{
if (string.IsNullOrEmpty(systemName)) { return null; }
return await edsmService.GetStarMapHostilityAsync(systemName, edsmId).ConfigureAwait(false) ?? new Traffic();
}
// EDSM Journal Synchronization
public bool TryStartEdsmJournal ()
{
edsmService?.StartJournalSync();
return edsmService != null;
}
public async Task StopEdsmJournalAsync ()
{
if ( edsmService != null )
{
await edsmService.StopJournalAsync().ConfigureAwait(false);
}
}
public Task<List<string>> GetIgnoredEdsmEventsAsync ()
{
return edsmService?.getIgnoredEventsAsync();
}
public void EnqueueEdsmEvent ( IDictionary<string, object> eventObject )
{
edsmService.EnqueueEvent( eventObject );
}
public async Task SyncFromStarMapServiceAsync ( DateTime? lastSync = null )
{
try
{
Logging.Info( "Syncing all flight logs from EDSM" );
var flightLogs = await edsmService.getStarMapLogAsync(lastSync).ConfigureAwait(false);
if ( flightLogs == null || flightLogs.Count == 0 )
{
Logging.Debug( "EDSM flight logs are already synchronized; no new flight logs since last sync." );
return;
}
var comments = await edsmService.getStarMapCommentsAsync().ConfigureAwait(false);
// Process in batches
var total = flightLogs.Count;
for ( var i = 0; i < total; i += StarMapService.syncBatchSize )
{
var batchSize = Math.Min(StarMapService.syncBatchSize, total - i);
var batch = flightLogs.GetRange(i, batchSize);
await SyncEdsmLogBatchAsync( batch, comments ).ConfigureAwait(false);
}
Logging.Info( "EDSM flight logs synchronized" );
}
catch ( EDSMException ex )
{
Logging.Debug( "EDSM error received: " + ex.Message, ex );
}
catch ( OperationCanceledException ex )
{
Logging.Debug( "EDSM update canceled by user: " + ex.Message );
}
}
// EDSM flight log synchronization (named star systems)
public async Task<IList<StarSystem>> SyncFromStarMapServiceAsync(IList<StarSystem> starSystems)
{
if ( starSystems.Count > 0 && !unitTesting )
{
try
{
Logging.Debug( $"Syncing flight logs from EDSM for {starSystems.Count} system(s)." );
var flightLogs = await edsmService.getStarMapLogAsync(null, starSystems.Select(s => s.systemAddress).ToArray()).ConfigureAwait(false);
var comments = await edsmService.getStarMapCommentsAsync().ConfigureAwait(false);
if (flightLogs?.Count > 0)
{
foreach (var starSystem in starSystems)
{
if (starSystem?.systemname != null)
{
Logging.Debug("Syncing star system " + starSystem.systemname + " from EDSM.");
foreach (var flightLog in flightLogs)
{
if (flightLog.systemId64 == starSystem.systemAddress)
{
starSystem.visitLog.Add(flightLog.date);
}
}
var comment = comments.FirstOrDefault(s => s.Key == starSystem.systemname);
if (!string.IsNullOrEmpty(comment.Value))
{
starSystem.comment = comment.Value;
}
}
}
}
else
{
Logging.Warn( $"No flight logs received for {starSystems.Count} system(s).." );
}
}
catch (EDSMException edsme)
{
Logging.Debug("EDSM error received: " + edsme.Message, edsme);
}
catch (ThreadAbortException e)
{
Logging.Debug("EDSM update stopped by user: " + e.Message);
}
}
return starSystems;
}
public async Task SyncEdsmLogBatchAsync ( List<StarMapResponseLogEntry> flightLogBatch, Dictionary<string, string> comments )
{
var syncedSystems = new List<StarSystem>();
var uniqueAddresses = flightLogBatch
.Select( f => f.systemId64 )
.Distinct()
.ToArray();
var batchSystems = await GetOrFetchStarSystemsAsync( uniqueAddresses, refreshIfOutdated: false, fetchEdsmVisitsAndComments: false ).ConfigureAwait(false);
var lookup = batchSystems.ToDictionary(s => s.systemAddress);
var groupedLogs = flightLogBatch.GroupBy(f => f.systemId64);
foreach ( var group in groupedLogs )
{
var address = group.Key;
var firstLog = group.First();
var systemName = firstLog.system;
// Get or create the StarSystem
if ( !lookup.TryGetValue( address, out var starSystem ) )
{
starSystem = new StarSystem
{
systemAddress = address,
systemname = systemName,
lastupdated = firstLog.date
};
batchSystems.Add( starSystem );
lookup[ address ] = starSystem;
}
// Backfill missing body system addresses
if ( starSystem.systemAddress == 0 && address > 0 )
{
starSystem.systemAddress = address;
foreach ( var body in starSystem.bodies )
{
body.systemAddress = address;
}
starSystem.AddOrUpdateBodies( starSystem.bodies );
}
// Merge comments
if ( comments.TryGetValue( systemName, out var comment ) )
{
starSystem.comment = comment;
}
// Append all visit dates at once
foreach ( var d in group.Select( f => f.date ) )
{
starSystem.visitLog.Add( d );
}
syncedSystems.Add( starSystem );
}
await saveFromStarMapServiceAsync( syncedSystems ).ConfigureAwait(false);
}
private async Task saveFromStarMapServiceAsync ( List<StarSystem> syncSystems )
{
await starSystemRepository.SaveStarSystemsAsync( syncSystems, cts.Token ).ConfigureAwait( false );
var starMapConfiguration = ConfigService.Instance.edsmConfiguration;
starMapConfiguration.lastFlightLogSync = DateTime.UtcNow;
ConfigService.Instance.edsmConfiguration = starMapConfiguration;
}
#endregion
}
}