From ded05ced13be9220169c9d1da8efa516e9c4a608 Mon Sep 17 00:00:00 2001 From: pfh59 <109206285+pfh59@users.noreply.github.com> Date: Thu, 26 Sep 2024 21:26:42 +0200 Subject: [PATCH] - Multi Map Management #9 (#302) - Multi Map Management #9 - remove usued using - reindent - add new service EveMapperRealTimeService - and new componentmap - update to donet 8.0.8 - fix migration : add alter table - fix WHNote for multimap - fix routeplanner for multimap - Delete old add system force - Use New Search System dialogue - add authorization policy for map and control map loading - fix and add testunit - Add tooltip for route planner button - Update realtime service to manage multi map and access events - Fix user connected and disconnected by map - Fix copy /paste sig and notes --- .../Models/Graph/EveEntityModelTest.cs | 6 +- .../Models/Graph/GraphModelsTest.cs | 5 +- src/WHMapper.Tests/Models/MapAdminTests.cs | 71 + .../Services/Db/DbIntegrationTest.cs | 148 +- .../EveMapper/EveMapperAccessHelperTests.cs | 29 + .../EveOnlineAPI/PublicEveOnlineAPITest.cs | 3 +- .../SDE/SdeServiceManagerIntegrationTests.cs | 1 - .../WHHelper/EveWHAccessHelperTest.cs | 56 +- .../EveWHMapperRoutePlannerHelperTest.cs | 62 +- .../WHHelper/WHColorHelperTest.cs | 4 +- .../WHHelper/WHSignatureHelperTest.cs | 4 +- src/WHMapper.Tests/WHMapper.Tests.csproj | 16 +- src/WHMapper/Data/WHMapperContext.cs | 18 +- src/WHMapper/FeatureFlag.cs | 18 - src/WHMapper/Hubs/IWHMapperNotificationHub.cs | 16 +- src/WHMapper/Hubs/WHMapperNotificationHub.cs | 320 ++- .../Migrations/20230805074405_Init.cs | 3 +- .../20240229165501_Add_Link_Jump_Log.cs | 3 +- ...ump_Log_Properties_To_Nullable.Designer.cs | 15 +- ..._Update_Jump_Log_Properties_To_Nullable.cs | 47 + ...20240828145305_Allow_Multi_Map.Designer.cs | 409 ++++ .../20240828145305_Allow_Multi_Map.cs | 50 + ...Update_UniqueKey_For_Multi_Map.Designer.cs | 407 ++++ ...31174011_Update_UniqueKey_For_Multi_Map.cs | 105 + ...tes_To_Be_Unique_For_Multi_Map.Designer.cs | 419 ++++ ...Update_Notes_To_Be_Unique_For_Multi_Map.cs | 61 + ...ute_To_Be_Unique_For_Multi_Map.Designer.cs | 431 ++++ ...Update_Route_To_Be_Unique_For_Multi_Map.cs | 61 + .../WHMapperContextModelSnapshot.cs | 72 +- .../Models/Custom/Node/EveSystemLinkModel.cs | 8 +- .../Models/Custom/Node/EveSystemNodeModel.cs | 8 +- .../Models/DTO/EveAPI/Alliance/Alliance.cs | 6 +- .../Models/DTO/EveAPI/Character/Character.cs | 5 +- .../DTO/EveAPI/Corporation/Corporation.cs | 5 +- .../Models/DTO/EveAPI/Dogma/Attribute.cs | 6 +- .../Models/DTO/EveAPI/Dogma/Effect.cs | 6 +- .../Models/DTO/EveAPI/SSO/EveToken.cs | 3 +- .../EveAPI/Search/SearchAllianceResults.cs | 6 +- .../EveAPI/Search/SearchCharacterResults.cs | 6 +- .../EveAPI/Search/SearchCoporationResults.cs | 6 +- .../Models/DTO/EveAPI/Universe/Category.cs | 6 +- .../DTO/EveAPI/Universe/Constellation.cs | 5 +- .../Models/DTO/EveAPI/Universe/Group.cs | 5 +- .../Models/DTO/EveAPI/Universe/Region.cs | 5 +- .../Models/DTO/EveAPI/Universe/Stargate.cs | 3 +- .../Models/DTO/EveAPI/Universe/Type.cs | 3 +- .../DTO/EveMapper/Enums/EveSystemTypeEnums.cs | 3 +- .../DTO/EveMapper/Enums/WHEffectEnums.cs | 3 +- .../EveMapper/EveEntity/CharactereEntity.cs | 1 - .../EveEntity/ConstellationEntity.cs | 1 - .../DTO/EveMapper/EveEntity/RegionEntity.cs | 1 - .../DTO/EveMapper/EveEntity/SystemEntity.cs | 1 - .../DTO/EveMapper/EveEntity/WHEntity.cs | 1 - .../Models/DTO/EveMapper/EveSystemEffect.cs | 5 +- .../Models/DTO/EveMapper/WormholeType.cs | 5 +- .../Models/DTO/InitialApplicationState.cs | 3 +- src/WHMapper/Models/DTO/MapAdmin/MapAdmin.cs | 19 + .../Models/DTO/SDE/SDESecondarySun.cs | 5 +- src/WHMapper/Models/DTO/SDE/SDESolarSystem.cs | 6 +- src/WHMapper/Models/DTO/TokenProvider.cs | 5 +- src/WHMapper/Models/Db/Enums/WHAccessEnums.cs | 3 +- .../Models/Db/Enums/WHSignatureEnums.cs | 3 +- .../Models/Db/Enums/WHSystemLinkEnums.cs | 3 +- .../Models/Db/Enums/WHSystemStatusEnums.cs | 1 - src/WHMapper/Models/Db/WHAccess.cs | 6 +- src/WHMapper/Models/Db/WHAdmin.cs | 6 +- src/WHMapper/Models/Db/WHMap.cs | 8 +- src/WHMapper/Models/Db/WHNote.cs | 19 +- src/WHMapper/Models/Db/WHRoute.cs | 9 +- src/WHMapper/Models/Db/WHSignature.cs | 3 +- src/WHMapper/Models/Db/WHSystem.cs | 3 +- src/WHMapper/Models/Db/WHSystemLink.cs | 5 +- src/WHMapper/Pages/Login.cshtml.cs | 2 - src/WHMapper/Pages/Logout.cshtml.cs | 3 - src/WHMapper/Pages/Mapper/Add.cs | 172 -- .../Administration/{ => Access}/Delete.cs | 11 +- .../Administration/{ => Access}/Delete.razor | 0 .../Administration/{ => Access}/Overview.cs | 6 +- .../{ => Access}/Overview.razor | 0 .../Pages/Mapper/Administration/Map/Add.cs | 72 + .../Pages/Mapper/Administration/Map/Add.razor | 11 + .../Mapper/Administration/Map/AddAccess.cs | 129 ++ .../Mapper/Administration/Map/AddAccess.razor | 24 + .../Pages/Mapper/Administration/Map/Delete.cs | 115 + .../Mapper/Administration/Map/Delete.razor | 17 + .../Mapper/Administration/Map/Overview.cs | 267 +++ .../Mapper/Administration/Map/Overview.razor | 86 + .../Mapper/Administration/Map/RemoveAccess.cs | 133 ++ .../Administration/Map/RemoveAccess.razor | 17 + .../Mapper/CustomDragMovablesBehavior.cs | 2 - .../Pages/Mapper/CustomNode/EveSystemLink.cs | 11 +- .../Pages/Mapper/CustomNode/EveSystemNode.cs | 16 +- .../Mapper/CustomNode/EveSystemNode.razor | 6 +- .../Pages/Mapper/LinkInfos/Overview.cs | 6 +- src/WHMapper/Pages/Mapper/Map/Overview.cs | 1714 ++++++++++++++ src/WHMapper/Pages/Mapper/Map/Overview.razor | 99 + src/WHMapper/Pages/Mapper/Notes/Overview.cs | 28 +- src/WHMapper/Pages/Mapper/Overview.cs | 1963 ++--------------- src/WHMapper/Pages/Mapper/Overview.razor | 148 +- src/WHMapper/Pages/Mapper/RoutePlanner/Add.cs | 123 -- .../Pages/Mapper/RoutePlanner/Add.razor | 25 - .../Pages/Mapper/RoutePlanner/Overview.cs | 64 +- .../Pages/Mapper/RoutePlanner/Overview.razor | 14 +- .../Pages/Mapper/Search/SearchSystem.cs | 121 + .../{Add.razor => Search/SearchSystem.razor} | 0 .../Pages/Mapper/Signatures/Delete.cs | 6 +- .../Pages/Mapper/Signatures/Import.cs | 17 +- .../Pages/Mapper/Signatures/Overview.cs | 103 +- .../Pages/Mapper/SystemInfos/Overview.cs | 12 +- .../Pages/Mapper/SystemInfos/Overview.razor | 2 +- src/WHMapper/Program.cs | 5 + .../Repositories/ADefaultRepository.cs | 6 +- .../WHAccesses/IWHAccessRepository.cs | 5 +- .../WHAccesses/WHAccessRepository.cs | 6 +- .../WHAdmins/IWHAdminRepository.cs | 5 +- .../WHAdmins/WHAdminRepository.cs | 8 +- .../WHJumpLogs/WHJumpLogRepository.cs | 2 - .../Repositories/WHMaps/IWHMapRepository.cs | 9 +- .../Repositories/WHMaps/WHMapRepository.cs | 127 +- .../Repositories/WHNotes/IWHNoteRepository.cs | 7 +- .../Repositories/WHNotes/WHNoteRepository.cs | 11 +- .../WHRoutes/IWHRouteRepository.cs | 4 +- .../WHRoutes/WHRouteRepository.cs | 8 +- .../WHSignatures/IWHSignatureRepository.cs | 3 +- .../WHSignatures/WHSignatureRepository.cs | 6 +- .../WHSystemLinks/IWHSystemLinkRepository.cs | 5 +- .../WHSystemLinks/WHSystemLinkRepository.cs | 7 +- .../WHSystems/IWHSystemRepository.cs | 4 +- .../WHSystems/WHSystemRepository.cs | 8 +- .../EveMapperMapHandler.cs | 50 + .../EveMapperMapRequirement.cs | 11 + .../EveMapper/EveMapperAccessHelper.cs | 37 +- .../Services/EveMapper/EveMapperHelper.cs | 4 +- .../EveMapper/EveMapperRealTimeService.cs | 421 ++++ .../EveMapper/EveMapperRoutePlannerHelper.cs | 20 +- .../EveMapper/IEveMapperAccessHelper.cs | 1 + .../EveMapper/IEveMapperRealTimeService.cs | 369 ++++ .../EveMapper/IEveMapperRoutePlannerHelper.cs | 6 +- src/WHMapper/Shared/AccessControl.razor | 1 + src/WHMapper/Shared/MainLayout.razor | 23 +- src/WHMapper/WHMapper.csproj | 20 +- 141 files changed, 7054 insertions(+), 2770 deletions(-) create mode 100644 src/WHMapper.Tests/Models/MapAdminTests.cs delete mode 100644 src/WHMapper/FeatureFlag.cs create mode 100644 src/WHMapper/Migrations/20240828145305_Allow_Multi_Map.Designer.cs create mode 100644 src/WHMapper/Migrations/20240828145305_Allow_Multi_Map.cs create mode 100644 src/WHMapper/Migrations/20240831174011_Update_UniqueKey_For_Multi_Map.Designer.cs create mode 100644 src/WHMapper/Migrations/20240831174011_Update_UniqueKey_For_Multi_Map.cs create mode 100644 src/WHMapper/Migrations/20240909201955_Update_Notes_To_Be_Unique_For_Multi_Map.Designer.cs create mode 100644 src/WHMapper/Migrations/20240909201955_Update_Notes_To_Be_Unique_For_Multi_Map.cs create mode 100644 src/WHMapper/Migrations/20240912202232_Update_Route_To_Be_Unique_For_Multi_Map.Designer.cs create mode 100644 src/WHMapper/Migrations/20240912202232_Update_Route_To_Be_Unique_For_Multi_Map.cs create mode 100644 src/WHMapper/Models/DTO/MapAdmin/MapAdmin.cs delete mode 100644 src/WHMapper/Pages/Mapper/Add.cs rename src/WHMapper/Pages/Mapper/Administration/{ => Access}/Delete.cs (93%) rename src/WHMapper/Pages/Mapper/Administration/{ => Access}/Delete.razor (100%) rename src/WHMapper/Pages/Mapper/Administration/{ => Access}/Overview.cs (98%) rename src/WHMapper/Pages/Mapper/Administration/{ => Access}/Overview.razor (100%) create mode 100644 src/WHMapper/Pages/Mapper/Administration/Map/Add.cs create mode 100644 src/WHMapper/Pages/Mapper/Administration/Map/Add.razor create mode 100644 src/WHMapper/Pages/Mapper/Administration/Map/AddAccess.cs create mode 100644 src/WHMapper/Pages/Mapper/Administration/Map/AddAccess.razor create mode 100644 src/WHMapper/Pages/Mapper/Administration/Map/Delete.cs create mode 100644 src/WHMapper/Pages/Mapper/Administration/Map/Delete.razor create mode 100644 src/WHMapper/Pages/Mapper/Administration/Map/Overview.cs create mode 100644 src/WHMapper/Pages/Mapper/Administration/Map/Overview.razor create mode 100644 src/WHMapper/Pages/Mapper/Administration/Map/RemoveAccess.cs create mode 100644 src/WHMapper/Pages/Mapper/Administration/Map/RemoveAccess.razor create mode 100644 src/WHMapper/Pages/Mapper/Map/Overview.cs create mode 100644 src/WHMapper/Pages/Mapper/Map/Overview.razor delete mode 100644 src/WHMapper/Pages/Mapper/RoutePlanner/Add.cs delete mode 100644 src/WHMapper/Pages/Mapper/RoutePlanner/Add.razor create mode 100644 src/WHMapper/Pages/Mapper/Search/SearchSystem.cs rename src/WHMapper/Pages/Mapper/{Add.razor => Search/SearchSystem.razor} (100%) create mode 100644 src/WHMapper/Services/EveMapper/AuthorizationPolicies/EveMapperMapHandler.cs create mode 100644 src/WHMapper/Services/EveMapper/AuthorizationPolicies/EveMapperMapRequirement.cs create mode 100644 src/WHMapper/Services/EveMapper/EveMapperRealTimeService.cs create mode 100644 src/WHMapper/Services/EveMapper/IEveMapperRealTimeService.cs diff --git a/src/WHMapper.Tests/Models/Graph/EveEntityModelTest.cs b/src/WHMapper.Tests/Models/Graph/EveEntityModelTest.cs index 198427b7..0d5c8521 100644 --- a/src/WHMapper.Tests/Models/Graph/EveEntityModelTest.cs +++ b/src/WHMapper.Tests/Models/Graph/EveEntityModelTest.cs @@ -1,6 +1,4 @@ -using Microsoft.AspNetCore.Mvc; -using Pipelines.Sockets.Unofficial.Arenas; -using WHMapper.Models.DTO.EveAPI.Alliance; +using WHMapper.Models.DTO.EveAPI.Alliance; using WHMapper.Models.DTO.EveAPI.Character; using WHMapper.Models.DTO.EveAPI.Corporation; using WHMapper.Models.DTO.EveMapper.Enums; @@ -9,7 +7,7 @@ namespace WHMapper.Tests.Models.Graph { - + [TestCaseOrderer(PriorityOrderer.Name, PriorityOrderer.Assembly)] public class EveEntityModelTest diff --git a/src/WHMapper.Tests/Models/Graph/GraphModelsTest.cs b/src/WHMapper.Tests/Models/Graph/GraphModelsTest.cs index e1df2e1e..a4155f7b 100644 --- a/src/WHMapper.Tests/Models/Graph/GraphModelsTest.cs +++ b/src/WHMapper.Tests/Models/Graph/GraphModelsTest.cs @@ -1,5 +1,4 @@ -using Blazor.Diagrams.Core.Models; -using WHMapper.Models.Custom.Node; +using WHMapper.Models.Custom.Node; using WHMapper.Models.Db; using WHMapper.Models.Db.Enums; using WHMapper.Models.DTO.EveMapper; @@ -53,7 +52,7 @@ public GraphModelsTest() [Fact] public async Task Eve_System_Node_Model() { - var node = new EveSystemNodeModel(new WHSystem(DEFAULT_MAP_ID,SOLAR_SYSTEM_JITA_ID, SOLAR_SYSTEM_JITA_NAME, SOLAR_SYSTEM_EXTENSION_NAME, SOLAR_SYSTEM_JITA_SECURITY), new WHNote(SOLAR_SYSTEM_JITA_ID,WHSystemStatus.Friendly,SOLAR_SYSTEM_JITA_NAME), REGION_JITA_NAME, CONSTELLATION_JITA_NAME); + var node = new EveSystemNodeModel(new WHSystem(DEFAULT_MAP_ID,SOLAR_SYSTEM_JITA_ID, SOLAR_SYSTEM_JITA_NAME, SOLAR_SYSTEM_EXTENSION_NAME, SOLAR_SYSTEM_JITA_SECURITY), new WHNote(DEFAULT_MAP_ID,SOLAR_SYSTEM_JITA_ID,WHSystemStatus.Friendly,SOLAR_SYSTEM_JITA_NAME), REGION_JITA_NAME, CONSTELLATION_JITA_NAME); Assert.NotNull(node); Assert.Equal(0, node.IdWH); Assert.Equal(DEFAULT_MAP_ID, node.IdWHMap); diff --git a/src/WHMapper.Tests/Models/MapAdminTests.cs b/src/WHMapper.Tests/Models/MapAdminTests.cs new file mode 100644 index 00000000..cc2a67d7 --- /dev/null +++ b/src/WHMapper.Tests/Models/MapAdminTests.cs @@ -0,0 +1,71 @@ +using System.Collections.Generic; +using WHMapper.Models.Db; +using WHMapper.Models.DTO.MapAdmin; +using Xunit; + + +namespace WHMapper.Tests.Models; + + +public class MapAdminTests +{ + [Fact] + public void Constructor_ShouldInitializeProperties() + { + // Arrange + var whMap = new WHMap("Test Map"); + whMap.Id = 1; + whMap.WHAccesses.Add(new WHAccess(1,"Test Access")); + + // Act + var mapAdmin = new MapAdmin(whMap); + + // Assert + Assert.Equal(1, mapAdmin.Id); + Assert.Equal("Test Map", mapAdmin.Name); + Assert.NotNull(mapAdmin.WHMapAccesses); + Assert.Single(mapAdmin.WHMapAccesses); + Assert.False(mapAdmin.ShowAccessDetails); + } + + [Fact] + public void Constructor_ShouldHandleNullWHMap() + { + // Act + var mapAdmin = new MapAdmin(null); + + // Assert + Assert.Equal(-1, mapAdmin.Id); + Assert.Equal(string.Empty, mapAdmin.Name); + Assert.Null(mapAdmin.WHMapAccesses); + Assert.False(mapAdmin.ShowAccessDetails); + } + + [Fact] + public void ShowAccessDetails_ShouldBeFalseByDefault() + { + // Arrange + var whMap = new WHMap("Test Map"); + + // Act + var mapAdmin = new MapAdmin(whMap); + + // Assert + Assert.False(mapAdmin.ShowAccessDetails); + } + + [Fact] + public void ShowAccessDetails_ShouldBeSettable() + { + // Arrange + var whMap = new WHMap("Test Map"); + var mapAdmin = new MapAdmin(whMap); + + // Act + mapAdmin.ShowAccessDetails = true; + + // Assert + Assert.True(mapAdmin.ShowAccessDetails); + } +} + diff --git a/src/WHMapper.Tests/Services/Db/DbIntegrationTest.cs b/src/WHMapper.Tests/Services/Db/DbIntegrationTest.cs index fcd4dfb8..5d26f540 100644 --- a/src/WHMapper.Tests/Services/Db/DbIntegrationTest.cs +++ b/src/WHMapper.Tests/Services/Db/DbIntegrationTest.cs @@ -15,7 +15,6 @@ using WHMapper.Repositories.WHSystems; using Xunit.Priority; -using static MudBlazor.CategoryTypes; namespace WHMapper.Tests.Services; @@ -131,6 +130,15 @@ public async Task CRUD_WHMAP() resByBadId = await repo.GetById(-10); Assert.Null(resByBadId); + //getByName + var resByName = await repo.GetByNameAsync(FOOBAR); + Assert.NotNull(resByName); + Assert.Equal(FOOBAR, resByName?.Name); + + //bad getByName + var resBadName = await repo.GetByNameAsync(FOOBAR_UPDATED); + Assert.Null(resBadName); + //update resultById1.Name = FOOBAR_UPDATED; @@ -138,22 +146,31 @@ public async Task CRUD_WHMAP() Assert.NotNull(resultUpdate1); Assert.Equal(FOOBAR_UPDATED, resultUpdate1.Name); + //bad update + var resultUpdateBad = await repo.Update(-10, resultById1); + Assert.Null(resultUpdateBad); + //update dupkicate resultById2.Name = FOOBAR_UPDATED; var resultUpdate2 = await repo.Update(resultById2.Id, resultById2); Assert.Null(resultUpdate2); + //Delete WHMAP Assert.NotNull(result1); var resultDelete1 = await repo.DeleteById(result1.Id); Assert.True(resultDelete1); - Assert.NotNull(result2); - var resultDelete2 = await repo.DeleteById(result2.Id); - Assert.True(resultDelete2); - var resBadDelete = await repo.DeleteById(-10); Assert.False(resBadDelete); + + //delete all + var resultDeleteAll = await repo.DeleteAll(); + Assert.True(resultDeleteAll); + + //nothing to delete all + var resultDeleteAll2 = await repo.DeleteAll(); + Assert.False(resultDeleteAll2); } [Fact, Priority(3)] @@ -584,6 +601,15 @@ public async Task CRUD_WHAdmin() public async Task CRUD_WHAccess() { Assert.NotNull(_contextFactory); + //init MAP + //Create IWHMapRepository + IWHMapRepository repoMap = new WHMapRepository(new NullLogger(),_contextFactory); + + //ADD WHMAP + var map = await repoMap.Create(new WHMap(FOOBAR)); + Assert.NotNull(map); + Assert.Equal(FOOBAR, map?.Name); + //Create AccessRepo IWHAccessRepository repo = new WHAccessRepository(new NullLogger(),_contextFactory); @@ -641,20 +667,62 @@ public async Task CRUD_WHAccess() Assert.Null(resultUpdate2); //Delete - var resultdel1 = await repo.DeleteById(result1.Id); - Assert.True(resultdel1); - var resultdel2 = await repo.DeleteById(result2.Id); Assert.True(resultdel2); var resultBaddel = await repo.DeleteById(-10); Assert.False(resultBaddel); + + //map access + var mapAccess = await repoMap.GetMapAccesses(map.Id); + Assert.NotNull(mapAccess); + Assert.Empty(mapAccess); + + //add access to map + var resultAddMapAccess = await repoMap.AddMapAccess(map.Id, result1.Id); + Assert.True(resultAddMapAccess); + + + Assert.NotNull(map); + mapAccess = await repoMap.GetMapAccesses(map.Id); + Assert.NotNull(mapAccess); + Assert.NotEmpty(mapAccess); + + //delete access from map + var resultDelMapAccess = await repoMap.DeleteMapAccess(map.Id, result1.Id); + Assert.True(resultDelMapAccess); + + //delete all access from map + var resultDelMapAccesses = await repoMap.DeleteMapAccesses(map.Id); + Assert.True(resultDelMapAccesses); + + //dfelete bad access from map + var resultDelBadMapAccess = await repoMap.DeleteMapAccess(-10, result1.Id); + Assert.False(resultDelBadMapAccess); + + //Delete WHMAP + var mapDeleted = await repoMap.DeleteById(map.Id); + Assert.True(mapDeleted); + + //Delete Access + var resultdel1 = await repo.DeleteById(result1.Id); + Assert.True(resultdel1); + } [Fact, Priority(8)] public async Task CRUD_WHNote() { Assert.NotNull(_contextFactory); + //init MAP + //Create IWHMapRepository + IWHMapRepository repoMap = new WHMapRepository(new NullLogger(),_contextFactory); + + //ADD WHMAP + var map = await repoMap.Create(new WHMap(FOOBAR)); + Assert.NotNull(map); + Assert.Equal(FOOBAR, map?.Name); + //Create AccessRepo IWHNoteRepository repo = new WHNoteRepository(new NullLogger(), _contextFactory); @@ -664,21 +732,22 @@ public async Task CRUD_WHNote() Assert.Empty(results); //ADD Note1 - var result1 = await repo.Create(new WHNote(FOOBAR_SYSTEM_ID,FOOBAR)); + Assert.NotNull(map); + var result1 = await repo.Create(new WHNote(map.Id,FOOBAR_SYSTEM_ID,FOOBAR)); Assert.NotNull(result1); Assert.Equal(FOOBAR_SYSTEM_ID, result1.SoloarSystemId); Assert.Equal(FOOBAR, result1.Comment); Assert.Equal(WHSystemStatus.Unknown, result1.SystemStatus); //ADD Note2 - var result2 = await repo.Create(new WHNote(FOOBAR_SYSTEM_ID2,WHSystemStatus.Hostile)); + var result2 = await repo.Create(new WHNote(map.Id,FOOBAR_SYSTEM_ID2,WHSystemStatus.Hostile)); Assert.NotNull(result2); Assert.Equal(FOOBAR_SYSTEM_ID2, result2.SoloarSystemId); Assert.Equal(string.Empty, result2.Comment); Assert.Equal(WHSystemStatus.Hostile,result2.SystemStatus); //ADD Access dupkicate - var resultDuplicate = await repo.Create(new WHNote(FOOBAR_SYSTEM_ID2, FOOBAR)); + var resultDuplicate = await repo.Create(new WHNote(map.Id,FOOBAR_SYSTEM_ID2, FOOBAR)); Assert.Null(resultDuplicate); //GetALL @@ -696,16 +765,15 @@ public async Task CRUD_WHNote() var resultBadById = await repo.GetById(-10); Assert.Null(resultBadById); - //GetBySolarSystemId - var resultBySolarSystemId = await repo.GetBySolarSystemId(FOOBAR_SYSTEM_ID); + //Get + var resultBySolarSystemId = await repo.Get(map.Id,FOOBAR_SYSTEM_ID); Assert.NotNull(resultBySolarSystemId); Assert.Equal(FOOBAR_SYSTEM_ID, resultBySolarSystemId.SoloarSystemId); Assert.Equal(FOOBAR, resultBySolarSystemId.Comment); - var resultBadBySolarSystemId = await repo.GetBySolarSystemId(-10); + var resultBadBySolarSystemId = await repo.Get(map.Id,-10); Assert.Null(resultBadBySolarSystemId); - //update result1.Comment = FOOBAR_SHORT_UPDATED; var resultUpdate1 = await repo.Update(result1.Id, result1); @@ -734,12 +802,25 @@ public async Task CRUD_WHNote() //bad id update var resultUpdateBadId = await repo.Update(-10, result1); Assert.Null(resultUpdateBadId); + + //Delete WHMAP + var mapDeleted = await repoMap.DeleteById(map.Id); + Assert.True(mapDeleted); } [Fact, Priority(9)] public async Task CRUD_WHRoute() { Assert.NotNull(_contextFactory); + //init MAP + //Create IWHMapRepository + IWHMapRepository repoMap = new WHMapRepository(new NullLogger(),_contextFactory); + + //ADD WHMAP + var map = await repoMap.Create(new WHMap(FOOBAR)); + Assert.NotNull(map); + Assert.Equal(FOOBAR, map?.Name); + //Create AccessRepo IWHRouteRepository repo = new WHRouteRepository(new NullLogger(), _contextFactory); @@ -749,20 +830,21 @@ public async Task CRUD_WHRoute() Assert.Empty(results); //ADD Route1 - var result1 = await repo.Create(new WHRoute(FOOBAR_SYSTEM_ID)); + Assert.NotNull(map); + var result1 = await repo.Create(new WHRoute(map.Id,FOOBAR_SYSTEM_ID)); Assert.NotNull(result1); Assert.Equal(FOOBAR_SYSTEM_ID, result1.SolarSystemId); Assert.Null(result1.EveEntityId); //ADD Route2 - var result2 = await repo.Create(new WHRoute(FOOBAR_SYSTEM_ID2, EVE_CORPO_ID)); + var result2 = await repo.Create(new WHRoute(map.Id,FOOBAR_SYSTEM_ID2, EVE_CORPO_ID)); Assert.NotNull(result2); Assert.Equal(FOOBAR_SYSTEM_ID2, result2.SolarSystemId); Assert.Equal(EVE_CORPO_ID, result2.EveEntityId); //ADD Route dupLicate - var resultDuplicate = await repo.Create(new WHRoute(FOOBAR_SYSTEM_ID2, EVE_CORPO_ID)); + var resultDuplicate = await repo.Create(new WHRoute(map.Id,FOOBAR_SYSTEM_ID2, EVE_CORPO_ID)); Assert.Null(resultDuplicate); //GetALL @@ -801,13 +883,13 @@ public async Task CRUD_WHRoute() Assert.False(resultBaddel); //ADD Route1 with eveentityid - var result = await repo.Create(new WHRoute(FOOBAR_SYSTEM_ID, EVE_CHARACTERE_ID)); + var result = await repo.Create(new WHRoute(map.Id,FOOBAR_SYSTEM_ID, EVE_CHARACTERE_ID)); Assert.NotNull(result); Assert.Equal(FOOBAR_SYSTEM_ID, result1.SolarSystemId); Assert.Equal(EVE_CHARACTERE_ID,result1.EveEntityId); //get by eveentityid - var resultByEveEntityId = await repo.GetRoutesByEveEntityId(EVE_CHARACTERE_ID); + var resultByEveEntityId = await repo.GetRoutesByEveEntityId(map.Id,EVE_CHARACTERE_ID); Assert.NotNull(resultByEveEntityId); Assert.NotEmpty(resultByEveEntityId); @@ -823,6 +905,10 @@ public async Task CRUD_WHRoute() var resultdel = await repo.DeleteById(result.Id); Assert.True(resultdel); + //Delete WHMAP + var mapDeleted = await repoMap.DeleteById(map.Id); + Assert.True(mapDeleted); + } [Fact, Priority(10)] @@ -919,5 +1005,27 @@ public async Task CRUD_WHJumpLog() //clean map var mapDeleted = await repoMap.DeleteById(map.Id); } + + [Fact, Priority(12)] + public async Task CRUD_WHJumpMassLog() + { + Assert.NotNull(_contextFactory); + + //init MAP + //Create IWHMapRepository + IWHMapRepository repoMap = new WHMapRepository(new NullLogger(),_contextFactory); + + //ADD WHMAP + var map = await repoMap.Create(new WHMap(FOOBAR)); + Assert.NotNull(map); + Assert.Equal(FOOBAR, map?.Name); + } + + + + + + + } diff --git a/src/WHMapper.Tests/Services/EveMapper/EveMapperAccessHelperTests.cs b/src/WHMapper.Tests/Services/EveMapper/EveMapperAccessHelperTests.cs index 5151a811..a4ccf370 100644 --- a/src/WHMapper.Tests/Services/EveMapper/EveMapperAccessHelperTests.cs +++ b/src/WHMapper.Tests/Services/EveMapper/EveMapperAccessHelperTests.cs @@ -130,5 +130,34 @@ EveMapperAccessHelper sut Assert.True(await sut.IsEveMapperUserAccessAuthorized(characterId)); } #endregion + + #region IsEveMapperMapAccessAuthorized() + [Theory] + [InlineAutoMoqData(1, 1)] + [InlineAutoMoqData(10000, 10000)] + [InlineAutoMoqData(int.MinValue, int.MinValue)] + [InlineAutoMoqData(int.MaxValue, int.MaxValue)] + public async Task IfAccessRepositoryIsPopulatedGettingKnownCharacterIdAndMapId_WhenGettingMapAccess_ReturnsExpectedResult( + int mapId, + int characterId, + WHAdmin wHAdmin, + [Frozen] Mock accessRepository, + EveMapperAccessHelper sut + ) + { + // Arrange + wHAdmin.EveCharacterId = characterId; + var accessRepositoryReturn = Task.FromResult(new List() { wHAdmin } as IEnumerable); + accessRepository.Setup(x => x.GetAll()).Returns(accessRepositoryReturn!); + + // Act + var result = await sut.IsEveMapperMapAccessAuthorized(mapId, characterId); + + // Assert + Assert.True(result); + } + + #endregion + } } diff --git a/src/WHMapper.Tests/Services/EveOnlineAPI/PublicEveOnlineAPITest.cs b/src/WHMapper.Tests/Services/EveOnlineAPI/PublicEveOnlineAPITest.cs index aa81c89e..2e16488f 100644 --- a/src/WHMapper.Tests/Services/EveOnlineAPI/PublicEveOnlineAPITest.cs +++ b/src/WHMapper.Tests/Services/EveOnlineAPI/PublicEveOnlineAPITest.cs @@ -1,5 +1,4 @@ -using System; -using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; using WHMapper.Models.DTO.EveAPI.Route.Enums; using WHMapper.Services.EveAPI.Alliances; using WHMapper.Services.EveAPI.Characters; diff --git a/src/WHMapper.Tests/Services/SDE/SdeServiceManagerIntegrationTests.cs b/src/WHMapper.Tests/Services/SDE/SdeServiceManagerIntegrationTests.cs index de7166cf..8154c391 100644 --- a/src/WHMapper.Tests/Services/SDE/SdeServiceManagerIntegrationTests.cs +++ b/src/WHMapper.Tests/Services/SDE/SdeServiceManagerIntegrationTests.cs @@ -1,5 +1,4 @@ using System.IO.Abstractions; -using Testably.Abstractions; using Microsoft.Extensions.Caching.Distributed; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; diff --git a/src/WHMapper.Tests/WHHelper/EveWHAccessHelperTest.cs b/src/WHMapper.Tests/WHHelper/EveWHAccessHelperTest.cs index f94b4403..5e525a33 100644 --- a/src/WHMapper.Tests/WHHelper/EveWHAccessHelperTest.cs +++ b/src/WHMapper.Tests/WHHelper/EveWHAccessHelperTest.cs @@ -1,21 +1,15 @@ -using System; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Internal; +using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using WHMapper.Data; using WHMapper.Models.Db; using WHMapper.Models.Db.Enums; using WHMapper.Repositories.WHAccesses; using WHMapper.Repositories.WHAdmins; -using WHMapper.Services.Anoik; -using WHMapper.Services.EveAPI; +using WHMapper.Repositories.WHMaps; using WHMapper.Services.EveAPI.Characters; -using WHMapper.Services.EveAPI.Universe; using WHMapper.Services.EveMapper; -using WHMapper.Services.SDE; using Xunit.Priority; namespace WHMapper.Tests.WHHelper; @@ -34,6 +28,7 @@ public class EveWHAccessHelperTest private IEveMapperAccessHelper? _accessHelper; private IWHAccessRepository? _whAccessRepository; private IWHAdminRepository? _whAdminRepository; + private IWHMapRepository? _whMapRepository; @@ -62,7 +57,8 @@ public EveWHAccessHelperTest() { _whAccessRepository = new WHAccessRepository(new NullLogger(), _contextFactory); _whAdminRepository = new WHAdminRepository(new NullLogger(), _contextFactory); - _accessHelper = new EveMapperAccessHelper(_whAccessRepository, _whAdminRepository, new CharacterServices(httpclientfactory.CreateClient())); + _whMapRepository = new WHMapRepository(new NullLogger(), _contextFactory); + _accessHelper = new EveMapperAccessHelper(_whAccessRepository, _whAdminRepository,_whMapRepository, new CharacterServices(httpclientfactory.CreateClient())); } } @@ -168,6 +164,48 @@ public async Task Eve_Mapper_Admin_Access() await _whAdminRepository.DeleteById(character.Id); } + [Fact, Priority(6)] + public async Task Eve_Mapper_Map_Access() + { + Assert.NotNull(_accessHelper); + Assert.NotNull(_whMapRepository); + Assert.NotNull(_whAccessRepository); + + + var map = await _whMapRepository.Create(new WHMap("MAP")); + Assert.NotNull(map); + Assert.Equal("MAP", map.Name); + Assert.Empty(map.WHAccesses); + + + var fullAuthorize = await _accessHelper.IsEveMapperMapAccessAuthorized(EVE_CHARACTERE_ID,map.Id); + Assert.True(fullAuthorize); + + //add access to evemap lock all maps + var characterAccess = await _whAccessRepository.Create(new WHAccess(EVE_CHARACTERE_ID, "TOTO",WHAccessEntity.Character)); + Assert.NotNull(characterAccess); + Assert.Equal(EVE_CHARACTERE_ID, characterAccess.EveEntityId); + + var notAuthorize1 = await _accessHelper.IsEveMapperMapAccessAuthorized(EVE_CHARACTERE_ID,map.Id); + Assert.False(notAuthorize1); + + var notAuthorize2 = await _accessHelper.IsEveMapperMapAccessAuthorized(EVE_CHARACTERE_ID2,map.Id); + Assert.False(notAuthorize2); + + //add access to evemap only for user1 + map.WHAccesses.Add(characterAccess); + await _whMapRepository.Update(map.Id,map); + + var authorize1 = await _accessHelper.IsEveMapperMapAccessAuthorized(EVE_CHARACTERE_ID,map.Id); + Assert.True(authorize1); + + var notAuthorize2_2 = await _accessHelper.IsEveMapperMapAccessAuthorized(EVE_CHARACTERE_ID2,map.Id); + Assert.False(notAuthorize2_2); + + await _whMapRepository.DeleteById(map.Id); + } + + } diff --git a/src/WHMapper.Tests/WHHelper/EveWHMapperRoutePlannerHelperTest.cs b/src/WHMapper.Tests/WHHelper/EveWHMapperRoutePlannerHelperTest.cs index f031c48f..58c9de75 100644 --- a/src/WHMapper.Tests/WHHelper/EveWHMapperRoutePlannerHelperTest.cs +++ b/src/WHMapper.Tests/WHHelper/EveWHMapperRoutePlannerHelperTest.cs @@ -7,13 +7,13 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using WHMapper.Data; +using WHMapper.Models.Db; +using WHMapper.Models.DTO.EveAPI.Assets; using WHMapper.Models.DTO.EveAPI.Route.Enums; using WHMapper.Models.DTO.RoutePlanner; -using WHMapper.Repositories.WHNotes; -using WHMapper.Services.Anoik; +using WHMapper.Repositories.WHMaps; using WHMapper.Services.Cache; using WHMapper.Services.EveAPI; -using WHMapper.Services.EveMapper; using WHMapper.Services.SDE; using Xunit.Priority; @@ -31,6 +31,8 @@ public class EveWHMapperRoutePlannerHelperTest private const int SOLAR_SYSTEM_WH_ID = 31001123; private IEveMapperRoutePlannerHelper _eveMapperRoutePlannerHelper = null!; + private IWHMapRepository? _whMapRepository = null!; + private WHMap? _defaultMAp = null!; public EveWHMapperRoutePlannerHelperTest() { @@ -71,10 +73,17 @@ public EveWHMapperRoutePlannerHelperTest() ICacheService cacheService = new CacheService(loggerCacheService, _distriCache); IFileSystem fileSystem = new FileSystem(); - HttpClient httpClient = new HttpClient() { BaseAddress = new Uri(configuration.GetValue("SdeDataSupplier:BaseUrl")) }; + var baseUrl = configuration.GetValue("SdeDataSupplier:BaseUrl"); + if (string.IsNullOrEmpty(baseUrl)) + { + throw new ArgumentNullException(nameof(baseUrl), "Base URL for SDE Data Supplier cannot be null or empty."); + } + HttpClient httpClient = new HttpClient() { BaseAddress = new Uri(baseUrl) }; ISDEDataSupplier dataSupplier = new SdeDataSupplier(new NullLogger(), httpClient); ISDEService sdeServices = new SDEService(loggerSDE, cacheService); + _whMapRepository = new WHMapRepository(new NullLogger(), _contextFactory); + _eveMapperRoutePlannerHelper = new EveMapperRoutePlannerHelper(logger, whRouteRepository, null!, @@ -85,7 +94,15 @@ public EveWHMapperRoutePlannerHelperTest() [Fact, Priority(1)] public async Task Add_Delete_Route() { - var result = await _eveMapperRoutePlannerHelper.AddRoute(SOLAR_SYSTEM_AHBAZON_ID,true); + + if(_defaultMAp == null) + { + Assert.NotNull(_whMapRepository); + _defaultMAp = await _whMapRepository.Create(new WHMapper.Models.Db.WHMap("Default")); + Assert.NotNull(_defaultMAp); + } + + var result = await _eveMapperRoutePlannerHelper.AddRoute(_defaultMAp.Id,SOLAR_SYSTEM_AHBAZON_ID,true); Assert.NotNull(result); Assert.Equal(SOLAR_SYSTEM_AHBAZON_ID,result.SolarSystemId); Assert.Null(result.EveEntityId); @@ -96,9 +113,13 @@ public async Task Add_Delete_Route() var result3 = await _eveMapperRoutePlannerHelper.DeleteRoute(-10); Assert.False(result3); - var myRouteNull = await _eveMapperRoutePlannerHelper.AddRoute(SOLAR_SYSTEM_AHBAZON_ID,false); + var myRouteNull = await _eveMapperRoutePlannerHelper.AddRoute(_defaultMAp.Id,SOLAR_SYSTEM_AHBAZON_ID,false); Assert.Null(myRouteNull); + //clean whmap + Assert.NotNull(_whMapRepository); + await _whMapRepository.DeleteById(_defaultMAp.Id); + } @@ -107,19 +128,26 @@ public async Task Add_Delete_Route() [Fact, Priority(2)] public async Task Get_Route() { - var badRoute = await _eveMapperRoutePlannerHelper.GetMyRoutes(123456789,RouteType.Shortest, null); + if(_defaultMAp == null) + { + Assert.NotNull(_whMapRepository); + _defaultMAp = await _whMapRepository.Create(new WHMapper.Models.Db.WHMap("Default")); + Assert.NotNull(_defaultMAp); + } + + var badRoute = await _eveMapperRoutePlannerHelper.GetMyRoutes(_defaultMAp.Id,123456789,RouteType.Shortest, null); Assert.Null(badRoute); - var myRoutes = await _eveMapperRoutePlannerHelper.GetMyRoutes(SOLAR_SYSTEM_JITA_ID,RouteType.Shortest, null); + var myRoutes = await _eveMapperRoutePlannerHelper.GetMyRoutes(_defaultMAp.Id,SOLAR_SYSTEM_JITA_ID,RouteType.Shortest, null); Assert.Null(myRoutes); - var routes = await _eveMapperRoutePlannerHelper.GetRoutesForAll(SOLAR_SYSTEM_WH_ID,RouteType.Shortest, null); + var routes = await _eveMapperRoutePlannerHelper.GetRoutesForAll(_defaultMAp.Id,SOLAR_SYSTEM_WH_ID,RouteType.Shortest, null); Assert.NotNull(routes); Assert.Empty(routes); - var result = await _eveMapperRoutePlannerHelper.AddRoute(SOLAR_SYSTEM_AHBAZON_ID,true); + var result = await _eveMapperRoutePlannerHelper.AddRoute(_defaultMAp.Id,SOLAR_SYSTEM_AHBAZON_ID,true); - routes = await _eveMapperRoutePlannerHelper.GetRoutesForAll(SOLAR_SYSTEM_JITA_ID,RouteType.Shortest, null); + routes = await _eveMapperRoutePlannerHelper.GetRoutesForAll(_defaultMAp.Id,SOLAR_SYSTEM_JITA_ID,RouteType.Shortest, null); Assert.NotNull(routes); Assert.NotEmpty(routes); var route_JITA_AHBAZON = routes.FirstOrDefault(); @@ -129,7 +157,7 @@ public async Task Get_Route() Assert.NotNull(route_JITA_AHBAZON.Route); Assert.Equal(5,route_JITA_AHBAZON.RouteLength); - routes = await _eveMapperRoutePlannerHelper.GetRoutesForAll(SOLAR_SYSTEM_WH_ID,RouteType.Shortest, new BlockingCollection + routes = await _eveMapperRoutePlannerHelper.GetRoutesForAll(_defaultMAp.Id,SOLAR_SYSTEM_WH_ID,RouteType.Shortest, new BlockingCollection { new RouteConnection(SOLAR_SYSTEM_WH_ID,-1.0f,SOLAR_SYSTEM_AHBAZON_ID,0.4f), new RouteConnection(SOLAR_SYSTEM_AHBAZON_ID,0.4f,SOLAR_SYSTEM_WH_ID,-1.0f) @@ -143,7 +171,7 @@ public async Task Get_Route() Assert.NotNull(route_WH_AHBAZON.Route); Assert.Equal(2,route_WH_AHBAZON.RouteLength); - routes = await _eveMapperRoutePlannerHelper.GetRoutesForAll(SOLAR_SYSTEM_JITA_ID,RouteType.Shortest,new BlockingCollection + routes = await _eveMapperRoutePlannerHelper.GetRoutesForAll(_defaultMAp.Id,SOLAR_SYSTEM_JITA_ID,RouteType.Shortest,new BlockingCollection { new RouteConnection(SOLAR_SYSTEM_WH_ID,-1.0f,SOLAR_SYSTEM_AHBAZON_ID,0.4f), new RouteConnection(SOLAR_SYSTEM_AHBAZON_ID,0.4f,SOLAR_SYSTEM_WH_ID,-1.0f), @@ -162,9 +190,9 @@ public async Task Get_Route() var result2 = await _eveMapperRoutePlannerHelper.DeleteRoute(result!.Id); Assert.True(result2); - result = await _eveMapperRoutePlannerHelper.AddRoute(SOLAR_SYSTEM_AMARR_ID,true); + result = await _eveMapperRoutePlannerHelper.AddRoute(_defaultMAp.Id,SOLAR_SYSTEM_AMARR_ID,true); - routes = await _eveMapperRoutePlannerHelper.GetRoutesForAll(SOLAR_SYSTEM_JITA_ID,RouteType.Secure, null); + routes = await _eveMapperRoutePlannerHelper.GetRoutesForAll(_defaultMAp.Id,SOLAR_SYSTEM_JITA_ID,RouteType.Secure, null); Assert.NotNull(routes); Assert.NotEmpty(routes); var route_JITA_AMARR = routes.FirstOrDefault(); @@ -176,6 +204,10 @@ public async Task Get_Route() result2 = await _eveMapperRoutePlannerHelper.DeleteRoute(result!.Id); Assert.True(result2); + + //clean whmap + Assert.NotNull(_whMapRepository); + await _whMapRepository.DeleteById(_defaultMAp.Id); } } diff --git a/src/WHMapper.Tests/WHHelper/WHColorHelperTest.cs b/src/WHMapper.Tests/WHHelper/WHColorHelperTest.cs index 7cd84ab4..08b23965 100644 --- a/src/WHMapper.Tests/WHHelper/WHColorHelperTest.cs +++ b/src/WHMapper.Tests/WHHelper/WHColorHelperTest.cs @@ -1,7 +1,5 @@ -using System; -using WHMapper.Models.Db.Enums; +using WHMapper.Models.Db.Enums; using WHMapper.Models.DTO.EveMapper.Enums; -using WHMapper.Services.EveAPI.Universe; using WHMapper.Services.WHColor; using Xunit.Priority; diff --git a/src/WHMapper.Tests/WHHelper/WHSignatureHelperTest.cs b/src/WHMapper.Tests/WHHelper/WHSignatureHelperTest.cs index 115b7278..ce8dd181 100644 --- a/src/WHMapper.Tests/WHHelper/WHSignatureHelperTest.cs +++ b/src/WHMapper.Tests/WHHelper/WHSignatureHelperTest.cs @@ -1,9 +1,7 @@ -using System; -using System.Collections.ObjectModel; +using System.Collections.ObjectModel; using WHMapper.Models.Db; using WHMapper.Models.Db.Enums; using WHMapper.Models.DTO.EveMapper.Enums; -using WHMapper.Services.WHColor; using WHMapper.Services.WHSignature; using WHMapper.Services.WHSignatures; using Xunit.Priority; diff --git a/src/WHMapper.Tests/WHMapper.Tests.csproj b/src/WHMapper.Tests/WHMapper.Tests.csproj index b70e1c0f..22b8c142 100644 --- a/src/WHMapper.Tests/WHMapper.Tests.csproj +++ b/src/WHMapper.Tests/WHMapper.Tests.csproj @@ -12,21 +12,21 @@ - - - - - - + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive all - + runtime; build; native; contentfiles; analyzers; buildtransitive all - + diff --git a/src/WHMapper/Data/WHMapperContext.cs b/src/WHMapper/Data/WHMapperContext.cs index 8b0001e1..4d0649e7 100644 --- a/src/WHMapper/Data/WHMapperContext.cs +++ b/src/WHMapper/Data/WHMapperContext.cs @@ -24,18 +24,20 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity().ToTable("Maps"); modelBuilder.Entity().HasIndex(x => new { x.Name }).IsUnique(true); - modelBuilder.Entity().HasMany(x => x.WHSystems).WithOne().HasForeignKey(x => x.WHMapId).IsRequired().OnDelete(DeleteBehavior.Cascade);; - modelBuilder.Entity().HasMany(x => x.WHSystemLinks).WithOne().HasForeignKey(x => x.WHMapId).IsRequired().OnDelete(DeleteBehavior.Cascade);; + modelBuilder.Entity().HasMany(x => x.WHSystems).WithOne().HasForeignKey(x => x.WHMapId).IsRequired().OnDelete(DeleteBehavior.Cascade); + modelBuilder.Entity().HasMany(x => x.WHSystemLinks).WithOne().HasForeignKey(x => x.WHMapId).IsRequired().OnDelete(DeleteBehavior.Cascade); + modelBuilder.Entity().HasMany(x => x.WHAccesses).WithMany(); + modelBuilder.Entity().ToTable("Systems"); - modelBuilder.Entity().HasIndex(x => new { x.SoloarSystemId }).IsUnique(true); - modelBuilder.Entity().HasIndex(x => new { x.Name }).IsUnique(true); + modelBuilder.Entity().HasIndex(x => new { x.WHMapId,x.SoloarSystemId }).IsUnique(true); + modelBuilder.Entity().HasIndex(x => new { x.WHMapId,x.Name }).IsUnique(true); modelBuilder.Entity().HasOne().WithMany(x => x.WHSystems).HasForeignKey(x =>x.WHMapId).IsRequired().OnDelete(DeleteBehavior.Cascade); modelBuilder.Entity().HasMany().WithOne().HasForeignKey(x=>x.IdWHSystemFrom).OnDelete(DeleteBehavior.Cascade); modelBuilder.Entity().HasMany().WithOne().HasForeignKey(x => x.IdWHSystemTo).OnDelete(DeleteBehavior.Cascade); modelBuilder.Entity().ToTable("SystemLinks"); - modelBuilder.Entity().HasIndex(x => new { x.IdWHSystemFrom, x.IdWHSystemTo }).IsUnique(true); + modelBuilder.Entity().HasIndex(x => new { x.WHMapId,x.IdWHSystemFrom, x.IdWHSystemTo }).IsUnique(true); modelBuilder.Entity().HasOne().WithMany(x => x.WHSystemLinks).HasForeignKey(x =>x.WHMapId).IsRequired().OnDelete(DeleteBehavior.Cascade); modelBuilder.Entity().HasMany(x=>x.JumpHistory).WithOne().HasForeignKey(x => x.WHSystemLinkId).IsRequired().OnDelete(DeleteBehavior.Cascade); @@ -45,10 +47,12 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) modelBuilder.Entity().HasOne().WithMany(x => x.WHSignatures).HasForeignKey(x=>x.WHId).IsRequired().OnDelete(DeleteBehavior.Cascade); modelBuilder.Entity().ToTable("Notes"); - modelBuilder.Entity().HasIndex(x => new { x.SoloarSystemId }).IsUnique(true); + modelBuilder.Entity().HasOne().WithMany().HasForeignKey(x => x.MapId).IsRequired().OnDelete(DeleteBehavior.Cascade); + modelBuilder.Entity().HasIndex(x => new { x.MapId, x.SoloarSystemId }).IsUnique(true); modelBuilder.Entity().ToTable("Routes"); - modelBuilder.Entity().HasIndex(x => new { x.SolarSystemId,x.EveEntityId }).IsUnique(true); + modelBuilder.Entity().HasOne().WithMany().HasForeignKey(x => x.MapId).IsRequired().OnDelete(DeleteBehavior.Cascade); + modelBuilder.Entity().HasIndex(x => new { x.MapId,x.SolarSystemId,x.EveEntityId }).IsUnique(true); modelBuilder.Entity().ToTable("JumpLogs"); modelBuilder.Entity().HasIndex(x => new { x.CharacterId, x.JumpDate }).IsUnique(true); diff --git a/src/WHMapper/FeatureFlag.cs b/src/WHMapper/FeatureFlag.cs deleted file mode 100644 index 365422c1..00000000 --- a/src/WHMapper/FeatureFlag.cs +++ /dev/null @@ -1,18 +0,0 @@ -#define DISABLE_MULTI_MAP - -using System; -namespace WHMapper -{ - public static class FeatureFlag - { - public static bool DISABLE_MULTI_MAP() - { - bool value = false; - #if (DISABLE_MULTI_MAP) - value = true; - #endif - return value; - } - } -} - diff --git a/src/WHMapper/Hubs/IWHMapperNotificationHub.cs b/src/WHMapper/Hubs/IWHMapperNotificationHub.cs index 67abd94e..8269411c 100644 --- a/src/WHMapper/Hubs/IWHMapperNotificationHub.cs +++ b/src/WHMapper/Hubs/IWHMapperNotificationHub.cs @@ -1,6 +1,4 @@ -using System; -using System.Collections.Generic; -using WHMapper.Models.Db.Enums; +using WHMapper.Models.Db.Enums; namespace WHMapper.Hubs { @@ -8,18 +6,26 @@ public interface IWHMapperNotificationHub { Task NotifyUserConnected(string userName); Task NotifyUserDisconnected(string userName); - Task NotifyUserPosition(string userName,string systemName); + Task NotifyUserPosition(string userName,int mapId,int wormholeId); Task NotifyWormoleAdded(string userName, int mapId,int wormholeId); Task NotifyWormholeRemoved(string userName, int mapId,int wormholeId); Task NotifyLinkAdded(string userName, int mapId, int linkId); Task NotifyLinkRemoved(string userName, int mapId, int linkId); - Task NotifyUsersPosition(IDictionary connectedUsersPosition); Task NotifyWormoleMoved(string userName, int mapId, int wormholeId,double posx,double posy); Task NotifyLinkChanged(string username,int mapId, int linkId, bool eol, SystemLinkSize size, SystemLinkMassStatus mass); Task NotifyWormholeNameExtensionChanged(string username, int mapId, int wormholeId,bool increment); Task NotifyWormholeSignaturesChanged(string username, int mapId, int wormholeId); Task NotifyWormholeLockChanged(string username, int mapId, int wormholeId, bool locked); Task NotifyWormholeSystemStatusChanged(string username, int mapId, int wormholeId, WHSystemStatus systemStatus); + Task NotifyMapAdded(string userName, int mapId); + Task NotifyMapRemoved(string userName, int mapId); + Task NotifyMapNameChanged(string userName, int mapId, string newName); + Task NotifyAllMapsRemoved(string userName); + Task NotifyMapAccessesAdded(string userName, int mapId, IEnumerable accessId); + Task NotifyMapAccessRemoved(string userName, int mapId, int accessId); + Task NotifyMapAllAccessesRemoved(string userName, int mapId); + Task NotifyUserOnMapConnected(string userName, int mapId); + Task NotifyUserOnMapDisconnected(string userName, int mapId); } } diff --git a/src/WHMapper/Hubs/WHMapperNotificationHub.cs b/src/WHMapper/Hubs/WHMapperNotificationHub.cs index 7f4a908c..f0a8074d 100644 --- a/src/WHMapper/Hubs/WHMapperNotificationHub.cs +++ b/src/WHMapper/Hubs/WHMapperNotificationHub.cs @@ -1,177 +1,259 @@ -using System; -using System.Collections.Concurrent; -using System.ComponentModel.DataAnnotations; -using System.Security.Claims; -using Microsoft.AspNetCore.Authentication.Cookies; -using Microsoft.AspNetCore.Authentication.JwtBearer; +using System.Collections.Concurrent; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.SignalR; -using WHMapper.Models.Db; using WHMapper.Models.Db.Enums; using WHMapper.Services.EveJwkExtensions; -using WHMapper.Services.EveOnlineUserInfosProvider; -using static MudBlazor.CategoryTypes; -namespace WHMapper.Hubs +namespace WHMapper.Hubs; + +[Authorize(AuthenticationSchemes = EveOnlineJwkDefaults.AuthenticationScheme)] +public class WHMapperNotificationHub : Hub { - [Authorize(AuthenticationSchemes = EveOnlineJwkDefaults.AuthenticationScheme)] - public class WHMapperNotificationHub : Hub - { - private readonly static ConnectionMapping _connections = new ConnectionMapping(); - private readonly static ConcurrentDictionary _connectedUserPosition = new ConcurrentDictionary(); + private readonly static ConnectionMapping _connections = new ConnectionMapping(); + private readonly static ConcurrentDictionary?> _connectedUserPosition = new ConcurrentDictionary?>(); - private string CurrentUser() + private string CurrentUser() + { + if (Context != null && Context.User != null) { - if (Context != null && Context.User != null) - { - var nameRes = Context.User.FindFirst("name"); - if (nameRes != null) - return nameRes.Value; - } - return string.Empty; + var nameRes = Context.User.FindFirst("name"); + if (nameRes != null) + return nameRes.Value; } + return string.Empty; + } - public override async Task OnConnectedAsync() + public override async Task OnConnectedAsync() + { + + string userName = CurrentUser(); + _connections.Add(userName, Context.ConnectionId); + + if(!_connectedUserPosition.ContainsKey(userName)) { - string userName = CurrentUser(); - _connections.Add(userName, Context.ConnectionId); - - if(!_connectedUserPosition.ContainsKey(userName)) - { - while (!_connectedUserPosition.TryAdd(userName, string.Empty)) - await Task.Delay(1); - } - await base.OnConnectedAsync(); - await Clients.AllExcept(Context.ConnectionId).NotifyUserConnected(userName); - await Clients.Caller.NotifyUsersPosition(_connectedUserPosition); - + while (!_connectedUserPosition.TryAdd(userName, null)) + await Task.Delay(1); } + await base.OnConnectedAsync(); + await Clients.AllExcept(Context.ConnectionId).NotifyUserConnected(userName); + } - public override async Task OnDisconnectedAsync(Exception? exception) + public override async Task OnDisconnectedAsync(Exception? exception) + { + + string userName = CurrentUser(); + _connections.Remove(userName, Context.ConnectionId); + + if (_connectedUserPosition.ContainsKey(userName) && _connections.GetConnections(userName).Count() == 0) { - string userName = CurrentUser(); - _connections.Remove(userName, Context.ConnectionId); - - if (_connectedUserPosition.ContainsKey(userName)) - { - while (!_connectedUserPosition.TryRemove(userName, out _)) - await Task.Delay(1); - } + while (!_connectedUserPosition.TryRemove(userName, out _)) + await Task.Delay(1); await Clients.AllExcept(Context.ConnectionId).NotifyUserDisconnected(userName); - await base.OnDisconnectedAsync(exception); } - public async Task SendUserPosition(string systemName) + + await base.OnDisconnectedAsync(exception); + } + + public async Task SendUserPosition(int mapId,int wormholeId) + { + string userName = CurrentUser(); + if (_connectedUserPosition.ContainsKey(userName)) { - string userName = CurrentUser(); - if (_connectedUserPosition.ContainsKey(userName)) - { - string? res = string.Empty; - while (!_connectedUserPosition.TryGetValue(userName, out res)) - await Task.Delay(1); + KeyValuePair? res = null; + while (!_connectedUserPosition.TryGetValue(userName, out res)) + await Task.Delay(1); - while (!_connectedUserPosition.TryUpdate(userName, systemName, res)) - await Task.Delay(1); - } + while (!_connectedUserPosition.TryUpdate(userName, new KeyValuePair(mapId,wormholeId), res)) + await Task.Delay(1); + } + + await Clients.AllExcept(Context.ConnectionId).NotifyUserPosition(userName, mapId, wormholeId); + } + + public async Task SendWormholeAdded(int mapId, int wowrmholeId) + { + string userName = CurrentUser(); + if (!string.IsNullOrEmpty(userName)) + { + await Clients.AllExcept(Context.ConnectionId).NotifyWormoleAdded(userName, mapId, wowrmholeId); + } + + } + + public async Task SendWormholeRemoved(int mapId, int wowrmholeId) + { + string userName = CurrentUser(); + if (!string.IsNullOrEmpty(userName)) + { + await Clients.AllExcept(Context.ConnectionId).NotifyWormholeRemoved(userName, mapId, wowrmholeId); + } + } + + public async Task SendLinkAdded(int mapId, int linkId) + { + string userName = CurrentUser(); + if (!string.IsNullOrEmpty(userName)) + { + await Clients.AllExcept(Context.ConnectionId).NotifyLinkAdded(userName, mapId, linkId); + } + } + + public async Task SendLinkRemoved(int mapId, int linkId) + { + string userName = CurrentUser(); + if (!string.IsNullOrEmpty(userName)) + { + await Clients.AllExcept(Context.ConnectionId).NotifyLinkRemoved(userName, mapId, linkId); + } + } + + public async Task SendWormholeMoved(int mapId, int wowrmholeId, double posX, double posY) + { + string userName = CurrentUser(); + if (!string.IsNullOrEmpty(userName)) + { + await Clients.AllExcept(Context.ConnectionId).NotifyWormoleMoved(userName, mapId, wowrmholeId, posX, posY); + } + } - await Clients.AllExcept(Context.ConnectionId).NotifyUserPosition(userName, systemName); + + public async Task SendLinkChanged(int mapId, int linkId, bool eol, SystemLinkSize size, SystemLinkMassStatus mass) + { + string userName = CurrentUser(); + if (!string.IsNullOrEmpty(userName)) + { + await Clients.AllExcept(Context.ConnectionId).NotifyLinkChanged(userName, mapId, linkId, eol, size, mass); } + } - public async Task SendWormholeAdded(int mapId, int wowrmholeId) + public async Task SendWormholeNameExtensionChanged(int mapId, int wowrmholeId,bool increment) + { + string userName = CurrentUser(); + if (!string.IsNullOrEmpty(userName)) { - string userName = CurrentUser(); - if (!string.IsNullOrEmpty(userName)) - { - await Clients.AllExcept(Context.ConnectionId).NotifyWormoleAdded(userName, mapId, wowrmholeId); - } - + await Clients.AllExcept(Context.ConnectionId).NotifyWormholeNameExtensionChanged(userName, mapId, wowrmholeId,increment); } - public async Task SendWormholeRemoved(int mapId, int wowrmholeId) + } + + public async Task SendWormholeSignaturesChanged(int mapId, int wowrmholeId) + { + string userName = CurrentUser(); + if (!string.IsNullOrEmpty(userName)) { - string userName = CurrentUser(); - if (!string.IsNullOrEmpty(userName)) - { - await Clients.AllExcept(Context.ConnectionId).NotifyWormholeRemoved(userName, mapId, wowrmholeId); - } + await Clients.AllExcept(Context.ConnectionId).NotifyWormholeSignaturesChanged(userName, mapId, wowrmholeId); } + } - public async Task SendLinkAdded(int mapId, int linkId) + public async Task SendWormholeLockChanged(int mapId, int wormholeId, bool locked) + { + string userName = CurrentUser(); + if (!string.IsNullOrEmpty(userName)) { - string userName = CurrentUser(); - if (!string.IsNullOrEmpty(userName)) - { - await Clients.AllExcept(Context.ConnectionId).NotifyLinkAdded(userName, mapId, linkId); - } + await Clients.AllExcept(Context.ConnectionId).NotifyWormholeLockChanged(userName, mapId, wormholeId, locked); } + } - public async Task SendLinkRemoved(int mapId, int linkId) + public async Task SendWormholeSystemStatusChanged(int mapId, int wormholeId, WHSystemStatus systemStatus) + { + string userName = CurrentUser(); + if (!string.IsNullOrEmpty(userName)) { - string userName = CurrentUser(); - if (!string.IsNullOrEmpty(userName)) - { - await Clients.AllExcept(Context.ConnectionId).NotifyLinkRemoved(userName, mapId, linkId); - } + await Clients.AllExcept(Context.ConnectionId).NotifyWormholeSystemStatusChanged(userName, mapId, wormholeId, systemStatus); } + } + + public Task?>> GetConnectedUsersPosition() + { + return Task.FromResult?>>(_connectedUserPosition); + } - public async Task SendWormholeMoved(int mapId, int wowrmholeId, double posX, double posY) + public async Task SendMapAdded(int mapId) + { + string userName = CurrentUser(); + if (!string.IsNullOrEmpty(userName)) { - string userName = CurrentUser(); - if (!string.IsNullOrEmpty(userName)) - { - await Clients.AllExcept(Context.ConnectionId).NotifyWormoleMoved(userName, mapId, wowrmholeId, posX, posY); - } + await Clients.All.NotifyMapAdded(userName, mapId); } + } + public async Task SendMapRemoved(int mapId) + { + string userName = CurrentUser(); + if (!string.IsNullOrEmpty(userName)) + { + await Clients.All.NotifyMapRemoved(userName, mapId); + } + } - public async Task SendLinkChanged(int mapId, int linkId, bool eol, SystemLinkSize size, SystemLinkMassStatus mass) + public async Task SendMapNameChanged(int mapId, string newName) + { + string userName = CurrentUser(); + if (!string.IsNullOrEmpty(userName)) { - string userName = CurrentUser(); - if (!string.IsNullOrEmpty(userName)) - { - await Clients.AllExcept(Context.ConnectionId).NotifyLinkChanged(userName, mapId, linkId, eol, size, mass); - } + await Clients.All.NotifyMapNameChanged(userName, mapId, newName); } + } - public async Task SendWormholeNameExtensionChanged(int mapId, int wowrmholeId,bool increment) + public async Task SendAllMapsRemoved() + { + string userName = CurrentUser(); + if (!string.IsNullOrEmpty(userName)) { - string userName = CurrentUser(); - if (!string.IsNullOrEmpty(userName)) - { - await Clients.AllExcept(Context.ConnectionId).NotifyWormholeNameExtensionChanged(userName, mapId, wowrmholeId,increment); - } + await Clients.All.NotifyAllMapsRemoved(userName); + } + } + public async Task SendMapAccessesAdded(int mapId, IEnumerable accessId) + { + string userName = CurrentUser(); + if (!string.IsNullOrEmpty(userName)) + { + await Clients.All.NotifyMapAccessesAdded(userName, mapId, accessId); } + } - public async Task SendWormholeSignaturesChanged(int mapId, int wowrmholeId) + public async Task SendMapAccessRemoved(int mapId, int accessId) + { + string userName = CurrentUser(); + if (!string.IsNullOrEmpty(userName)) { - string userName = CurrentUser(); - if (!string.IsNullOrEmpty(userName)) - { - await Clients.AllExcept(Context.ConnectionId).NotifyWormholeSignaturesChanged(userName, mapId, wowrmholeId); - } + await Clients.All.NotifyMapAccessRemoved(userName, mapId, accessId); } + } - public async Task SendWormholeLockChanged(int mapId, int wormholeId, bool locked) + public async Task SendMapAllAccessesRemoved(int mapId) + { + string userName = CurrentUser(); + if (!string.IsNullOrEmpty(userName)) { - string userName = CurrentUser(); - if (!string.IsNullOrEmpty(userName)) - { - await Clients.AllExcept(Context.ConnectionId).NotifyWormholeLockChanged(userName, mapId, wormholeId, locked); - } + await Clients.All.NotifyMapAllAccessesRemoved(userName, mapId); } + } + + public async Task SendUserOnMapConnected(int mapId) + { + string userName = CurrentUser(); + if (!string.IsNullOrEmpty(userName)) + { + await Clients.AllExcept(Context.ConnectionId).NotifyUserOnMapConnected(userName, mapId); + } + } - public async Task SendWormholeSystemStatusChanged(int mapId, int wormholeId, WHSystemStatus systemStatus) + public async Task SendUserOnMapDisconnected(int mapId) + { + string userName = CurrentUser(); + if (!string.IsNullOrEmpty(userName)) { - string userName = CurrentUser(); - if (!string.IsNullOrEmpty(userName)) - { - await Clients.AllExcept(Context.ConnectionId).NotifyWormholeSystemStatusChanged(userName, mapId, wormholeId, systemStatus); - } + await Clients.AllExcept(Context.ConnectionId).NotifyUserOnMapDisconnected(userName, mapId); } - } + + + } + diff --git a/src/WHMapper/Migrations/20230805074405_Init.cs b/src/WHMapper/Migrations/20230805074405_Init.cs index b1c7b622..20840fd2 100644 --- a/src/WHMapper/Migrations/20230805074405_Init.cs +++ b/src/WHMapper/Migrations/20230805074405_Init.cs @@ -1,5 +1,4 @@ -using System; -using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Migrations; using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; #nullable disable diff --git a/src/WHMapper/Migrations/20240229165501_Add_Link_Jump_Log.cs b/src/WHMapper/Migrations/20240229165501_Add_Link_Jump_Log.cs index b429df59..3b626d76 100644 --- a/src/WHMapper/Migrations/20240229165501_Add_Link_Jump_Log.cs +++ b/src/WHMapper/Migrations/20240229165501_Add_Link_Jump_Log.cs @@ -1,5 +1,4 @@ -using System; -using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Migrations; using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; #nullable disable diff --git a/src/WHMapper/Migrations/20240507153308_Update_Jump_Log_Properties_To_Nullable.Designer.cs b/src/WHMapper/Migrations/20240507153308_Update_Jump_Log_Properties_To_Nullable.Designer.cs index 76e51e51..f2bcb063 100644 --- a/src/WHMapper/Migrations/20240507153308_Update_Jump_Log_Properties_To_Nullable.Designer.cs +++ b/src/WHMapper/Migrations/20240507153308_Update_Jump_Log_Properties_To_Nullable.Designer.cs @@ -74,6 +74,7 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) b.ToTable("Admins", (string)null); }); + modelBuilder.Entity("WHMapper.Models.Db.WHJumpLog", b => { b.Property("Id") @@ -89,17 +90,20 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) .HasColumnType("timestamp with time zone"); b.Property("ShipItemId") - .HasColumnType("bigint"); + .HasColumnType("bigint") + .IsRequired(false); - b.Property("ShipMass") - .HasColumnType("real"); - + .HasColumnType("real") + .IsRequired(false); + b.Property("ShipTypeId") - .HasColumnType("integer"); + .HasColumnType("integer") + .IsRequired(false); // Set the column to be nullable b.Property("WHSystemLinkId") .HasColumnType("integer"); + b.HasKey("Id"); @@ -250,6 +254,7 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) b.ToTable("Systems", (string)null); }); + modelBuilder.Entity("WHMapper.Models.Db.WHSystemLink", b => { b.Property("Id") diff --git a/src/WHMapper/Migrations/20240507153308_Update_Jump_Log_Properties_To_Nullable.cs b/src/WHMapper/Migrations/20240507153308_Update_Jump_Log_Properties_To_Nullable.cs index 8d08f198..690cd03d 100644 --- a/src/WHMapper/Migrations/20240507153308_Update_Jump_Log_Properties_To_Nullable.cs +++ b/src/WHMapper/Migrations/20240507153308_Update_Jump_Log_Properties_To_Nullable.cs @@ -10,13 +10,60 @@ public partial class Update_Jump_Log_Properties_To_Nullable : Migration /// protected override void Up(MigrationBuilder migrationBuilder) { + migrationBuilder.AlterColumn( + name: "ShipTypeId", + table: "JumpLogs", + type: "INTEGER", + nullable: true, + oldClrType: typeof(int), + oldType: "INTEGER"); + migrationBuilder.AlterColumn( + name: "ShipItemId", + table: "JumpLogs", + type: "INTEGER", + nullable: true, + oldClrType: typeof(long), + oldType: "INTEGER"); + + migrationBuilder.AlterColumn( + name: "ShipMass", + table: "JumpLogs", + type: "REAL", + nullable: true, + oldClrType: typeof(float), + oldType: "REAL"); } /// protected override void Down(MigrationBuilder migrationBuilder) { + migrationBuilder.AlterColumn( + name: "ShipTypeId", + table: "JumpLogs", + type: "INTEGER", + nullable: false, + oldClrType: typeof(int), + oldType: "INTEGER", + oldNullable: true); + + migrationBuilder.AlterColumn( + name: "ShipItemId", + table: "JumpLogs", + type: "INTEGER", + nullable: false, + oldClrType: typeof(long), + oldType: "INTEGER", + oldNullable: true); + migrationBuilder.AlterColumn( + name: "ShipMass", + table: "JumpLogs", + type: "REAL", + nullable: false, + oldClrType: typeof(float), + oldType: "REAL", + oldNullable: true); } } } diff --git a/src/WHMapper/Migrations/20240828145305_Allow_Multi_Map.Designer.cs b/src/WHMapper/Migrations/20240828145305_Allow_Multi_Map.Designer.cs new file mode 100644 index 00000000..fecf0c74 --- /dev/null +++ b/src/WHMapper/Migrations/20240828145305_Allow_Multi_Map.Designer.cs @@ -0,0 +1,409 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; +using WHMapper.Data; + +#nullable disable + +namespace WHMapper.Migrations +{ + [DbContext(typeof(WHMapperContext))] + [Migration("20240828145305_Allow_Multi_Map")] + partial class Allow_Multi_Map + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "8.0.5") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("WHAccessWHMap", b => + { + b.Property("WHAccessesId") + .HasColumnType("integer"); + + b.Property("WHMapId") + .HasColumnType("integer"); + + b.HasKey("WHAccessesId", "WHMapId"); + + b.HasIndex("WHMapId"); + + b.ToTable("WHAccessWHMap"); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHAccess", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("EveEntity") + .HasColumnType("integer"); + + b.Property("EveEntityId") + .HasColumnType("integer"); + + b.Property("EveEntityName") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("EveEntityId", "EveEntity") + .IsUnique(); + + b.ToTable("Accesses", (string)null); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHAdmin", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("EveCharacterId") + .HasColumnType("integer"); + + b.Property("EveCharacterName") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("EveCharacterId") + .IsUnique(); + + b.ToTable("Admins", (string)null); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHJumpLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CharacterId") + .HasColumnType("integer"); + + b.Property("JumpDate") + .HasColumnType("timestamp with time zone"); + + b.Property("ShipItemId") + .HasColumnType("bigint"); + + b.Property("ShipMass") + .HasColumnType("real"); + + b.Property("ShipTypeId") + .HasColumnType("integer"); + + b.Property("WHSystemLinkId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("WHSystemLinkId"); + + b.HasIndex("CharacterId", "JumpDate") + .IsUnique(); + + b.ToTable("JumpLogs", (string)null); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHMap", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Maps", (string)null); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHNote", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Comment") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("SoloarSystemId") + .HasColumnType("integer"); + + b.Property("SystemStatus") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("SoloarSystemId") + .IsUnique(); + + b.ToTable("Notes", (string)null); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHSignature", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedBy") + .IsRequired() + .HasColumnType("text"); + + b.Property("Group") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(7) + .HasColumnType("character varying(7)"); + + b.Property("Type") + .HasColumnType("text"); + + b.Property("Updated") + .HasColumnType("timestamp with time zone"); + + b.Property("UpdatedBy") + .IsRequired() + .HasColumnType("text"); + + b.Property("WHId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("WHId", "Name") + .IsUnique(); + + b.ToTable("Signatures", (string)null); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHSystem", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Locked") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("NameExtension") + .HasColumnType("smallint"); + + b.Property("PosX") + .HasColumnType("double precision"); + + b.Property("PosY") + .HasColumnType("double precision"); + + b.Property("SecurityStatus") + .HasColumnType("real"); + + b.Property("SoloarSystemId") + .HasColumnType("integer"); + + b.Property("WHMapId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("SoloarSystemId") + .IsUnique(); + + b.HasIndex("WHMapId"); + + b.ToTable("Systems", (string)null); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHSystemLink", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("IdWHSystemFrom") + .HasColumnType("integer"); + + b.Property("IdWHSystemTo") + .HasColumnType("integer"); + + b.Property("IsEndOfLifeConnection") + .HasColumnType("boolean"); + + b.Property("MassStatus") + .HasColumnType("integer"); + + b.Property("Size") + .HasColumnType("integer"); + + b.Property("WHMapId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("IdWHSystemTo"); + + b.HasIndex("WHMapId"); + + b.HasIndex("IdWHSystemFrom", "IdWHSystemTo") + .IsUnique(); + + b.ToTable("SystemLinks", (string)null); + }); + + modelBuilder.Entity("WHMapper.WHRoute", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("EveEntityId") + .HasColumnType("integer"); + + b.Property("SolarSystemId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("SolarSystemId", "EveEntityId") + .IsUnique(); + + b.ToTable("Routes", (string)null); + }); + + modelBuilder.Entity("WHAccessWHMap", b => + { + b.HasOne("WHMapper.Models.Db.WHAccess", null) + .WithMany() + .HasForeignKey("WHAccessesId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("WHMapper.Models.Db.WHMap", null) + .WithMany() + .HasForeignKey("WHMapId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHJumpLog", b => + { + b.HasOne("WHMapper.Models.Db.WHSystemLink", null) + .WithMany("JumpHistory") + .HasForeignKey("WHSystemLinkId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHSignature", b => + { + b.HasOne("WHMapper.Models.Db.WHSystem", null) + .WithMany("WHSignatures") + .HasForeignKey("WHId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHSystem", b => + { + b.HasOne("WHMapper.Models.Db.WHMap", null) + .WithMany("WHSystems") + .HasForeignKey("WHMapId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHSystemLink", b => + { + b.HasOne("WHMapper.Models.Db.WHSystem", null) + .WithMany() + .HasForeignKey("IdWHSystemFrom") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("WHMapper.Models.Db.WHSystem", null) + .WithMany() + .HasForeignKey("IdWHSystemTo") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("WHMapper.Models.Db.WHMap", null) + .WithMany("WHSystemLinks") + .HasForeignKey("WHMapId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHMap", b => + { + b.Navigation("WHSystemLinks"); + + b.Navigation("WHSystems"); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHSystem", b => + { + b.Navigation("WHSignatures"); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHSystemLink", b => + { + b.Navigation("JumpHistory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/WHMapper/Migrations/20240828145305_Allow_Multi_Map.cs b/src/WHMapper/Migrations/20240828145305_Allow_Multi_Map.cs new file mode 100644 index 00000000..f620b31d --- /dev/null +++ b/src/WHMapper/Migrations/20240828145305_Allow_Multi_Map.cs @@ -0,0 +1,50 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace WHMapper.Migrations +{ + /// + public partial class Allow_Multi_Map : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "WHAccessWHMap", + columns: table => new + { + WHAccessesId = table.Column(type: "integer", nullable: false), + WHMapId = table.Column(type: "integer", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_WHAccessWHMap", x => new { x.WHAccessesId, x.WHMapId }); + table.ForeignKey( + name: "FK_WHAccessWHMap_Accesses_WHAccessesId", + column: x => x.WHAccessesId, + principalTable: "Accesses", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_WHAccessWHMap_Maps_WHMapId", + column: x => x.WHMapId, + principalTable: "Maps", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_WHAccessWHMap_WHMapId", + table: "WHAccessWHMap", + column: "WHMapId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "WHAccessWHMap"); + } + } +} diff --git a/src/WHMapper/Migrations/20240831174011_Update_UniqueKey_For_Multi_Map.Designer.cs b/src/WHMapper/Migrations/20240831174011_Update_UniqueKey_For_Multi_Map.Designer.cs new file mode 100644 index 00000000..6a5cc337 --- /dev/null +++ b/src/WHMapper/Migrations/20240831174011_Update_UniqueKey_For_Multi_Map.Designer.cs @@ -0,0 +1,407 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; +using WHMapper.Data; + +#nullable disable + +namespace WHMapper.Migrations +{ + [DbContext(typeof(WHMapperContext))] + [Migration("20240831174011_Update_UniqueKey_For_Multi_Map")] + partial class Update_UniqueKey_For_Multi_Map + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "8.0.5") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("WHAccessWHMap", b => + { + b.Property("WHAccessesId") + .HasColumnType("integer"); + + b.Property("WHMapId") + .HasColumnType("integer"); + + b.HasKey("WHAccessesId", "WHMapId"); + + b.HasIndex("WHMapId"); + + b.ToTable("WHAccessWHMap"); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHAccess", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("EveEntity") + .HasColumnType("integer"); + + b.Property("EveEntityId") + .HasColumnType("integer"); + + b.Property("EveEntityName") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("EveEntityId", "EveEntity") + .IsUnique(); + + b.ToTable("Accesses", (string)null); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHAdmin", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("EveCharacterId") + .HasColumnType("integer"); + + b.Property("EveCharacterName") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("EveCharacterId") + .IsUnique(); + + b.ToTable("Admins", (string)null); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHJumpLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CharacterId") + .HasColumnType("integer"); + + b.Property("JumpDate") + .HasColumnType("timestamp with time zone"); + + b.Property("ShipItemId") + .HasColumnType("bigint"); + + b.Property("ShipMass") + .HasColumnType("real"); + + b.Property("ShipTypeId") + .HasColumnType("integer"); + + b.Property("WHSystemLinkId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("WHSystemLinkId"); + + b.HasIndex("CharacterId", "JumpDate") + .IsUnique(); + + b.ToTable("JumpLogs", (string)null); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHMap", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Maps", (string)null); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHNote", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Comment") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("SoloarSystemId") + .HasColumnType("integer"); + + b.Property("SystemStatus") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("SoloarSystemId") + .IsUnique(); + + b.ToTable("Notes", (string)null); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHSignature", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedBy") + .IsRequired() + .HasColumnType("text"); + + b.Property("Group") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(7) + .HasColumnType("character varying(7)"); + + b.Property("Type") + .HasColumnType("text"); + + b.Property("Updated") + .HasColumnType("timestamp with time zone"); + + b.Property("UpdatedBy") + .IsRequired() + .HasColumnType("text"); + + b.Property("WHId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("WHId", "Name") + .IsUnique(); + + b.ToTable("Signatures", (string)null); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHSystem", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Locked") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("NameExtension") + .HasColumnType("smallint"); + + b.Property("PosX") + .HasColumnType("double precision"); + + b.Property("PosY") + .HasColumnType("double precision"); + + b.Property("SecurityStatus") + .HasColumnType("real"); + + b.Property("SoloarSystemId") + .HasColumnType("integer"); + + b.Property("WHMapId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("WHMapId", "Name") + .IsUnique(); + + b.HasIndex("WHMapId", "SoloarSystemId") + .IsUnique(); + + b.ToTable("Systems", (string)null); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHSystemLink", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("IdWHSystemFrom") + .HasColumnType("integer"); + + b.Property("IdWHSystemTo") + .HasColumnType("integer"); + + b.Property("IsEndOfLifeConnection") + .HasColumnType("boolean"); + + b.Property("MassStatus") + .HasColumnType("integer"); + + b.Property("Size") + .HasColumnType("integer"); + + b.Property("WHMapId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("IdWHSystemFrom"); + + b.HasIndex("IdWHSystemTo"); + + b.HasIndex("WHMapId", "IdWHSystemFrom", "IdWHSystemTo") + .IsUnique(); + + b.ToTable("SystemLinks", (string)null); + }); + + modelBuilder.Entity("WHMapper.WHRoute", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("EveEntityId") + .HasColumnType("integer"); + + b.Property("SolarSystemId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("SolarSystemId", "EveEntityId") + .IsUnique(); + + b.ToTable("Routes", (string)null); + }); + + modelBuilder.Entity("WHAccessWHMap", b => + { + b.HasOne("WHMapper.Models.Db.WHAccess", null) + .WithMany() + .HasForeignKey("WHAccessesId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("WHMapper.Models.Db.WHMap", null) + .WithMany() + .HasForeignKey("WHMapId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHJumpLog", b => + { + b.HasOne("WHMapper.Models.Db.WHSystemLink", null) + .WithMany("JumpHistory") + .HasForeignKey("WHSystemLinkId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHSignature", b => + { + b.HasOne("WHMapper.Models.Db.WHSystem", null) + .WithMany("WHSignatures") + .HasForeignKey("WHId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHSystem", b => + { + b.HasOne("WHMapper.Models.Db.WHMap", null) + .WithMany("WHSystems") + .HasForeignKey("WHMapId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHSystemLink", b => + { + b.HasOne("WHMapper.Models.Db.WHSystem", null) + .WithMany() + .HasForeignKey("IdWHSystemFrom") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("WHMapper.Models.Db.WHSystem", null) + .WithMany() + .HasForeignKey("IdWHSystemTo") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("WHMapper.Models.Db.WHMap", null) + .WithMany("WHSystemLinks") + .HasForeignKey("WHMapId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHMap", b => + { + b.Navigation("WHSystemLinks"); + + b.Navigation("WHSystems"); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHSystem", b => + { + b.Navigation("WHSignatures"); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHSystemLink", b => + { + b.Navigation("JumpHistory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/WHMapper/Migrations/20240831174011_Update_UniqueKey_For_Multi_Map.cs b/src/WHMapper/Migrations/20240831174011_Update_UniqueKey_For_Multi_Map.cs new file mode 100644 index 00000000..f9b1bb9d --- /dev/null +++ b/src/WHMapper/Migrations/20240831174011_Update_UniqueKey_For_Multi_Map.cs @@ -0,0 +1,105 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace WHMapper.Migrations +{ + /// + public partial class Update_UniqueKey_For_Multi_Map : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "IX_Systems_Name", + table: "Systems"); + + migrationBuilder.DropIndex( + name: "IX_Systems_SoloarSystemId", + table: "Systems"); + + migrationBuilder.DropIndex( + name: "IX_Systems_WHMapId", + table: "Systems"); + + migrationBuilder.DropIndex( + name: "IX_SystemLinks_IdWHSystemFrom_IdWHSystemTo", + table: "SystemLinks"); + + migrationBuilder.DropIndex( + name: "IX_SystemLinks_WHMapId", + table: "SystemLinks"); + + migrationBuilder.CreateIndex( + name: "IX_Systems_WHMapId_Name", + table: "Systems", + columns: new[] { "WHMapId", "Name" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_Systems_WHMapId_SoloarSystemId", + table: "Systems", + columns: new[] { "WHMapId", "SoloarSystemId" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_SystemLinks_IdWHSystemFrom", + table: "SystemLinks", + column: "IdWHSystemFrom"); + + migrationBuilder.CreateIndex( + name: "IX_SystemLinks_WHMapId_IdWHSystemFrom_IdWHSystemTo", + table: "SystemLinks", + columns: new[] { "WHMapId", "IdWHSystemFrom", "IdWHSystemTo" }, + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "IX_Systems_WHMapId_Name", + table: "Systems"); + + migrationBuilder.DropIndex( + name: "IX_Systems_WHMapId_SoloarSystemId", + table: "Systems"); + + migrationBuilder.DropIndex( + name: "IX_SystemLinks_IdWHSystemFrom", + table: "SystemLinks"); + + migrationBuilder.DropIndex( + name: "IX_SystemLinks_WHMapId_IdWHSystemFrom_IdWHSystemTo", + table: "SystemLinks"); + + migrationBuilder.CreateIndex( + name: "IX_Systems_Name", + table: "Systems", + column: "Name", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_Systems_SoloarSystemId", + table: "Systems", + column: "SoloarSystemId", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_Systems_WHMapId", + table: "Systems", + column: "WHMapId"); + + migrationBuilder.CreateIndex( + name: "IX_SystemLinks_IdWHSystemFrom_IdWHSystemTo", + table: "SystemLinks", + columns: new[] { "IdWHSystemFrom", "IdWHSystemTo" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_SystemLinks_WHMapId", + table: "SystemLinks", + column: "WHMapId"); + } + } +} diff --git a/src/WHMapper/Migrations/20240909201955_Update_Notes_To_Be_Unique_For_Multi_Map.Designer.cs b/src/WHMapper/Migrations/20240909201955_Update_Notes_To_Be_Unique_For_Multi_Map.Designer.cs new file mode 100644 index 00000000..88894e8b --- /dev/null +++ b/src/WHMapper/Migrations/20240909201955_Update_Notes_To_Be_Unique_For_Multi_Map.Designer.cs @@ -0,0 +1,419 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; +using WHMapper.Data; + +#nullable disable + +namespace WHMapper.Migrations +{ + [DbContext(typeof(WHMapperContext))] + [Migration("20240909201955_Update_Notes_To_Be_Unique_For_Multi_Map")] + partial class Update_Notes_To_Be_Unique_For_Multi_Map + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "8.0.8") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("WHAccessWHMap", b => + { + b.Property("WHAccessesId") + .HasColumnType("integer"); + + b.Property("WHMapId") + .HasColumnType("integer"); + + b.HasKey("WHAccessesId", "WHMapId"); + + b.HasIndex("WHMapId"); + + b.ToTable("WHAccessWHMap"); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHAccess", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("EveEntity") + .HasColumnType("integer"); + + b.Property("EveEntityId") + .HasColumnType("integer"); + + b.Property("EveEntityName") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("EveEntityId", "EveEntity") + .IsUnique(); + + b.ToTable("Accesses", (string)null); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHAdmin", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("EveCharacterId") + .HasColumnType("integer"); + + b.Property("EveCharacterName") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("EveCharacterId") + .IsUnique(); + + b.ToTable("Admins", (string)null); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHJumpLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CharacterId") + .HasColumnType("integer"); + + b.Property("JumpDate") + .HasColumnType("timestamp with time zone"); + + b.Property("ShipItemId") + .HasColumnType("bigint"); + + b.Property("ShipMass") + .HasColumnType("real"); + + b.Property("ShipTypeId") + .HasColumnType("integer"); + + b.Property("WHSystemLinkId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("WHSystemLinkId"); + + b.HasIndex("CharacterId", "JumpDate") + .IsUnique(); + + b.ToTable("JumpLogs", (string)null); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHMap", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Maps", (string)null); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHNote", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Comment") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("MapId") + .HasColumnType("integer"); + + b.Property("SoloarSystemId") + .HasColumnType("integer"); + + b.Property("SystemStatus") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("MapId", "SoloarSystemId") + .IsUnique(); + + b.ToTable("Notes", (string)null); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHSignature", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedBy") + .IsRequired() + .HasColumnType("text"); + + b.Property("Group") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(7) + .HasColumnType("character varying(7)"); + + b.Property("Type") + .HasColumnType("text"); + + b.Property("Updated") + .HasColumnType("timestamp with time zone"); + + b.Property("UpdatedBy") + .IsRequired() + .HasColumnType("text"); + + b.Property("WHId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("WHId", "Name") + .IsUnique(); + + b.ToTable("Signatures", (string)null); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHSystem", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Locked") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("NameExtension") + .HasColumnType("smallint"); + + b.Property("PosX") + .HasColumnType("double precision"); + + b.Property("PosY") + .HasColumnType("double precision"); + + b.Property("SecurityStatus") + .HasColumnType("real"); + + b.Property("SoloarSystemId") + .HasColumnType("integer"); + + b.Property("WHMapId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("WHMapId", "Name") + .IsUnique(); + + b.HasIndex("WHMapId", "SoloarSystemId") + .IsUnique(); + + b.ToTable("Systems", (string)null); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHSystemLink", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("IdWHSystemFrom") + .HasColumnType("integer"); + + b.Property("IdWHSystemTo") + .HasColumnType("integer"); + + b.Property("IsEndOfLifeConnection") + .HasColumnType("boolean"); + + b.Property("MassStatus") + .HasColumnType("integer"); + + b.Property("Size") + .HasColumnType("integer"); + + b.Property("WHMapId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("IdWHSystemFrom"); + + b.HasIndex("IdWHSystemTo"); + + b.HasIndex("WHMapId", "IdWHSystemFrom", "IdWHSystemTo") + .IsUnique(); + + b.ToTable("SystemLinks", (string)null); + }); + + modelBuilder.Entity("WHMapper.WHRoute", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("EveEntityId") + .HasColumnType("integer"); + + b.Property("SolarSystemId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("SolarSystemId", "EveEntityId") + .IsUnique(); + + b.ToTable("Routes", (string)null); + }); + + modelBuilder.Entity("WHAccessWHMap", b => + { + b.HasOne("WHMapper.Models.Db.WHAccess", null) + .WithMany() + .HasForeignKey("WHAccessesId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("WHMapper.Models.Db.WHMap", null) + .WithMany() + .HasForeignKey("WHMapId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHJumpLog", b => + { + b.HasOne("WHMapper.Models.Db.WHSystemLink", null) + .WithMany("JumpHistory") + .HasForeignKey("WHSystemLinkId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHNote", b => + { + b.HasOne("WHMapper.Models.Db.WHMap", null) + .WithMany() + .HasForeignKey("MapId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHSignature", b => + { + b.HasOne("WHMapper.Models.Db.WHSystem", null) + .WithMany("WHSignatures") + .HasForeignKey("WHId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHSystem", b => + { + b.HasOne("WHMapper.Models.Db.WHMap", null) + .WithMany("WHSystems") + .HasForeignKey("WHMapId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHSystemLink", b => + { + b.HasOne("WHMapper.Models.Db.WHSystem", null) + .WithMany() + .HasForeignKey("IdWHSystemFrom") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("WHMapper.Models.Db.WHSystem", null) + .WithMany() + .HasForeignKey("IdWHSystemTo") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("WHMapper.Models.Db.WHMap", null) + .WithMany("WHSystemLinks") + .HasForeignKey("WHMapId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHMap", b => + { + b.Navigation("WHSystemLinks"); + + b.Navigation("WHSystems"); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHSystem", b => + { + b.Navigation("WHSignatures"); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHSystemLink", b => + { + b.Navigation("JumpHistory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/WHMapper/Migrations/20240909201955_Update_Notes_To_Be_Unique_For_Multi_Map.cs b/src/WHMapper/Migrations/20240909201955_Update_Notes_To_Be_Unique_For_Multi_Map.cs new file mode 100644 index 00000000..c806a225 --- /dev/null +++ b/src/WHMapper/Migrations/20240909201955_Update_Notes_To_Be_Unique_For_Multi_Map.cs @@ -0,0 +1,61 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace WHMapper.Migrations +{ + /// + public partial class Update_Notes_To_Be_Unique_For_Multi_Map : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "IX_Notes_SoloarSystemId", + table: "Notes"); + + migrationBuilder.AddColumn( + name: "MapId", + table: "Notes", + type: "integer", + nullable: false, + defaultValue: 1); + + migrationBuilder.CreateIndex( + name: "IX_Notes_MapId_SoloarSystemId", + table: "Notes", + columns: new[] { "MapId", "SoloarSystemId" }, + unique: true); + + migrationBuilder.AddForeignKey( + name: "FK_Notes_Maps_MapId", + table: "Notes", + column: "MapId", + principalTable: "Maps", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropForeignKey( + name: "FK_Notes_Maps_MapId", + table: "Notes"); + + migrationBuilder.DropIndex( + name: "IX_Notes_MapId_SoloarSystemId", + table: "Notes"); + + migrationBuilder.DropColumn( + name: "MapId", + table: "Notes"); + + migrationBuilder.CreateIndex( + name: "IX_Notes_SoloarSystemId", + table: "Notes", + column: "SoloarSystemId", + unique: true); + } + } +} diff --git a/src/WHMapper/Migrations/20240912202232_Update_Route_To_Be_Unique_For_Multi_Map.Designer.cs b/src/WHMapper/Migrations/20240912202232_Update_Route_To_Be_Unique_For_Multi_Map.Designer.cs new file mode 100644 index 00000000..cfbfb000 --- /dev/null +++ b/src/WHMapper/Migrations/20240912202232_Update_Route_To_Be_Unique_For_Multi_Map.Designer.cs @@ -0,0 +1,431 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; +using WHMapper.Data; + +#nullable disable + +namespace WHMapper.Migrations +{ + [DbContext(typeof(WHMapperContext))] + [Migration("20240912202232_Update_Route_To_Be_Unique_For_Multi_Map")] + partial class Update_Route_To_Be_Unique_For_Multi_Map + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "8.0.8") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("WHAccessWHMap", b => + { + b.Property("WHAccessesId") + .HasColumnType("integer"); + + b.Property("WHMapId") + .HasColumnType("integer"); + + b.HasKey("WHAccessesId", "WHMapId"); + + b.HasIndex("WHMapId"); + + b.ToTable("WHAccessWHMap"); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHAccess", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("EveEntity") + .HasColumnType("integer"); + + b.Property("EveEntityId") + .HasColumnType("integer"); + + b.Property("EveEntityName") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("EveEntityId", "EveEntity") + .IsUnique(); + + b.ToTable("Accesses", (string)null); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHAdmin", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("EveCharacterId") + .HasColumnType("integer"); + + b.Property("EveCharacterName") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("EveCharacterId") + .IsUnique(); + + b.ToTable("Admins", (string)null); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHJumpLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CharacterId") + .HasColumnType("integer"); + + b.Property("JumpDate") + .HasColumnType("timestamp with time zone"); + + b.Property("ShipItemId") + .HasColumnType("bigint"); + + b.Property("ShipMass") + .HasColumnType("real"); + + b.Property("ShipTypeId") + .HasColumnType("integer"); + + b.Property("WHSystemLinkId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("WHSystemLinkId"); + + b.HasIndex("CharacterId", "JumpDate") + .IsUnique(); + + b.ToTable("JumpLogs", (string)null); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHMap", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Maps", (string)null); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHNote", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Comment") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("MapId") + .HasColumnType("integer"); + + b.Property("SoloarSystemId") + .HasColumnType("integer"); + + b.Property("SystemStatus") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("MapId", "SoloarSystemId") + .IsUnique(); + + b.ToTable("Notes", (string)null); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHSignature", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedBy") + .IsRequired() + .HasColumnType("text"); + + b.Property("Group") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(7) + .HasColumnType("character varying(7)"); + + b.Property("Type") + .HasColumnType("text"); + + b.Property("Updated") + .HasColumnType("timestamp with time zone"); + + b.Property("UpdatedBy") + .IsRequired() + .HasColumnType("text"); + + b.Property("WHId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("WHId", "Name") + .IsUnique(); + + b.ToTable("Signatures", (string)null); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHSystem", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Locked") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("NameExtension") + .HasColumnType("smallint"); + + b.Property("PosX") + .HasColumnType("double precision"); + + b.Property("PosY") + .HasColumnType("double precision"); + + b.Property("SecurityStatus") + .HasColumnType("real"); + + b.Property("SoloarSystemId") + .HasColumnType("integer"); + + b.Property("WHMapId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("WHMapId", "Name") + .IsUnique(); + + b.HasIndex("WHMapId", "SoloarSystemId") + .IsUnique(); + + b.ToTable("Systems", (string)null); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHSystemLink", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("IdWHSystemFrom") + .HasColumnType("integer"); + + b.Property("IdWHSystemTo") + .HasColumnType("integer"); + + b.Property("IsEndOfLifeConnection") + .HasColumnType("boolean"); + + b.Property("MassStatus") + .HasColumnType("integer"); + + b.Property("Size") + .HasColumnType("integer"); + + b.Property("WHMapId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("IdWHSystemFrom"); + + b.HasIndex("IdWHSystemTo"); + + b.HasIndex("WHMapId", "IdWHSystemFrom", "IdWHSystemTo") + .IsUnique(); + + b.ToTable("SystemLinks", (string)null); + }); + + modelBuilder.Entity("WHMapper.WHRoute", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("EveEntityId") + .HasColumnType("integer"); + + b.Property("MapId") + .HasColumnType("integer"); + + b.Property("SolarSystemId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("MapId", "SolarSystemId", "EveEntityId") + .IsUnique(); + + b.ToTable("Routes", (string)null); + }); + + modelBuilder.Entity("WHAccessWHMap", b => + { + b.HasOne("WHMapper.Models.Db.WHAccess", null) + .WithMany() + .HasForeignKey("WHAccessesId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("WHMapper.Models.Db.WHMap", null) + .WithMany() + .HasForeignKey("WHMapId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHJumpLog", b => + { + b.HasOne("WHMapper.Models.Db.WHSystemLink", null) + .WithMany("JumpHistory") + .HasForeignKey("WHSystemLinkId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHNote", b => + { + b.HasOne("WHMapper.Models.Db.WHMap", null) + .WithMany() + .HasForeignKey("MapId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHSignature", b => + { + b.HasOne("WHMapper.Models.Db.WHSystem", null) + .WithMany("WHSignatures") + .HasForeignKey("WHId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHSystem", b => + { + b.HasOne("WHMapper.Models.Db.WHMap", null) + .WithMany("WHSystems") + .HasForeignKey("WHMapId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHSystemLink", b => + { + b.HasOne("WHMapper.Models.Db.WHSystem", null) + .WithMany() + .HasForeignKey("IdWHSystemFrom") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("WHMapper.Models.Db.WHSystem", null) + .WithMany() + .HasForeignKey("IdWHSystemTo") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("WHMapper.Models.Db.WHMap", null) + .WithMany("WHSystemLinks") + .HasForeignKey("WHMapId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("WHMapper.WHRoute", b => + { + b.HasOne("WHMapper.Models.Db.WHMap", null) + .WithMany() + .HasForeignKey("MapId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHMap", b => + { + b.Navigation("WHSystemLinks"); + + b.Navigation("WHSystems"); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHSystem", b => + { + b.Navigation("WHSignatures"); + }); + + modelBuilder.Entity("WHMapper.Models.Db.WHSystemLink", b => + { + b.Navigation("JumpHistory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/WHMapper/Migrations/20240912202232_Update_Route_To_Be_Unique_For_Multi_Map.cs b/src/WHMapper/Migrations/20240912202232_Update_Route_To_Be_Unique_For_Multi_Map.cs new file mode 100644 index 00000000..a660df53 --- /dev/null +++ b/src/WHMapper/Migrations/20240912202232_Update_Route_To_Be_Unique_For_Multi_Map.cs @@ -0,0 +1,61 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace WHMapper.Migrations +{ + /// + public partial class Update_Route_To_Be_Unique_For_Multi_Map : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "IX_Routes_SolarSystemId_EveEntityId", + table: "Routes"); + + migrationBuilder.AddColumn( + name: "MapId", + table: "Routes", + type: "integer", + nullable: false, + defaultValue: 1); + + migrationBuilder.CreateIndex( + name: "IX_Routes_MapId_SolarSystemId_EveEntityId", + table: "Routes", + columns: new[] { "MapId", "SolarSystemId", "EveEntityId" }, + unique: true); + + migrationBuilder.AddForeignKey( + name: "FK_Routes_Maps_MapId", + table: "Routes", + column: "MapId", + principalTable: "Maps", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropForeignKey( + name: "FK_Routes_Maps_MapId", + table: "Routes"); + + migrationBuilder.DropIndex( + name: "IX_Routes_MapId_SolarSystemId_EveEntityId", + table: "Routes"); + + migrationBuilder.DropColumn( + name: "MapId", + table: "Routes"); + + migrationBuilder.CreateIndex( + name: "IX_Routes_SolarSystemId_EveEntityId", + table: "Routes", + columns: new[] { "SolarSystemId", "EveEntityId" }, + unique: true); + } + } +} diff --git a/src/WHMapper/Migrations/WHMapperContextModelSnapshot.cs b/src/WHMapper/Migrations/WHMapperContextModelSnapshot.cs index 66420677..47fd1f85 100644 --- a/src/WHMapper/Migrations/WHMapperContextModelSnapshot.cs +++ b/src/WHMapper/Migrations/WHMapperContextModelSnapshot.cs @@ -17,11 +17,26 @@ protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder - .HasAnnotation("ProductVersion", "8.0.3") + .HasAnnotation("ProductVersion", "8.0.8") .HasAnnotation("Relational:MaxIdentifierLength", 63); NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + modelBuilder.Entity("WHAccessWHMap", b => + { + b.Property("WHAccessesId") + .HasColumnType("integer"); + + b.Property("WHMapId") + .HasColumnType("integer"); + + b.HasKey("WHAccessesId", "WHMapId"); + + b.HasIndex("WHMapId"); + + b.ToTable("WHAccessWHMap"); + }); + modelBuilder.Entity("WHMapper.Models.Db.WHAccess", b => { b.Property("Id") @@ -141,6 +156,9 @@ protected override void BuildModel(ModelBuilder modelBuilder) .HasMaxLength(255) .HasColumnType("character varying(255)"); + b.Property("MapId") + .HasColumnType("integer"); + b.Property("SoloarSystemId") .HasColumnType("integer"); @@ -149,7 +167,7 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.HasKey("Id"); - b.HasIndex("SoloarSystemId") + b.HasIndex("MapId", "SoloarSystemId") .IsUnique(); b.ToTable("Notes", (string)null); @@ -235,14 +253,12 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.HasKey("Id"); - b.HasIndex("Name") + b.HasIndex("WHMapId", "Name") .IsUnique(); - b.HasIndex("SoloarSystemId") + b.HasIndex("WHMapId", "SoloarSystemId") .IsUnique(); - b.HasIndex("WHMapId"); - b.ToTable("Systems", (string)null); }); @@ -274,11 +290,11 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.HasKey("Id"); - b.HasIndex("IdWHSystemTo"); + b.HasIndex("IdWHSystemFrom"); - b.HasIndex("WHMapId"); + b.HasIndex("IdWHSystemTo"); - b.HasIndex("IdWHSystemFrom", "IdWHSystemTo") + b.HasIndex("WHMapId", "IdWHSystemFrom", "IdWHSystemTo") .IsUnique(); b.ToTable("SystemLinks", (string)null); @@ -295,17 +311,35 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Property("EveEntityId") .HasColumnType("integer"); + b.Property("MapId") + .HasColumnType("integer"); + b.Property("SolarSystemId") .HasColumnType("integer"); b.HasKey("Id"); - b.HasIndex("SolarSystemId", "EveEntityId") + b.HasIndex("MapId", "SolarSystemId", "EveEntityId") .IsUnique(); b.ToTable("Routes", (string)null); }); + modelBuilder.Entity("WHAccessWHMap", b => + { + b.HasOne("WHMapper.Models.Db.WHAccess", null) + .WithMany() + .HasForeignKey("WHAccessesId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("WHMapper.Models.Db.WHMap", null) + .WithMany() + .HasForeignKey("WHMapId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + modelBuilder.Entity("WHMapper.Models.Db.WHJumpLog", b => { b.HasOne("WHMapper.Models.Db.WHSystemLink", null) @@ -315,6 +349,15 @@ protected override void BuildModel(ModelBuilder modelBuilder) .IsRequired(); }); + modelBuilder.Entity("WHMapper.Models.Db.WHNote", b => + { + b.HasOne("WHMapper.Models.Db.WHMap", null) + .WithMany() + .HasForeignKey("MapId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + modelBuilder.Entity("WHMapper.Models.Db.WHSignature", b => { b.HasOne("WHMapper.Models.Db.WHSystem", null) @@ -354,6 +397,15 @@ protected override void BuildModel(ModelBuilder modelBuilder) .IsRequired(); }); + modelBuilder.Entity("WHMapper.WHRoute", b => + { + b.HasOne("WHMapper.Models.Db.WHMap", null) + .WithMany() + .HasForeignKey("MapId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + modelBuilder.Entity("WHMapper.Models.Db.WHMap", b => { b.Navigation("WHSystemLinks"); diff --git a/src/WHMapper/Models/Custom/Node/EveSystemLinkModel.cs b/src/WHMapper/Models/Custom/Node/EveSystemLinkModel.cs index a9d14350..3b027f10 100644 --- a/src/WHMapper/Models/Custom/Node/EveSystemLinkModel.cs +++ b/src/WHMapper/Models/Custom/Node/EveSystemLinkModel.cs @@ -1,12 +1,6 @@ -using System; -using System.ComponentModel.DataAnnotations; -using Blazor.Diagrams.Core.Models; -using Blazor.Diagrams.Core.Extensions; +using Blazor.Diagrams.Core.Models; using WHMapper.Models.Db; using WHMapper.Models.Db.Enums; -using static MudBlazor.CategoryTypes; -using WHMapper.Services.WHColor; -using Blazor.Diagrams.Core.Geometry; namespace WHMapper.Models.Custom.Node { diff --git a/src/WHMapper/Models/Custom/Node/EveSystemNodeModel.cs b/src/WHMapper/Models/Custom/Node/EveSystemNodeModel.cs index 1e6f0c1e..78bfdb3f 100644 --- a/src/WHMapper/Models/Custom/Node/EveSystemNodeModel.cs +++ b/src/WHMapper/Models/Custom/Node/EveSystemNodeModel.cs @@ -1,13 +1,7 @@ -using System; -using System.Collections.Concurrent; -using System.ComponentModel; -using System.Xml.Linq; -using Blazor.Diagrams.Core.Geometry; +using System.Collections.Concurrent; using Blazor.Diagrams.Core.Models; -using Blazor.Diagrams.Core.Models.Base; using WHMapper.Models.DTO.EveMapper.Enums; using WHMapper.Models.Db; -using WHMapper.Models.DTO.EveAPI.Universe; using WHMapper.Models.DTO.EveMapper; using WHMapper.Models.Db.Enums; diff --git a/src/WHMapper/Models/DTO/EveAPI/Alliance/Alliance.cs b/src/WHMapper/Models/DTO/EveAPI/Alliance/Alliance.cs index 48951eee..022398a4 100644 --- a/src/WHMapper/Models/DTO/EveAPI/Alliance/Alliance.cs +++ b/src/WHMapper/Models/DTO/EveAPI/Alliance/Alliance.cs @@ -1,10 +1,8 @@ -using System; -using System.Text.Json.Serialization; -using WHMapper.Models.DTO.EveAPI.Universe; +using System.Text.Json.Serialization; namespace WHMapper.Models.DTO.EveAPI.Alliance { - public class Alliance + public class Alliance { [JsonPropertyName("creator_corporation_id")] public int CreatorCorporationId { get; set; } diff --git a/src/WHMapper/Models/DTO/EveAPI/Character/Character.cs b/src/WHMapper/Models/DTO/EveAPI/Character/Character.cs index 8cac4bdb..f4c3932c 100644 --- a/src/WHMapper/Models/DTO/EveAPI/Character/Character.cs +++ b/src/WHMapper/Models/DTO/EveAPI/Character/Character.cs @@ -1,9 +1,8 @@ -using System; -using System.Text.Json.Serialization; +using System.Text.Json.Serialization; namespace WHMapper.Models.DTO.EveAPI.Character { - public class Character + public class Character { [JsonPropertyName("alliance_id")] public int AllianceId { get; set; } diff --git a/src/WHMapper/Models/DTO/EveAPI/Corporation/Corporation.cs b/src/WHMapper/Models/DTO/EveAPI/Corporation/Corporation.cs index 8cdc6aff..1e995eff 100644 --- a/src/WHMapper/Models/DTO/EveAPI/Corporation/Corporation.cs +++ b/src/WHMapper/Models/DTO/EveAPI/Corporation/Corporation.cs @@ -1,9 +1,8 @@ -using System; -using System.Text.Json.Serialization; +using System.Text.Json.Serialization; namespace WHMapper.Models.DTO.EveAPI.Corporation { - public class Corporation + public class Corporation { [JsonPropertyName("alliance_id")] public int AllianceId { get; set; } diff --git a/src/WHMapper/Models/DTO/EveAPI/Dogma/Attribute.cs b/src/WHMapper/Models/DTO/EveAPI/Dogma/Attribute.cs index dc7475f7..2591a956 100644 --- a/src/WHMapper/Models/DTO/EveAPI/Dogma/Attribute.cs +++ b/src/WHMapper/Models/DTO/EveAPI/Dogma/Attribute.cs @@ -1,10 +1,8 @@ -using System; -using System.Text.Json.Serialization; -using static MudBlazor.FilterOperator; +using System.Text.Json.Serialization; namespace WHMapper.Models.DTO.EveAPI.Dogma { - public class Attribute + public class Attribute { [JsonPropertyName("attribute_id")] public int AttributeId { get; set; } diff --git a/src/WHMapper/Models/DTO/EveAPI/Dogma/Effect.cs b/src/WHMapper/Models/DTO/EveAPI/Dogma/Effect.cs index d3adcd81..25232b45 100644 --- a/src/WHMapper/Models/DTO/EveAPI/Dogma/Effect.cs +++ b/src/WHMapper/Models/DTO/EveAPI/Dogma/Effect.cs @@ -1,10 +1,8 @@ -using System; -using System.Text.Json.Serialization; -using static MudBlazor.FilterOperator; +using System.Text.Json.Serialization; namespace WHMapper.Models.DTO.EveAPI.Dogma { - public class Effect + public class Effect { [JsonPropertyName("description")] public string Description { get; set; } = string.Empty; diff --git a/src/WHMapper/Models/DTO/EveAPI/SSO/EveToken.cs b/src/WHMapper/Models/DTO/EveAPI/SSO/EveToken.cs index 0bd61121..8f9f4fde 100644 --- a/src/WHMapper/Models/DTO/EveAPI/SSO/EveToken.cs +++ b/src/WHMapper/Models/DTO/EveAPI/SSO/EveToken.cs @@ -1,5 +1,4 @@ -using System; -using System.Text.Json.Serialization; +using System.Text.Json.Serialization; namespace WHMapper.Models.DTO.EveAPI.SSO { diff --git a/src/WHMapper/Models/DTO/EveAPI/Search/SearchAllianceResults.cs b/src/WHMapper/Models/DTO/EveAPI/Search/SearchAllianceResults.cs index 053e090b..e4e64d42 100644 --- a/src/WHMapper/Models/DTO/EveAPI/Search/SearchAllianceResults.cs +++ b/src/WHMapper/Models/DTO/EveAPI/Search/SearchAllianceResults.cs @@ -1,10 +1,8 @@ -using System; -using System.Text.Json.Serialization; -using WHMapper.Models.DTO.EveAPI.Universe; +using System.Text.Json.Serialization; namespace WHMapper.Models.DTO.EveAPI.Search { - public class SearchAllianceResults + public class SearchAllianceResults { [JsonPropertyName("alliance")] public int[]? Alliances { get; set; } = null!; diff --git a/src/WHMapper/Models/DTO/EveAPI/Search/SearchCharacterResults.cs b/src/WHMapper/Models/DTO/EveAPI/Search/SearchCharacterResults.cs index 7e8a43ac..d2477966 100644 --- a/src/WHMapper/Models/DTO/EveAPI/Search/SearchCharacterResults.cs +++ b/src/WHMapper/Models/DTO/EveAPI/Search/SearchCharacterResults.cs @@ -1,10 +1,8 @@ -using System; -using System.Text.Json.Serialization; -using WHMapper.Models.DTO.EveAPI.Universe; +using System.Text.Json.Serialization; namespace WHMapper.Models.DTO.EveAPI.Search { - public class SearchCharacterResults + public class SearchCharacterResults { [JsonPropertyName("character")] public int[]? Characters { get; set; } diff --git a/src/WHMapper/Models/DTO/EveAPI/Search/SearchCoporationResults.cs b/src/WHMapper/Models/DTO/EveAPI/Search/SearchCoporationResults.cs index 8a45cbf5..5fd23090 100644 --- a/src/WHMapper/Models/DTO/EveAPI/Search/SearchCoporationResults.cs +++ b/src/WHMapper/Models/DTO/EveAPI/Search/SearchCoporationResults.cs @@ -1,10 +1,8 @@ -using System; -using System.Text.Json.Serialization; -using WHMapper.Models.DTO.EveAPI.Universe; +using System.Text.Json.Serialization; namespace WHMapper.Models.DTO.EveAPI.Search { - public class SearchCoporationResults + public class SearchCoporationResults { [JsonPropertyName("corporation")] public int[]? Corporations { get; set; } diff --git a/src/WHMapper/Models/DTO/EveAPI/Universe/Category.cs b/src/WHMapper/Models/DTO/EveAPI/Universe/Category.cs index 65d896df..1c22647c 100644 --- a/src/WHMapper/Models/DTO/EveAPI/Universe/Category.cs +++ b/src/WHMapper/Models/DTO/EveAPI/Universe/Category.cs @@ -1,8 +1,4 @@ -using System; -using System.Text.Json.Serialization; -using MudBlazor; -using System.Text.RegularExpressions; -using System.Xml.Linq; +using System.Text.Json.Serialization; namespace WHMapper.Models.DTO.EveAPI.Universe { diff --git a/src/WHMapper/Models/DTO/EveAPI/Universe/Constellation.cs b/src/WHMapper/Models/DTO/EveAPI/Universe/Constellation.cs index 00721c86..e280e426 100644 --- a/src/WHMapper/Models/DTO/EveAPI/Universe/Constellation.cs +++ b/src/WHMapper/Models/DTO/EveAPI/Universe/Constellation.cs @@ -1,9 +1,8 @@ -using System; -using System.Text.Json.Serialization; +using System.Text.Json.Serialization; namespace WHMapper.Models.DTO.EveAPI.Universe { - public class Constellation + public class Constellation { [JsonPropertyName("constellation_id")] public required int ConstellationId { get; set; } diff --git a/src/WHMapper/Models/DTO/EveAPI/Universe/Group.cs b/src/WHMapper/Models/DTO/EveAPI/Universe/Group.cs index 6af9de5a..a66e5b4a 100644 --- a/src/WHMapper/Models/DTO/EveAPI/Universe/Group.cs +++ b/src/WHMapper/Models/DTO/EveAPI/Universe/Group.cs @@ -1,9 +1,8 @@ -using System; -using System.Text.Json.Serialization; +using System.Text.Json.Serialization; namespace WHMapper.Models.DTO.EveAPI.Universe { - public class Group + public class Group { [JsonPropertyName("group_id")] diff --git a/src/WHMapper/Models/DTO/EveAPI/Universe/Region.cs b/src/WHMapper/Models/DTO/EveAPI/Universe/Region.cs index f6493c43..879a8a91 100644 --- a/src/WHMapper/Models/DTO/EveAPI/Universe/Region.cs +++ b/src/WHMapper/Models/DTO/EveAPI/Universe/Region.cs @@ -1,9 +1,8 @@ -using System; -using System.Text.Json.Serialization; +using System.Text.Json.Serialization; namespace WHMapper.Models.DTO.EveAPI.Universe { - public class Region + public class Region { [JsonPropertyName("region_id")] public required int RegionId { get; set; } diff --git a/src/WHMapper/Models/DTO/EveAPI/Universe/Stargate.cs b/src/WHMapper/Models/DTO/EveAPI/Universe/Stargate.cs index ae917e82..756b8fd9 100644 --- a/src/WHMapper/Models/DTO/EveAPI/Universe/Stargate.cs +++ b/src/WHMapper/Models/DTO/EveAPI/Universe/Stargate.cs @@ -1,5 +1,4 @@ -using System; -using System.Text.Json.Serialization; +using System.Text.Json.Serialization; namespace WHMapper.Models.DTO.EveAPI.Universe { diff --git a/src/WHMapper/Models/DTO/EveAPI/Universe/Type.cs b/src/WHMapper/Models/DTO/EveAPI/Universe/Type.cs index c9c9f764..9e3f243c 100644 --- a/src/WHMapper/Models/DTO/EveAPI/Universe/Type.cs +++ b/src/WHMapper/Models/DTO/EveAPI/Universe/Type.cs @@ -1,5 +1,4 @@ -using System; -using System.Text.Json.Serialization; +using System.Text.Json.Serialization; namespace WHMapper.Models.DTO.EveAPI.Universe { diff --git a/src/WHMapper/Models/DTO/EveMapper/Enums/EveSystemTypeEnums.cs b/src/WHMapper/Models/DTO/EveMapper/Enums/EveSystemTypeEnums.cs index 3fcaea21..9937aa3f 100644 --- a/src/WHMapper/Models/DTO/EveMapper/Enums/EveSystemTypeEnums.cs +++ b/src/WHMapper/Models/DTO/EveMapper/Enums/EveSystemTypeEnums.cs @@ -1,5 +1,4 @@ -using System; -using System.ComponentModel; +using System.ComponentModel; using System.Reflection; namespace WHMapper.Models.DTO.EveMapper.Enums diff --git a/src/WHMapper/Models/DTO/EveMapper/Enums/WHEffectEnums.cs b/src/WHMapper/Models/DTO/EveMapper/Enums/WHEffectEnums.cs index 7ec8847e..137a2afc 100644 --- a/src/WHMapper/Models/DTO/EveMapper/Enums/WHEffectEnums.cs +++ b/src/WHMapper/Models/DTO/EveMapper/Enums/WHEffectEnums.cs @@ -1,5 +1,4 @@ -using System; -using System.ComponentModel; +using System.ComponentModel; namespace WHMapper.Models.DTO.EveMapper.Enums { diff --git a/src/WHMapper/Models/DTO/EveMapper/EveEntity/CharactereEntity.cs b/src/WHMapper/Models/DTO/EveMapper/EveEntity/CharactereEntity.cs index 227da443..4bbd2615 100644 --- a/src/WHMapper/Models/DTO/EveMapper/EveEntity/CharactereEntity.cs +++ b/src/WHMapper/Models/DTO/EveMapper/EveEntity/CharactereEntity.cs @@ -1,5 +1,4 @@ using System.Text.Json.Serialization; -using WHMapper.Models.DTO.EveAPI.Alliance; using WHMapper.Models.DTO.EveAPI.Character; using WHMapper.Models.DTO.EveMapper.Enums; diff --git a/src/WHMapper/Models/DTO/EveMapper/EveEntity/ConstellationEntity.cs b/src/WHMapper/Models/DTO/EveMapper/EveEntity/ConstellationEntity.cs index 566bf10f..d25947c4 100644 --- a/src/WHMapper/Models/DTO/EveMapper/EveEntity/ConstellationEntity.cs +++ b/src/WHMapper/Models/DTO/EveMapper/EveEntity/ConstellationEntity.cs @@ -1,7 +1,6 @@ using System.Text.Json.Serialization; using WHMapper.Models.DTO.EveAPI.Universe; using WHMapper.Models.DTO.EveMapper.Enums; -using WHMapper.Models.DTO.EveMapper.EveEntity; namespace WHMapper.Models.DTO.EveMapper.EveEntity; diff --git a/src/WHMapper/Models/DTO/EveMapper/EveEntity/RegionEntity.cs b/src/WHMapper/Models/DTO/EveMapper/EveEntity/RegionEntity.cs index 8200c6b9..461b09ef 100644 --- a/src/WHMapper/Models/DTO/EveMapper/EveEntity/RegionEntity.cs +++ b/src/WHMapper/Models/DTO/EveMapper/EveEntity/RegionEntity.cs @@ -1,7 +1,6 @@ using System.Text.Json.Serialization; using WHMapper.Models.DTO.EveAPI.Universe; using WHMapper.Models.DTO.EveMapper.Enums; -using WHMapper.Models.DTO.EveMapper.EveEntity; namespace WHMapper.Models.DTO.EveMapper.EveEntity; diff --git a/src/WHMapper/Models/DTO/EveMapper/EveEntity/SystemEntity.cs b/src/WHMapper/Models/DTO/EveMapper/EveEntity/SystemEntity.cs index c3e8eb87..81c0852a 100644 --- a/src/WHMapper/Models/DTO/EveMapper/EveEntity/SystemEntity.cs +++ b/src/WHMapper/Models/DTO/EveMapper/EveEntity/SystemEntity.cs @@ -1,6 +1,5 @@ using System.Text.Json.Serialization; using WHMapper.Models.DTO.EveMapper.Enums; -using WHMapper.Models.DTO.SDE; namespace WHMapper.Models.DTO.EveMapper.EveEntity { diff --git a/src/WHMapper/Models/DTO/EveMapper/EveEntity/WHEntity.cs b/src/WHMapper/Models/DTO/EveMapper/EveEntity/WHEntity.cs index 4ace4681..c68ee76d 100644 --- a/src/WHMapper/Models/DTO/EveMapper/EveEntity/WHEntity.cs +++ b/src/WHMapper/Models/DTO/EveMapper/EveEntity/WHEntity.cs @@ -1,5 +1,4 @@ using System.Text.Json.Serialization; -using WHMapper.Models.DTO.EveAPI.Universe; using WHMapper.Models.DTO.EveMapper.Enums; namespace WHMapper.Models.DTO.EveMapper.EveEntity; diff --git a/src/WHMapper/Models/DTO/EveMapper/EveSystemEffect.cs b/src/WHMapper/Models/DTO/EveMapper/EveSystemEffect.cs index f56b4d1f..694a05af 100644 --- a/src/WHMapper/Models/DTO/EveMapper/EveSystemEffect.cs +++ b/src/WHMapper/Models/DTO/EveMapper/EveSystemEffect.cs @@ -1,7 +1,4 @@ -using System; -using System.ComponentModel; - -namespace WHMapper.Models.DTO.EveMapper +namespace WHMapper.Models.DTO.EveMapper { public class EveSystemEffect { diff --git a/src/WHMapper/Models/DTO/EveMapper/WormholeType.cs b/src/WHMapper/Models/DTO/EveMapper/WormholeType.cs index 137982b3..524b04fc 100644 --- a/src/WHMapper/Models/DTO/EveMapper/WormholeType.cs +++ b/src/WHMapper/Models/DTO/EveMapper/WormholeType.cs @@ -1,10 +1,9 @@ -using System; -using WHMapper.Models.DTO.EveMapper.Enums; +using WHMapper.Models.DTO.EveMapper.Enums; using WHMapper.Models.DTO.EveMapper.EveEntity; namespace WHMapper.Models.DTO.EveMapper { - public class WormholeType + public class WormholeType { public string Name { private set; get; } public EveSystemType Destination { private set; get; } diff --git a/src/WHMapper/Models/DTO/InitialApplicationState.cs b/src/WHMapper/Models/DTO/InitialApplicationState.cs index aacb7169..03303843 100644 --- a/src/WHMapper/Models/DTO/InitialApplicationState.cs +++ b/src/WHMapper/Models/DTO/InitialApplicationState.cs @@ -1,5 +1,4 @@ -using System; -namespace WHMapper.Models.DTO +namespace WHMapper.Models.DTO { public class InitialApplicationState { diff --git a/src/WHMapper/Models/DTO/MapAdmin/MapAdmin.cs b/src/WHMapper/Models/DTO/MapAdmin/MapAdmin.cs new file mode 100644 index 00000000..a70dc466 --- /dev/null +++ b/src/WHMapper/Models/DTO/MapAdmin/MapAdmin.cs @@ -0,0 +1,19 @@ +using WHMapper.Models.Db; + +namespace WHMapper.Models.DTO.MapAdmin; + +public class MapAdmin + { + private WHMap? map = null; + public int Id => map?.Id ?? -1; + public string Name => map?.Name ?? string.Empty; + public IEnumerable? WHMapAccesses => map?.WHAccesses; + public bool ShowAccessDetails { get; set; } = false; + + public MapAdmin(WHMapper.Models.Db.WHMap map) + { + this.map = map; + this.ShowAccessDetails = false; + } + } + diff --git a/src/WHMapper/Models/DTO/SDE/SDESecondarySun.cs b/src/WHMapper/Models/DTO/SDE/SDESecondarySun.cs index a24351e6..4b6d73cf 100644 --- a/src/WHMapper/Models/DTO/SDE/SDESecondarySun.cs +++ b/src/WHMapper/Models/DTO/SDE/SDESecondarySun.cs @@ -1,7 +1,6 @@ -using System; -namespace WHMapper.Models.DTO.SDE +namespace WHMapper.Models.DTO.SDE { - public class SDESecondarySun + public class SDESecondarySun { public int EffectBeaconTypeID { get; set; } public int ItemID { get; set; } diff --git a/src/WHMapper/Models/DTO/SDE/SDESolarSystem.cs b/src/WHMapper/Models/DTO/SDE/SDESolarSystem.cs index 64eca840..c8ca2821 100644 --- a/src/WHMapper/Models/DTO/SDE/SDESolarSystem.cs +++ b/src/WHMapper/Models/DTO/SDE/SDESolarSystem.cs @@ -1,11 +1,9 @@ -using System; -using System.Collections.Concurrent; -using System.Text.Json.Serialization; +using System.Collections.Concurrent; using YamlDotNet.Serialization; namespace WHMapper.Models.DTO.SDE { - public class SDESolarSystem + public class SDESolarSystem { /* [JsonIgnore] diff --git a/src/WHMapper/Models/DTO/TokenProvider.cs b/src/WHMapper/Models/DTO/TokenProvider.cs index 79da1919..b791fd10 100644 --- a/src/WHMapper/Models/DTO/TokenProvider.cs +++ b/src/WHMapper/Models/DTO/TokenProvider.cs @@ -1,7 +1,4 @@ -using System; -using Microsoft.IdentityModel.JsonWebTokens; - -namespace WHMapper.Models.DTO +namespace WHMapper.Models.DTO { public class TokenProvider { diff --git a/src/WHMapper/Models/Db/Enums/WHAccessEnums.cs b/src/WHMapper/Models/Db/Enums/WHAccessEnums.cs index 80e381ee..0cc04335 100644 --- a/src/WHMapper/Models/Db/Enums/WHAccessEnums.cs +++ b/src/WHMapper/Models/Db/Enums/WHAccessEnums.cs @@ -1,5 +1,4 @@ -using System; -namespace WHMapper.Models.Db.Enums +namespace WHMapper.Models.Db.Enums { public enum WHAccessEntity { diff --git a/src/WHMapper/Models/Db/Enums/WHSignatureEnums.cs b/src/WHMapper/Models/Db/Enums/WHSignatureEnums.cs index 5106f3de..ae70c9de 100644 --- a/src/WHMapper/Models/Db/Enums/WHSignatureEnums.cs +++ b/src/WHMapper/Models/Db/Enums/WHSignatureEnums.cs @@ -1,5 +1,4 @@ -using System; -namespace WHMapper.Models.Db.Enums +namespace WHMapper.Models.Db.Enums { public enum WHSignatureGroup { diff --git a/src/WHMapper/Models/Db/Enums/WHSystemLinkEnums.cs b/src/WHMapper/Models/Db/Enums/WHSystemLinkEnums.cs index 3c4e3fda..03907666 100644 --- a/src/WHMapper/Models/Db/Enums/WHSystemLinkEnums.cs +++ b/src/WHMapper/Models/Db/Enums/WHSystemLinkEnums.cs @@ -1,5 +1,4 @@ -using System; -namespace WHMapper.Models.Db.Enums +namespace WHMapper.Models.Db.Enums { public enum SystemLinkSize : int { diff --git a/src/WHMapper/Models/Db/Enums/WHSystemStatusEnums.cs b/src/WHMapper/Models/Db/Enums/WHSystemStatusEnums.cs index 592370f5..8dc24793 100644 --- a/src/WHMapper/Models/Db/Enums/WHSystemStatusEnums.cs +++ b/src/WHMapper/Models/Db/Enums/WHSystemStatusEnums.cs @@ -1,4 +1,3 @@ -using System; namespace WHMapper.Models.Db.Enums { public enum WHSystemStatus diff --git a/src/WHMapper/Models/Db/WHAccess.cs b/src/WHMapper/Models/Db/WHAccess.cs index 2b085b52..69ce200a 100644 --- a/src/WHMapper/Models/Db/WHAccess.cs +++ b/src/WHMapper/Models/Db/WHAccess.cs @@ -1,10 +1,9 @@ -using System; -using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations; using WHMapper.Models.Db.Enums; namespace WHMapper.Models.Db { - public class WHAccess + public class WHAccess { [Key] public int Id { get; set; } @@ -18,7 +17,6 @@ public class WHAccess [Required] public WHAccessEntity EveEntity { get; set; } - [Obsolete("EF Requires it")] protected WHAccess() { } public WHAccess(int eveEntityId,string eveEntityName) : this(eveEntityId, eveEntityName, WHAccessEntity.Character) diff --git a/src/WHMapper/Models/Db/WHAdmin.cs b/src/WHMapper/Models/Db/WHAdmin.cs index 66c4fcad..976db159 100644 --- a/src/WHMapper/Models/Db/WHAdmin.cs +++ b/src/WHMapper/Models/Db/WHAdmin.cs @@ -1,10 +1,8 @@ -using System; -using System.ComponentModel.DataAnnotations; -using WHMapper.Models.DTO.ResponseMessage; +using System.ComponentModel.DataAnnotations; namespace WHMapper.Models.Db { - public class WHAdmin + public class WHAdmin { [Key] public int Id { get; set; } diff --git a/src/WHMapper/Models/Db/WHMap.cs b/src/WHMapper/Models/Db/WHMap.cs index 1e149ff3..1133ed2e 100644 --- a/src/WHMapper/Models/Db/WHMap.cs +++ b/src/WHMapper/Models/Db/WHMap.cs @@ -1,5 +1,4 @@ -using System; -using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations; namespace WHMapper.Models.Db { @@ -11,8 +10,9 @@ public class WHMap [Required] [StringLength(255, ErrorMessage = "Map name is too long.")] public string Name { get; set; } = string.Empty; - public ICollection WHSystems { get; } = new HashSet(); - public ICollection WHSystemLinks { get; } = new HashSet(); + public virtual ICollection WHSystems { get; } = new HashSet(); + public virtual ICollection WHSystemLinks { get; } = new HashSet(); + public virtual ICollection WHAccesses { get; } = new HashSet(); [Obsolete("EF Requires it")] protected WHMap() { } diff --git a/src/WHMapper/Models/Db/WHNote.cs b/src/WHMapper/Models/Db/WHNote.cs index 0bc5a2d7..30bfd3d3 100644 --- a/src/WHMapper/Models/Db/WHNote.cs +++ b/src/WHMapper/Models/Db/WHNote.cs @@ -1,14 +1,16 @@ -using System; -using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations; using WHMapper.Models.Db.Enums; namespace WHMapper.Models.Db { - public class WHNote + public class WHNote { [Key] public int Id { get; set; } + [Required] + public int MapId { get; set; } = -1; + [Required] public int SoloarSystemId { get; set; } = -1; @@ -20,21 +22,22 @@ public class WHNote [Obsolete("EF Requires it")] protected WHNote() { } - public WHNote(int soloarSystemId,string comment) - : this(soloarSystemId,WHSystemStatus.Unknown,comment) + public WHNote(int mapId,int soloarSystemId,string comment) + : this(mapId,soloarSystemId,WHSystemStatus.Unknown,comment) { } - public WHNote(int soloarSystemId, WHSystemStatus systemStatus) - :this(soloarSystemId,systemStatus,string.Empty) + public WHNote(int mapId,int soloarSystemId, WHSystemStatus systemStatus) + :this(mapId,soloarSystemId,systemStatus,string.Empty) { } - public WHNote(int soloarSystemId, WHSystemStatus systemStatus,string comment) + public WHNote(int mapId,int soloarSystemId, WHSystemStatus systemStatus,string comment) { + MapId = mapId; SoloarSystemId = soloarSystemId; SystemStatus = systemStatus; Comment = comment; diff --git a/src/WHMapper/Models/Db/WHRoute.cs b/src/WHMapper/Models/Db/WHRoute.cs index bc23c254..c30a77e9 100644 --- a/src/WHMapper/Models/Db/WHRoute.cs +++ b/src/WHMapper/Models/Db/WHRoute.cs @@ -10,19 +10,24 @@ public class WHRoute public int? EveEntityId { get; set; } + [Required] + public int MapId { get; set; } + [Required] public int SolarSystemId { get; set; } [Obsolete("EF Requires it")] protected WHRoute() { } - public WHRoute(int solarSystemId) + public WHRoute(int mapId,int solarSystemId) { + MapId = mapId; SolarSystemId = solarSystemId; } - public WHRoute(int solarSystemId,int eveEntityId) + public WHRoute(int mapid,int solarSystemId,int eveEntityId) { + MapId = mapid; EveEntityId = eveEntityId; SolarSystemId = solarSystemId; } diff --git a/src/WHMapper/Models/Db/WHSignature.cs b/src/WHMapper/Models/Db/WHSignature.cs index 166948a7..fabb2c2a 100644 --- a/src/WHMapper/Models/Db/WHSignature.cs +++ b/src/WHMapper/Models/Db/WHSignature.cs @@ -1,5 +1,4 @@ -using System; -using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations; using WHMapper.Models.Db.Enums; namespace WHMapper.Models.Db diff --git a/src/WHMapper/Models/Db/WHSystem.cs b/src/WHMapper/Models/Db/WHSystem.cs index d0855a22..10fe089b 100644 --- a/src/WHMapper/Models/Db/WHSystem.cs +++ b/src/WHMapper/Models/Db/WHSystem.cs @@ -1,6 +1,5 @@  using System.ComponentModel.DataAnnotations; -using System.ComponentModel.DataAnnotations.Schema; namespace WHMapper.Models.Db @@ -24,7 +23,7 @@ public class WHSystem [Required] public float SecurityStatus { get; set; } - public ICollection WHSignatures { get; } = new HashSet(); + public virtual ICollection WHSignatures { get; } = new HashSet(); public double PosX { get; set; } = 0.0; diff --git a/src/WHMapper/Models/Db/WHSystemLink.cs b/src/WHMapper/Models/Db/WHSystemLink.cs index 903f5928..f6cdb691 100644 --- a/src/WHMapper/Models/Db/WHSystemLink.cs +++ b/src/WHMapper/Models/Db/WHSystemLink.cs @@ -1,5 +1,4 @@ -using System; -using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations; using WHMapper.Models.Db.Enums; namespace WHMapper.Models.Db @@ -28,7 +27,7 @@ public class WHSystemLink public SystemLinkMassStatus MassStatus { get; set; } = SystemLinkMassStatus.Normal; [Required] - public ICollection JumpHistory { get; } = new HashSet(); + public virtual ICollection JumpHistory { get; } = new HashSet(); [Obsolete("EF Requires it")] diff --git a/src/WHMapper/Pages/Login.cshtml.cs b/src/WHMapper/Pages/Login.cshtml.cs index d573ef19..eac112b4 100644 --- a/src/WHMapper/Pages/Login.cshtml.cs +++ b/src/WHMapper/Pages/Login.cshtml.cs @@ -1,6 +1,4 @@ -using System.Security.Claims; using Microsoft.AspNetCore.Authentication; -using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; diff --git a/src/WHMapper/Pages/Logout.cshtml.cs b/src/WHMapper/Pages/Logout.cshtml.cs index 8a65af11..a7adb6d6 100644 --- a/src/WHMapper/Pages/Logout.cshtml.cs +++ b/src/WHMapper/Pages/Logout.cshtml.cs @@ -1,15 +1,12 @@ using System.Net; -using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.Json; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; -using WHMapper.Models.DTO; using WHMapper.Services.EveOAuthProvider; namespace WHMapper.Pages { diff --git a/src/WHMapper/Pages/Mapper/Add.cs b/src/WHMapper/Pages/Mapper/Add.cs deleted file mode 100644 index 83e88b10..00000000 --- a/src/WHMapper/Pages/Mapper/Add.cs +++ /dev/null @@ -1,172 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Reflection.Emit; -using Blazor.Diagrams; -using Blazor.Diagrams.Core.Events; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Components; -using Microsoft.AspNetCore.SignalR.Client; -using Microsoft.Extensions.Logging; -using MudBlazor; -using MudBlazor.Charts; -using WHMapper.Models.Custom.Node; -using WHMapper.Models.Db; -using WHMapper.Models.DTO.EveAPI.Universe; -using WHMapper.Models.DTO.EveMapper.EveEntity; -using WHMapper.Models.DTO.SDE; -using WHMapper.Repositories.WHMaps; -using WHMapper.Repositories.WHSystems; -using WHMapper.Services.Anoik; -using WHMapper.Services.EveAPI; -using WHMapper.Services.EveMapper; -using WHMapper.Services.EveOnlineUserInfosProvider; -using WHMapper.Services.SDE; -using WHMapper.Services.WHSignature; -using YamlDotNet.Core.Tokens; -using static MudBlazor.Colors; - -namespace WHMapper.Pages.Mapper -{ - [Authorize(Policy = "Access")] - public partial class Add :ComponentBase - { - private const string MSG_SEARCH_ERROR = "Search System Error"; - private const string MSG_BAD_SOLAR_SYSTEM_NAME_ERROR = "Bad solar system name"; - private const string MSG_ADD_WORHMOLE_DB_ERROR = "Add Wormhole db error"; - - - [Inject] - public ILogger Logger { get; set; } = null!; - - [Inject] - private IEveMapperHelper MapperServices { get; set; } = null!; - - [Inject] - private IEveMapperService EveMapperEntity { get; set; } = null!; - - [Inject] - IWHSystemRepository DbWHSystems { get; set; } = null!; - - [Inject] - private ISnackbar Snackbar { get; set; } = null!; - - - [Inject] - private IEveMapperSearch EveMapperSearch { get; set; } = null!; - - [CascadingParameter] - MudDialogInstance MudDialog { get; set; } = null!; - - [Parameter] - public BlazorDiagram CurrentDiagram { get; set; } = null!; - - [Parameter] - public WHMap CurrentWHMap { get; set; } = null!; - - [Parameter] - public double MouseX { get; set; } - - [Parameter] - public double MouseY { get; set; } - - private MudForm _form = null!; - private bool _success = false; - - private SDESolarSystem _searchResult = null!; - - - private SemaphoreSlim _semaphoreSlim = new SemaphoreSlim(1, 1); - - protected override async Task OnInitializedAsync() - { - await base.OnInitializedAsync(); - } - - private async Task Submit() - { - await _form.Validate(); - - if (_form.IsValid) - { - await _semaphoreSlim.WaitAsync(); - try - { - - if (CurrentWHMap == null || CurrentDiagram==null)//add log and message - { - Logger.LogError("CurrentWHMap or CurrentDiagram is null"); - Snackbar?.Add("CurrentWHMap or CurrentDiagram is null", Severity.Error); - MudDialog.Close(DialogResult.Cancel); - } - - if(_searchResult==null) - { - Logger.LogError("Solar System not found"); - Snackbar?.Add("Solar System not found", Severity.Error); - MudDialog.Close(DialogResult.Ok(0)); - } - - - - if(CurrentWHMap?.WHSystems.Where(x => x.SoloarSystemId == _searchResult?.SolarSystemID).FirstOrDefault()!=null) - { - Snackbar?.Add("Solar System is already added", Severity.Normal); - MudDialog.Close(DialogResult.Cancel); - } - - int solarSystemId = ((_searchResult==null) ? -1 : _searchResult.SolarSystemID); - int currentMapId = ((CurrentWHMap == null) ? -1 : CurrentWHMap.Id); - SystemEntity? solarSystem = await EveMapperEntity.GetSystem(solarSystemId); - - - WHSystem? newWHSystem=null!; - if (solarSystem == null) - { - Logger.LogError("Solar System not found"); - Snackbar?.Add("Solar System not found", Severity.Error); - MudDialog.Close(DialogResult.Cancel); - } - else - newWHSystem = await DbWHSystems.Create(new WHSystem(currentMapId,solarSystem.Id, solarSystem.Name, solarSystem.SecurityStatus, MouseX, MouseY)); //change position - - - if (newWHSystem == null) - { - Logger.LogError(MSG_ADD_WORHMOLE_DB_ERROR); - Snackbar?.Add(MSG_ADD_WORHMOLE_DB_ERROR, Severity.Error); - MudDialog.Close(DialogResult.Cancel); - } - - EveSystemNodeModel nodeModel = await MapperServices.DefineEveSystemNodeModel(newWHSystem!); - CurrentWHMap?.WHSystems.Add(newWHSystem!); - CurrentDiagram?.Nodes.Add(nodeModel); - - Snackbar?.Add(String.Format("{0} solar system successfully added",nodeModel.Name), Severity.Success); - MudDialog.Close(DialogResult.Ok(newWHSystem!.Id)); - - } - catch (Exception ex) - { - Snackbar?.Add(ex.Message, Severity.Error); - MudDialog.Close(DialogResult.Cancel); - } - finally - { - _semaphoreSlim.Release(); - } - } - else - { - Logger.LogError(MSG_BAD_SOLAR_SYSTEM_NAME_ERROR); - Snackbar?.Add(MSG_BAD_SOLAR_SYSTEM_NAME_ERROR, Severity.Error); - MudDialog.Close(DialogResult.Cancel); - } - } - - private void Cancel() - { - MudDialog.Cancel(); - } - } -} - diff --git a/src/WHMapper/Pages/Mapper/Administration/Delete.cs b/src/WHMapper/Pages/Mapper/Administration/Access/Delete.cs similarity index 93% rename from src/WHMapper/Pages/Mapper/Administration/Delete.cs rename to src/WHMapper/Pages/Mapper/Administration/Access/Delete.cs index 1d2183f3..e98cb7a4 100644 --- a/src/WHMapper/Pages/Mapper/Administration/Delete.cs +++ b/src/WHMapper/Pages/Mapper/Administration/Access/Delete.cs @@ -1,17 +1,10 @@ -using System; -using System.Text.RegularExpressions; -using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Components; -using Microsoft.Extensions.Logging; using MudBlazor; -using WHMapper.Models.Db; using WHMapper.Repositories.WHAccesses; using WHMapper.Repositories.WHAdmins; -using WHMapper.Repositories.WHSignatures; -using WHMapper.Repositories.WHSystems; -using WHMapper.Services.EveAPI; -namespace WHMapper.Pages.Mapper.Administration +namespace WHMapper.Pages.Mapper.Administration.Access { [Authorize(Policy = "Admin")] public partial class Delete: Microsoft.AspNetCore.Components.ComponentBase diff --git a/src/WHMapper/Pages/Mapper/Administration/Delete.razor b/src/WHMapper/Pages/Mapper/Administration/Access/Delete.razor similarity index 100% rename from src/WHMapper/Pages/Mapper/Administration/Delete.razor rename to src/WHMapper/Pages/Mapper/Administration/Access/Delete.razor diff --git a/src/WHMapper/Pages/Mapper/Administration/Overview.cs b/src/WHMapper/Pages/Mapper/Administration/Access/Overview.cs similarity index 98% rename from src/WHMapper/Pages/Mapper/Administration/Overview.cs rename to src/WHMapper/Pages/Mapper/Administration/Access/Overview.cs index 602c02a8..25aa3403 100644 --- a/src/WHMapper/Pages/Mapper/Administration/Overview.cs +++ b/src/WHMapper/Pages/Mapper/Administration/Access/Overview.cs @@ -1,5 +1,4 @@ -using System; -using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Components; using MudBlazor; using WHMapper.Models.Db; @@ -9,7 +8,8 @@ using WHMapper.Repositories.WHAccesses; using WHMapper.Repositories.WHAdmins; using WHMapper.Services.EveMapper; -namespace WHMapper.Pages.Mapper.Administration + +namespace WHMapper.Pages.Mapper.Administration.Access { [Authorize(Policy = "Admin")] public partial class Overview : ComponentBase diff --git a/src/WHMapper/Pages/Mapper/Administration/Overview.razor b/src/WHMapper/Pages/Mapper/Administration/Access/Overview.razor similarity index 100% rename from src/WHMapper/Pages/Mapper/Administration/Overview.razor rename to src/WHMapper/Pages/Mapper/Administration/Access/Overview.razor diff --git a/src/WHMapper/Pages/Mapper/Administration/Map/Add.cs b/src/WHMapper/Pages/Mapper/Administration/Map/Add.cs new file mode 100644 index 00000000..d49d3c34 --- /dev/null +++ b/src/WHMapper/Pages/Mapper/Administration/Map/Add.cs @@ -0,0 +1,72 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Components; +using MudBlazor; +using System; +using WHMapper.Models.Db; +using WHMapper.Repositories.WHMaps; + +namespace WHMapper.Pages.Mapper.Administration.Map; + + + +[Authorize(Policy = "Admin")] +public partial class Add : ComponentBase +{ + private MudForm _form = null!; + private bool _success = false; + + private string _mapName = null!; + + [Inject] + private ILogger Logger { get; set; } = null!; + + [Inject] + private ISnackbar Snackbar { get; set; } = null!; + + [Inject] + private IWHMapRepository DbMap {get;set;}=null!; + + [CascadingParameter] + MudDialogInstance MudDialog { get; set; } = null!; + + + + private async Task Submit() + { + await _form.Validate(); + + if (_form.IsValid) + { + // Check if map name already exists + var existingMap = await DbMap.GetByNameAsync(_mapName); + if (existingMap != null) + { + Snackbar.Add("Map name already exists. Please choose a different name.", Severity.Warning); + return; + } + + WHMap newMap = new WHMap(_mapName); + if(await DbMap.Create(newMap) == null) + { + Snackbar.Add("Error while creating map", Severity.Error); + MudDialog.Close(DialogResult.Cancel); + } + else + { + MudDialog.Close(DialogResult.Ok(newMap)); + } + } + else + { + Logger.LogError("Error while validating form"); + Snackbar?.Add("Error while validating form", Severity.Error); + MudDialog.Close(DialogResult.Cancel); + } + } + + + private void Cancel() + { + MudDialog.Cancel(); + } +} diff --git a/src/WHMapper/Pages/Mapper/Administration/Map/Add.razor b/src/WHMapper/Pages/Mapper/Administration/Map/Add.razor new file mode 100644 index 00000000..9c3db5d9 --- /dev/null +++ b/src/WHMapper/Pages/Mapper/Administration/Map/Add.razor @@ -0,0 +1,11 @@ + + + + + + + + Cancel + Add Map + + diff --git a/src/WHMapper/Pages/Mapper/Administration/Map/AddAccess.cs b/src/WHMapper/Pages/Mapper/Administration/Map/AddAccess.cs new file mode 100644 index 00000000..555230c8 --- /dev/null +++ b/src/WHMapper/Pages/Mapper/Administration/Map/AddAccess.cs @@ -0,0 +1,129 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Components; +using MudBlazor; +using System; +using WHMapper.Models.Db; +using WHMapper.Repositories.WHAccesses; +using WHMapper.Repositories.WHMaps; +using WHMapper.Services.EveMapper; + +namespace WHMapper.Pages.Mapper.Administration.Map; + +[Authorize(Policy = "Admin")] +public partial class AddAccess : ComponentBase +{ + private MudForm _form = null!; + private bool _success = false; + + private IEnumerable _accesses = null!; + private WHAccess _selectedAccess = null!; + private IEnumerable? _selectedAccesses = new HashSet(); + + private Func _listConverter = a => a?.EveEntityName ?? string.Empty; + + [Inject] + private ILogger Logger { get; set; } = null!; + + [Inject] + private ISnackbar Snackbar { get; set; } = null!; + + + [Inject] + private IWHAccessRepository DbWHAccesses { get; set; } = null!; + + [Inject] + private IWHMapRepository DbWHMaps { get; set; } = null!; + + + [CascadingParameter] + MudDialogInstance MudDialog { get; set; } = null!; + + [Parameter] + public int MapId { get; set; } + + private WHMap _map = null!; + + + + protected override async Task OnInitializedAsync() + { + _form = new MudForm(); + + await base.OnInitializedAsync(); + } + + protected override async Task OnParametersSetAsync() + { + + var accesses = await DbWHAccesses.GetAll(); + _map = await DbWHMaps.GetById(MapId); + if(_map == null) + { + Logger.LogError("Map not found"); + Snackbar.Add("Map not found", Severity.Error); + MudDialog.Cancel(); + return; + } + + if(accesses == null) + { + Logger.LogError("No accesses found"); + Snackbar.Add("No accesses found", Severity.Error); + MudDialog.Cancel(); + return; + } + + if(_map.WHAccesses.Any()) + { + _accesses = accesses.Where(a => !_map.WHAccesses.Any(ma => ma.Id == a.Id)); + } + else + { + _accesses = accesses; + } + + await base.OnParametersSetAsync(); + } + + + + + private async Task Submit() + { + await _form.Validate(); + + if (_form.IsValid) + { + if(_selectedAccesses == null) + { + Logger.LogError("No access selected"); + Snackbar.Add("No access selected", Severity.Error); + return; + } + + + foreach(var access in _selectedAccesses) + { + await DbWHMaps.AddMapAccess(_map.Id,access.Id); + } + + + Snackbar.Add("Access added", Severity.Success); + MudDialog.Close(DialogResult.Ok(_selectedAccesses.ToList())); + + } + else + { + Logger.LogError("Error while validating form"); + Snackbar?.Add("Error while validating form", Severity.Error); + MudDialog.Close(DialogResult.Cancel); + } + } + private void Cancel() + { + MudDialog.Cancel(); + } + + + +} diff --git a/src/WHMapper/Pages/Mapper/Administration/Map/AddAccess.razor b/src/WHMapper/Pages/Mapper/Administration/Map/AddAccess.razor new file mode 100644 index 00000000..8ad6bf19 --- /dev/null +++ b/src/WHMapper/Pages/Mapper/Administration/Map/AddAccess.razor @@ -0,0 +1,24 @@ +@using MudBlazor +@using WHMapper.Models.Db; + + + + + + + @if(_accesses != null) + { + foreach(WHAccess item in _accesses) + { + @item.EveEntityName + } + } + + + + + Cancel + Add Map Access + + + diff --git a/src/WHMapper/Pages/Mapper/Administration/Map/Delete.cs b/src/WHMapper/Pages/Mapper/Administration/Map/Delete.cs new file mode 100644 index 00000000..5df1f20e --- /dev/null +++ b/src/WHMapper/Pages/Mapper/Administration/Map/Delete.cs @@ -0,0 +1,115 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Components; +using MudBlazor; +using System.Threading.Tasks; +using WHMapper.Repositories.WHMaps; + +namespace WHMapper.Pages.Mapper.Administration.Map; + +[Authorize(Policy = "Access")] +public partial class Delete : ComponentBase +{ + private const string MSG_DELETE_MAP = "Do you really want to delete this map?"; + private const string MSG_DELETE_MAPS = "Do you really want to delete all maps?"; + + [Inject] + private ILogger Logger { get; set; } = null!; + + [Inject] + private ISnackbar Snackbar { get; set; } = null!; + + [Inject] + private IWHMapRepository DbWHMap { get; set; } = null!; + + [CascadingParameter] + private MudDialogInstance MudDialog { get; set; } = null!; + + [Parameter] + public int? MapId { get; set; } + + private async Task Submit() + { + if (!MapId.HasValue) + { + await DeleteMaps(); + } + else if (MapId.Value > 0) + { + await DeleteMap(); + } + else + { + LogError("Bad map parameters"); + } + } + + private async Task DeleteMap() + { + if (DbWHMap == null) + { + LogError("DbWHMap is null"); + MudDialog.Close(DialogResult.Ok(false)); + return; + } + + if (MapId.HasValue && MapId.Value > 0) + { + bool isDeleted = await DbWHMap.DeleteById(MapId.Value); + if (isDeleted) + { + LogSuccess("Map is successfully deleted"); + MudDialog.Close(DialogResult.Ok(true)); + } + else + { + LogError("No Map deleted"); + MudDialog.Close(DialogResult.Ok(false)); + } + } + else + { + LogError("Bad map parameters"); + MudDialog.Close(DialogResult.Ok(false)); + } + } + + private async Task DeleteMaps() + { + if (DbWHMap == null) + { + LogError("DbWHMap is null"); + MudDialog.Close(DialogResult.Ok(false)); + return; + } + + bool result = await DbWHMap.DeleteAll(); + if (result) + { + LogSuccess("All Maps are successfully deleted"); + MudDialog.Close(DialogResult.Ok(true)); + } + else + { + LogError("No Map deleted"); + MudDialog.Close(DialogResult.Ok(false)); + } + + } + + private void Cancel() + { + MudDialog?.Cancel(); + } + + private void LogError(string message) + { + Logger.LogError(message); + Snackbar.Add(message, Severity.Error); + } + + private void LogSuccess(string message) + { + Logger.LogInformation(message); + Snackbar.Add(message, Severity.Success); + } +} diff --git a/src/WHMapper/Pages/Mapper/Administration/Map/Delete.razor b/src/WHMapper/Pages/Mapper/Administration/Map/Delete.razor new file mode 100644 index 00000000..3be2b32f --- /dev/null +++ b/src/WHMapper/Pages/Mapper/Administration/Map/Delete.razor @@ -0,0 +1,17 @@ + + + @if (MapId > 0) + { + @MSG_DELETE_MAP + } + else + { + @MSG_DELETE_MAPS + } + + + Cancel + Delete + + + diff --git a/src/WHMapper/Pages/Mapper/Administration/Map/Overview.cs b/src/WHMapper/Pages/Mapper/Administration/Map/Overview.cs new file mode 100644 index 00000000..5a00c9b2 --- /dev/null +++ b/src/WHMapper/Pages/Mapper/Administration/Map/Overview.cs @@ -0,0 +1,267 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Components; +using MudBlazor; +using WHMapper.Models.Db; +using WHMapper.Repositories.WHMaps; +using WHMapper.Models.DTO.MapAdmin; +using System.Linq; +using WHMapper.Repositories.WHAccesses; +using WHMapper.Services.EveMapper; + +namespace WHMapper.Pages.Mapper.Administration.Map; + +[Authorize(Policy = "Admin")] +public partial class Overview : ComponentBase, IAsyncDisposable +{ + [Inject] + private IDialogService DialogService { get; set; } = null!; + + [Inject] + private ISnackbar Snackbar { get; set; } = null!; + + [Inject] + public ILogger Logger { get; set; } = null!; + + [Inject] + private IWHMapRepository DbWHMap { get; set; } = null!; + [Inject] + private IWHAccessRepository DbWHAccess { get; set; } = null!; + + [Inject] + private IEveMapperRealTimeService EveMapperRealTimeService { get; set; } = null!; + + private IList? Maps { get; set; } = null; + private MapAdmin _selectedMap = null!; + private WHAccess _selectedWHAccess = null!; + + private IEnumerable? WHAccesses { get; set; } = null; + + + protected override async Task OnInitializedAsync() + { + await base.OnInitializedAsync(); + if(EveMapperRealTimeService!=null) + { + await EveMapperRealTimeService.Start(); + } + } + + + + + + protected override async Task OnParametersSetAsync() + { + await Restore(); + await base.OnParametersSetAsync(); + } + + private async Task Restore() + { + if (DbWHMap == null) + { + Logger.LogError("DbWHMap is null"); + return; + } + + WHAccesses = await DbWHAccess.GetAll(); + + var maps = await DbWHMap.GetAll(); + Maps = maps?.Select(m => new MapAdmin(m)).ToList(); + } + + private Task ShowMapAccess(int mapId) + { + if (Maps == null) + { + Logger.LogError("Maps is null"); + Snackbar.Add("Maps is null", Severity.Error); + return Task.CompletedTask; + } + + var tmpMapAdmin = Maps.FirstOrDefault(x => x.Id == mapId); + if (tmpMapAdmin != null) + { + tmpMapAdmin.ShowAccessDetails = !tmpMapAdmin.ShowAccessDetails; + } + + return Task.CompletedTask; + } + + private async Task OpenAddMap() + { + var options = new DialogOptions { CloseButton = true, MaxWidth = MaxWidth.ExtraSmall }; + var dialog = await DialogService.ShowAsync("Add Map", new DialogParameters(), options); + var result = await dialog.Result; + + if (result != null && !result.Canceled) + { + var newMap = result.Data as WHMap; + if (newMap == null) + { + Logger.LogError("newMap is null"); + Snackbar.Add("newMap is null", Severity.Error); + return; + } + if(Maps == null) + { + Maps=new List(); + } + + Maps.Add(new MapAdmin(newMap)); + EveMapperRealTimeService?.NotifyMapAdded(newMap.Id); + } + } + + private async Task DeleteAllMaps() + { + if (Maps == null) + { + Logger.LogError("Maps is null"); + Snackbar.Add("Maps is null", Severity.Error); + return; + } + + var options = new DialogOptions { CloseButton = true, MaxWidth = MaxWidth.ExtraSmall }; + var dialog = await DialogService.ShowAsync("Delete All Maps", new DialogParameters(), options); + var result = await dialog.Result; + + if (result != null && !result.Canceled) + { + Maps.Clear(); + EveMapperRealTimeService?.NotifyAllMapsRemoved(); + } + } + + private async Task DeleteMap(int mapId) + { + if (Maps == null) + { + Logger.LogError("Maps is null"); + return; + } + + var parameters = new DialogParameters { { "MapId", mapId } }; + var options = new DialogOptions { CloseButton = true, MaxWidth = MaxWidth.ExtraSmall }; + var dialog = await DialogService.ShowAsync("Delete Map", parameters, options); + var result = await dialog.Result; + + if (result != null && !result.Canceled) + { + ((List)Maps).RemoveAll(x => x.Id == mapId); + EveMapperRealTimeService?.NotifyMapRemoved(mapId); + } + } + + private async Task OpenAddAccess(int mapId) + { + if (Maps == null) + { + Logger.LogError("Maps is null"); + return; + } + + var options = new DialogOptions { CloseButton = true, MaxWidth = MaxWidth.ExtraSmall }; + var parameters = new DialogParameters { { "MapId", mapId} }; + var dialog = await DialogService.ShowAsync("Map Access Manager", parameters, options); + var result = await dialog.Result; + + if (result != null && !result.Canceled) + { + List accesses = result.Data as List ?? new List(); + + MapAdmin? map = Maps.FirstOrDefault(x => x.Id == mapId); + if (map == null) + { + Logger.LogError("map is null"); + Snackbar.Add("map is null", Severity.Error); + return; + } + + foreach (var access in accesses) + { + if (map.WHMapAccesses is HashSet accessList) + { + accessList.Add(access); + } + else + { + Logger.LogError("WHMapAccesses is not a List"); + Snackbar.Add("WHMapAccesses is not a List", Severity.Error); + } + } + + EveMapperRealTimeService?.NotifyMapAccessesAdded(mapId, accesses.Select(x => x.Id).ToList()); + } + } + + private async Task RemoveAccess(int mapId,int accessId) + { + + var parameters = new DialogParameters { {"AccessId", accessId },{ "MapId",mapId } }; + var options = new DialogOptions { CloseButton = true, MaxWidth = MaxWidth.ExtraSmall }; + var dialog = await DialogService.ShowAsync("Remove Access", parameters, options); + var result = await dialog.Result; + + if (result != null && !result.Canceled) + { + MapAdmin map = Maps.FirstOrDefault(x => x.Id == mapId); + if (map == null) + { + Logger.LogError("map is null"); + Snackbar.Add("map is null", Severity.Error); + return; + } + + if (map.WHMapAccesses is HashSet accessList) + { + accessList.RemoveWhere(x => x.Id == accessId); + } + else + { + Logger.LogError("WHMapAccesses is not a List"); + Snackbar.Add("WHMapAccesses is not a List", Severity.Error); + } + + EveMapperRealTimeService?.NotifyMapAccessRemoved(mapId, accessId); + } + } + + private async Task RemoveAllAccesses(int mapId) + { + var parameters = new DialogParameters { { "MapId", mapId } }; + var options = new DialogOptions { CloseButton = true, MaxWidth = MaxWidth.ExtraSmall }; + var dialog = await DialogService.ShowAsync("Remove All Accesses", parameters, options); + var result = await dialog.Result; + + if (result != null && !result.Canceled) + { + MapAdmin? map = Maps.FirstOrDefault(x => x.Id == mapId); + if (map == null) + { + Logger.LogError("map is null"); + Snackbar.Add("map is null", Severity.Error); + return; + } + if (map.WHMapAccesses is HashSet accessList) + { + accessList.Clear(); + } + else + { + Logger.LogError("WHMapAccesses is not a List"); + Snackbar.Add("WHMapAccesses is not a List", Severity.Error); + } + EveMapperRealTimeService?.NotifyMapAllAccessesRemoved(mapId); + } + } + + public async ValueTask DisposeAsync() + { + if (EveMapperRealTimeService != null) + { + await EveMapperRealTimeService.Stop(); + await EveMapperRealTimeService.DisposeAsync(); + } + } +} diff --git a/src/WHMapper/Pages/Mapper/Administration/Map/Overview.razor b/src/WHMapper/Pages/Mapper/Administration/Map/Overview.razor new file mode 100644 index 00000000..8eda86dc --- /dev/null +++ b/src/WHMapper/Pages/Mapper/Administration/Map/Overview.razor @@ -0,0 +1,86 @@ +@page "/whmappermapadmin" +@using WHMapper.Models.Db; +@using WHMapper.Models.DTO.MapAdmin; + + + + + + + + Map Admin: + + + + + + + + + Name + Access + + + + @context.Name + + @if(WHAccesses!=null && WHAccesses.Any()) + { + @((context.ShowAccessDetails == true)? "Hide" : "Show") Access + } + else + { + Full Access + } + + + + + + + @if(context.ShowAccessDetails) + { + + + + + + + Map Access Details for @context.Name + + + + + + + + + + + + + + Eve Character Id + Eve Character Name + + + + @accessContext.EveEntity.ToString() + @accessContext.EveEntityName + + + + + + + + + + } + + + + + diff --git a/src/WHMapper/Pages/Mapper/Administration/Map/RemoveAccess.cs b/src/WHMapper/Pages/Mapper/Administration/Map/RemoveAccess.cs new file mode 100644 index 00000000..e3c57c4d --- /dev/null +++ b/src/WHMapper/Pages/Mapper/Administration/Map/RemoveAccess.cs @@ -0,0 +1,133 @@ + +using WHMapper.Repositories.WHMaps; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Components; +using MudBlazor; + +namespace WHMapper.Pages.Mapper.Administration.Map; + +[Authorize(Policy = "Access")] +public partial class RemoveAccess : ComponentBase +{ + private const string MSG_DELETE_ACCESS = "Do you really want to delete this access?"; + private const string MSG_DELETE_ACCESSES = "Do you really want to delete all accesses?"; + + [Inject] + private ILogger Logger { get; set; } = null!; + + [Inject] + private ISnackbar Snackbar { get; set; } = null!; + + [Inject] + private IWHMapRepository DbWHMap { get; set; } = null!; + + [CascadingParameter] + private MudDialogInstance MudDialog { get; set; } = null!; + + + [Parameter] + public int? MapId { get; set; } + + [Parameter] + public int? AccessId { get; set; } + + + private async Task Submit() + { + + if(AccessId.HasValue && MapId.HasValue) + { + await DeleteMapAccess(); + } + else if (!AccessId.HasValue && MapId.HasValue) + { + await DeleteMapAccesses(); + } + else + { + LogError("Bad map parameters"); + Snackbar.Add("Bad map parameters", Severity.Error); + } + } + + private async Task DeleteMapAccess() + { + try + { + if(!MapId.HasValue || !AccessId.HasValue) + { + LogError("Bad map parameters"); + Snackbar.Add("Bad map parameters", Severity.Error); + return; + } + + var result = await DbWHMap.DeleteMapAccess(MapId.Value, AccessId.Value); + if (result) + { + LogSuccess("Map access removed"); + Snackbar.Add("Map access removed", Severity.Success); + MudDialog?.Close(DialogResult.Ok(AccessId.Value)); + } + else + { + LogError("Map access not removed"); + Snackbar.Add("Map access not removed", Severity.Error); + } + } + catch (Exception ex) + { + LogError("Error removing map access"); + Snackbar.Add("Error removing map access", Severity.Error); + } + } + + private async Task DeleteMapAccesses() + { + try + { + if (!MapId.HasValue) + { + LogError("Bad map parameters"); + Snackbar.Add("Bad map parameters", Severity.Error); + return; + } + + var result = await DbWHMap.DeleteMapAccesses(MapId.Value); + if (result) + { + LogSuccess("Map accesses removed"); + Snackbar.Add("Map accesses removed", Severity.Success); + MudDialog?.Close(DialogResult.Ok(true)); + } + else + { + LogError("Map accesses not removed"); + Snackbar.Add("Map accesses not removed", Severity.Error); + } + } + catch (Exception ex) + { + LogError("Error removing map accesses"); + Snackbar.Add("Error removing map accesses", Severity.Error); + } + } + + + + private void Cancel() + { + MudDialog?.Cancel(); + } + + private void LogError(string message) + { + Logger.LogError(message); + Snackbar.Add(message, Severity.Error); + } + + private void LogSuccess(string message) + { + Logger.LogInformation(message); + Snackbar.Add(message, Severity.Success); + } +} \ No newline at end of file diff --git a/src/WHMapper/Pages/Mapper/Administration/Map/RemoveAccess.razor b/src/WHMapper/Pages/Mapper/Administration/Map/RemoveAccess.razor new file mode 100644 index 00000000..5de82905 --- /dev/null +++ b/src/WHMapper/Pages/Mapper/Administration/Map/RemoveAccess.razor @@ -0,0 +1,17 @@ + + + @if (MapId > 0) + { + @MSG_DELETE_ACCESS + } + else + { + @MSG_DELETE_ACCESSES + } + + + Cancel + Delete Access + + + diff --git a/src/WHMapper/Pages/Mapper/CustomDragMovablesBehavior.cs b/src/WHMapper/Pages/Mapper/CustomDragMovablesBehavior.cs index 0bb2c730..0dab2e01 100644 --- a/src/WHMapper/Pages/Mapper/CustomDragMovablesBehavior.cs +++ b/src/WHMapper/Pages/Mapper/CustomDragMovablesBehavior.cs @@ -1,8 +1,6 @@ using Blazor.Diagrams.Core.Geometry; using Blazor.Diagrams.Core.Models.Base; using Blazor.Diagrams.Core.Events; -using System; -using System.Collections.Generic; using Blazor.Diagrams.Core.Models; using Blazor.Diagrams.Core; diff --git a/src/WHMapper/Pages/Mapper/CustomNode/EveSystemLink.cs b/src/WHMapper/Pages/Mapper/CustomNode/EveSystemLink.cs index 7db5df23..387ad330 100644 --- a/src/WHMapper/Pages/Mapper/CustomNode/EveSystemLink.cs +++ b/src/WHMapper/Pages/Mapper/CustomNode/EveSystemLink.cs @@ -1,13 +1,4 @@ -using System; -using System.Reflection.Emit; -using System.Xml.Linq; -using Blazor.Diagrams; -using Blazor.Diagrams.Core.Geometry; -using Blazor.Diagrams.Core.Models; -using Blazor.Diagrams.Core.Models.Base; -using Blazor.Diagrams.Extensions; -using Microsoft.AspNetCore.Components; -using Microsoft.AspNetCore.Components.Web; +using Microsoft.AspNetCore.Components; using WHMapper.Models.Custom.Node; using WHMapper.Services.WHColor; diff --git a/src/WHMapper/Pages/Mapper/CustomNode/EveSystemNode.cs b/src/WHMapper/Pages/Mapper/CustomNode/EveSystemNode.cs index b1a96f92..1de7e30c 100644 --- a/src/WHMapper/Pages/Mapper/CustomNode/EveSystemNode.cs +++ b/src/WHMapper/Pages/Mapper/CustomNode/EveSystemNode.cs @@ -1,20 +1,6 @@ -using System.Reflection.Emit; -using System.Xml.Linq; -using Blazor.Diagrams.Core.Models; -using Microsoft.AspNetCore.Components; -using Microsoft.AspNetCore.Components.Web; -using Microsoft.AspNetCore.SignalR.Client; -using Microsoft.Extensions.Logging; -using MudBlazor; +using Microsoft.AspNetCore.Components; using WHMapper.Models.Custom.Node; -using WHMapper.Models.Db; -using WHMapper.Models.Db.Enums; -using WHMapper.Repositories.WHNotes; -using WHMapper.Repositories.WHSystems; -using WHMapper.Services.EveAPI; -using WHMapper.Services.SDE; using WHMapper.Services.WHColor; -using static MudBlazor.CategoryTypes; using ComponentBase = Microsoft.AspNetCore.Components.ComponentBase; namespace WHMapper.Pages.Mapper.CustomNode diff --git a/src/WHMapper/Pages/Mapper/CustomNode/EveSystemNode.razor b/src/WHMapper/Pages/Mapper/CustomNode/EveSystemNode.razor index 2f24bbdf..44853610 100644 --- a/src/WHMapper/Pages/Mapper/CustomNode/EveSystemNode.razor +++ b/src/WHMapper/Pages/Mapper/CustomNode/EveSystemNode.razor @@ -16,13 +16,13 @@ @if (Locked) { - + } @if (Node != null && Node.Effect != WHMapper.Models.DTO.EveMapper.Enums.WHEffect.None) { - + @@ -44,7 +44,7 @@
@if (Node != null && Node.ConnectedUsers != null && Node.ConnectedUsers.FirstOrDefault() != null) { - + diff --git a/src/WHMapper/Pages/Mapper/LinkInfos/Overview.cs b/src/WHMapper/Pages/Mapper/LinkInfos/Overview.cs index 0d1fc154..c5f41ea0 100644 --- a/src/WHMapper/Pages/Mapper/LinkInfos/Overview.cs +++ b/src/WHMapper/Pages/Mapper/LinkInfos/Overview.cs @@ -1,12 +1,8 @@ -using System; -using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Components; -using Microsoft.EntityFrameworkCore.Diagnostics; -using MudBlazor; using WHMapper.Models.Custom.Node; using WHMapper.Models.Db; using WHMapper.Repositories.WHSystemLinks; -using WHMapper.Services.EveAPI; using WHMapper.Services.EveMapper; using WHMapper.Services.WHColor; diff --git a/src/WHMapper/Pages/Mapper/Map/Overview.cs b/src/WHMapper/Pages/Mapper/Map/Overview.cs new file mode 100644 index 00000000..f929f12d --- /dev/null +++ b/src/WHMapper/Pages/Mapper/Map/Overview.cs @@ -0,0 +1,1714 @@ +using Blazor.Diagrams; +using Blazor.Diagrams.Core.Behaviors; +using BlazorContextMenu; +using Microsoft.AspNetCore.Components; +using Microsoft.EntityFrameworkCore.Infrastructure.Internal; +using MudBlazor; +using WHMapper.Models.Custom.Node; +using WHMapper.Models.Db; +using WHMapper.Models.Db.Enums; +using WHMapper.Models.DTO.EveAPI.Location; +using WHMapper.Models.DTO.EveMapper.Enums; +using WHMapper.Models.DTO.EveMapper.EveEntity; +using WHMapper.Pages.Mapper.CustomNode; +using WHMapper.Repositories.WHJumpLogs; +using WHMapper.Repositories.WHMaps; +using WHMapper.Repositories.WHNotes; +using WHMapper.Repositories.WHSystemLinks; +using WHMapper.Repositories.WHSystems; +using WHMapper.Services.EveAPI; +using WHMapper.Services.EveMapper; +using WHMapper.Services.EveOnlineUserInfosProvider; +using WHMapper.Pages.Mapper.Search; +using Microsoft.AspNetCore.Authorization; + +namespace WHMapper.Pages.Mapper.Map; + +public partial class Overview : ComponentBase,IAsyncDisposable +{ + private const float EPSILON = 0.0001f; // or some other small value + private BlazorDiagram _blazorDiagram = null!; + private int? _selectedWHMapId = null; + + private EveSystemNodeModel? _selectedSystemNode =null; + private EveSystemNodeModel? SelectedSystemNode + { + get => _selectedSystemNode; + set + { + if (_selectedSystemNode != value) + { + _selectedSystemNode = value; + StateHasChanged(); + } + } + } + + private EveSystemLinkModel? _selectedSystemLink =null; + private EveSystemLinkModel? SelectedSystemLink + { + get => _selectedSystemLink; + set + { + if (_selectedSystemLink != value) + { + _selectedSystemLink = value; + StateHasChanged(); + } + } + } + + private ICollection? _selectedSystemNodes = null; + private ICollection? _selectedSystemLinks = null; + private readonly SemaphoreSlim _semaphoreSlim = new SemaphoreSlim(1, 1); + + private SystemEntity? _currentSolarSystem = null!; + private Ship? _currentShip = null!; + private ShipEntity? _currentShipInfos = null!; + + private string _userName = string.Empty; + private int _characterId = 0; + + [Inject] + private ILogger Logger { get; set; } = null!; + + [Inject] + private IDialogService DialogService { get; set; } = null!; + + [Inject] + private ISnackbar Snackbar { get; set; } = null!; + + [Inject] + private IEveAPIServices EveServices { get; set; } = null!; + + [Inject] + private IEveMapperTracker TrackerServices { get; set; } = null!; + + [Inject] + private IEveMapperHelper MapperServices { get; set; } = null!; + + [Inject] + private IEveMapperRealTimeService EveMapperRealTime { get; set; } = null!; + + [Inject] + IEveUserInfosServices UserInfos { get; set; } = null!; + + #region Repositories + [Inject] + IWHMapRepository DbWHMaps { get; set; } = null!; + + [Inject] + IWHSystemRepository DbWHSystems { get; set; } = null!; + + [Inject] + IWHSystemLinkRepository DbWHSystemLinks { get; set; } = null!; + + [Inject] + IWHJumpLogRepository DbWHJumpLogs { get; set; } = null!; + + + [Inject] + IWHNoteRepository DbNotes { get; set; } = null!; + #endregion + + [Parameter] + public int? MapId { get; set; } = null!; + + + protected override async Task OnInitializedAsync() + { + _userName = await UserInfos.GetUserName(); + _characterId = await UserInfos.GetCharactedID(); + + if(!await InitDiagram()) + { + Snackbar?.Add("Map Initialization error", Severity.Error); + } + + await base.OnInitializedAsync(); + } + + + protected override async Task OnParametersSetAsync() + { + if(MapId.HasValue && (!_selectedWHMapId.HasValue || _selectedWHMapId.Value!=MapId.Value)) + { + await EveMapperRealTime.NotifyUserOnMapConnected(MapId.Value); + if(await Restore(MapId.Value)) + { + TrackerServices.SystemChanged += OnSystemChanged; + TrackerServices.ShipChanged += OnShipChanged; + + + EveMapperRealTime.UserDisconnected += OnUserDisconnected; + EveMapperRealTime.UserOnMapConnected += OnUserOnMapConnected; + EveMapperRealTime.UserOnMapDisconnected += OnUserOnMapDisconnected; + + EveMapperRealTime.UserPosition += OnUserPositionChanged; + + EveMapperRealTime.WormholeAdded += OnWormholeAdded; + EveMapperRealTime.WormholeRemoved += OnWormholeRemoved; + EveMapperRealTime.WormholeMoved += OnWormholeMoved; + EveMapperRealTime.WormholeLockChanged += OnWormholeLockChanged; + EveMapperRealTime.WormholeSystemStatusChanged += OnWormholeSystemStatusChanged; + EveMapperRealTime.WormholeNameExtensionChanged += OnWormholeNameExtensionChanged; + + EveMapperRealTime.LinkAdded += OnLinkAdded; + EveMapperRealTime.LinkRemoved += OnLinkRemoved; + EveMapperRealTime.LinkChanged += OnLinkChanged; + + + IDictionary?> usersPosition = await EveMapperRealTime.GetConnectedUsersPosition(); + try + { + await Parallel.ForEachAsync(usersPosition, async (item, cancellationToken) => + { + if (item.Value.HasValue && item.Value.Value.Key == MapId.Value) + { + EveSystemNodeModel? systemToAddUser = (EveSystemNodeModel?)_blazorDiagram?.Nodes?.FirstOrDefault(x => ((EveSystemNodeModel)x).IdWH == item.Value.Value.Value); + + if (systemToAddUser != null) + { + await systemToAddUser.AddConnectedUser(item.Key); + systemToAddUser.Refresh(); + } + } + }); + } + catch (Exception ex) + { + Logger.LogError(ex, "On NotifyUserPosition error"); + } + + + await TrackerServices.StartTracking(); + await InitBlazorDiagramEvents(); + } + else + { + Snackbar?.Add("Map Restore error", Severity.Error); + } + + } + await base.OnParametersSetAsync(); + } + + public async ValueTask DisposeAsync() + { + if(TrackerServices!=null) + { + await TrackerServices.StopTracking(); + TrackerServices.SystemChanged-=OnSystemChanged; + TrackerServices.ShipChanged-=OnShipChanged; + + } + + if(EveMapperRealTime!=null) + { + EveMapperRealTime.UserDisconnected -= OnUserDisconnected; + EveMapperRealTime.UserOnMapConnected -= OnUserOnMapConnected; + EveMapperRealTime.UserOnMapDisconnected -= OnUserOnMapDisconnected; + + EveMapperRealTime.UserPosition -= OnUserPositionChanged; + EveMapperRealTime.WormholeAdded -= OnWormholeAdded; + EveMapperRealTime.WormholeRemoved -= OnWormholeRemoved; + EveMapperRealTime.WormholeMoved -= OnWormholeMoved; + EveMapperRealTime.WormholeLockChanged -= OnWormholeLockChanged; + EveMapperRealTime.WormholeSystemStatusChanged -= OnWormholeSystemStatusChanged; + EveMapperRealTime.WormholeNameExtensionChanged -= OnWormholeNameExtensionChanged; + EveMapperRealTime.LinkAdded -= OnLinkAdded; + EveMapperRealTime.LinkRemoved -= OnLinkRemoved; + EveMapperRealTime.LinkChanged -= OnLinkChanged; + + if (MapId.HasValue && EveMapperRealTime.IsConnected) + { + + await EveMapperRealTime.NotifyUserOnMapDisconnected(MapId.Value); + } + } + await ClearDiagram(); + GC.SuppressFinalize(this); + } + + private async Task Restore(int mapId) + { + try + { + WHMap? selectedWHMap = null; + Logger.LogInformation("Beginning Restore Map"); + + if (DbWHMaps == null) + { + Logger.LogError("DbWHMaps is null"); + return false; + } + + selectedWHMap = await DbWHMaps.GetById(mapId); + + + if(selectedWHMap != null) + { + await ClearDiagram(); + await InitializeSystemNodes(selectedWHMap); + await InitializeSystemLinks(selectedWHMap); + } + + Logger.LogInformation("Restore Mapper Success"); + return true; + } + catch (Exception ex) + { + Logger.LogError(ex, "Mapper Restore"); + return false; + } + } + + private Task ClearDiagram() + { + if (_blazorDiagram != null) + { + _blazorDiagram.Links.Clear(); + _blazorDiagram.Nodes.Clear(); + } + + return Task.CompletedTask; + } + + private Task InitDiagram() + { + try + { + Logger.LogInformation("Start Init Diagram"); + if (_blazorDiagram == null) + { + + _blazorDiagram = new BlazorDiagram(); + _blazorDiagram.UnregisterBehavior(); + _blazorDiagram.RegisterBehavior(new CustomDragMovablesBehavior(_blazorDiagram)); + + _blazorDiagram.Options.Zoom.Enabled = true; + _blazorDiagram.Options.Zoom.Inverse = false; + _blazorDiagram.Options.Links.EnableSnapping = false; + _blazorDiagram.Options.AllowMultiSelection = true; + _blazorDiagram.RegisterComponent(); + _blazorDiagram.RegisterComponent(); + } + else + { + Logger.LogWarning("Diagram already initialized, clear nodes and links"); + _blazorDiagram.Nodes.Clear(); + _blazorDiagram.Links.Clear(); + } + + Logger.LogInformation("Init Diagram Success"); + return Task.FromResult(true); + } + catch(Exception ex) + { + Logger.LogError(ex, "Init Diagram Error"); + return Task.FromResult(false); + } + } + private Task InitBlazorDiagramEvents() + { + if (_blazorDiagram == null) + { + Logger.LogError("Blazor Diagram is null,Blaor Diagram Events not initialized"); + throw new NullReferenceException("Blazor Diagram is null"); + } + + _blazorDiagram.SelectionChanged += async (item) => await OnDiagramSelectionChanged(item); + _blazorDiagram.KeyDown += async (kbevent) => await OnDiagramKeyDown(kbevent); + _blazorDiagram.PointerUp += async (item, pointerEvent) => await OnDiagramPointerUp(item, pointerEvent); + + return Task.CompletedTask; + } + + private async Task InitializeSystemNodes(WHMap? selectedWHMap) + { + if (selectedWHMap != null && selectedWHMap.WHSystems != null) + { + foreach (var dbWHSys in selectedWHMap.WHSystems) + { + EveSystemNodeModel whSysNode = await MapperServices.DefineEveSystemNodeModel(dbWHSys); + whSysNode.OnLocked += OnWHSystemNodeLocked; + whSysNode.OnSystemStatusChanged += OnWHSystemStatusChange; + _blazorDiagram.Nodes.Add(whSysNode); + } + } + } + + private async Task InitializeSystemLinks(WHMap? selectedWHMap) + { + if (selectedWHMap?.WHSystemLinks == null || selectedWHMap.WHSystemLinks.Count == 0) + { + return; + } + + foreach (var dbWHSysLink in selectedWHMap.WHSystemLinks) + { + var srcNode = await GetSystemNode(dbWHSysLink.IdWHSystemFrom); + var targetNode = await GetSystemNode(dbWHSysLink.IdWHSystemTo); + + if (srcNode != null && targetNode != null) + { + _blazorDiagram.Links.Add(new EveSystemLinkModel(dbWHSysLink, srcNode, targetNode)); + } + else + { + Logger.LogWarning("Bad Link, srcNode or Targetnode is null, Auto remove"); + await DbWHSystemLinks.DeleteById(dbWHSysLink.Id); + } + } + } + + #region Diagram Events + + #region Diagram Selection + private async Task OnDiagramSelectionChanged(Blazor.Diagrams.Core.Models.Base.SelectableModel? item) + { + await _semaphoreSlim.WaitAsync(); + try + { + await InvokeAsync(() => + { + if (item == null) + return; + + var selectedModels = _blazorDiagram.GetSelectedModels(); + _selectedSystemNodes = selectedModels.OfType().ToList(); + _selectedSystemLinks = selectedModels.OfType().ToList(); + + if (item is EveSystemNodeModel node) + { + HandleNodeSelection(node); + } + else if (item is EveSystemLinkModel link) + { + HandleLinkSelection(link); + } + }); + } + catch (Exception ex) + { + Logger.LogError(ex, "On diagram selection changed error"); + } + finally + { + _semaphoreSlim.Release(); + } + } + + private void HandleNodeSelection(EveSystemNodeModel node) + { + SelectedSystemLink = null; + + if (node.Selected) + { + SelectedSystemNode = node; + _blazorDiagram.SendToFront(SelectedSystemNode); + } + else + { + SelectedSystemNode = null; + } + } + + private void HandleLinkSelection(EveSystemLinkModel link) + { + SelectedSystemNode = null; + + if (link.Selected) + { + SelectedSystemLink = link; + _blazorDiagram.SendToFront(SelectedSystemLink); + } + else + { + SelectedSystemLink = null; + } + + // StateHasChanged(); + } + #endregion + + #region Diagram Keyboard Events + private async Task OnDiagramKeyDown(Blazor.Diagrams.Core.Events.KeyboardEventArgs eventArgs) +{ + await _semaphoreSlim.WaitAsync(); + try + { + if (await HandleLinkSystemKey(eventArgs) || + await HandleIncrementOrDecrementExtensionKey(eventArgs) || + await HandleDeleteKey(eventArgs)) + { + return; + } + } + catch (Exception ex) + { + Logger.LogError(ex, "OnDiagramKeyDown error"); + } + finally + { + _semaphoreSlim.Release(); + } +} + + #region Diagram Keyboard Pressed + private async Task HandleLinkSystemKey(Blazor.Diagrams.Core.Events.KeyboardEventArgs eventArgs) + { + if (eventArgs.Code == "KeyL" && MapId.HasValue && _selectedSystemNodes != null && _selectedSystemNodes.Count == 2) + { + if (await IsLinkExist(_selectedSystemNodes.ElementAt(0), _selectedSystemNodes.ElementAt(1))) + { + Snackbar.Add("Nodes are already linked", Severity.Warning); + return false; + } + else + { + if (!await AddSystemNodeLink(MapId.Value, _selectedSystemNodes.ElementAt(0), _selectedSystemNodes.ElementAt(1), true)) + { + Logger.LogError("Add Wormhole Link db error"); + Snackbar.Add("Add Wormhole Link db error", Severity.Error); + return false; + } + return true; + } + } + return false; + } + + private async Task HandleIncrementOrDecrementExtensionKey(Blazor.Diagrams.Core.Events.KeyboardEventArgs eventArgs) + { + if ((eventArgs.Code == "NumpadAdd" || eventArgs.Code == "NumpadSubtract" || eventArgs.Code == "ArrowUp" || eventArgs.Code == "ArrowDown") && MapId.HasValue && SelectedSystemNode != null) + { + bool res = eventArgs.Code == "NumpadAdd" || eventArgs.Code == "ArrowUp" + ? await IncrementOrDecrementNodeExtensionNameOnMap(MapId.Value, SelectedSystemNode, true) + : await IncrementOrDecrementNodeExtensionNameOnMap(MapId.Value, SelectedSystemNode, false); + + if (res) + { + SelectedSystemNode.Refresh(); + return true; + } + else + { + Snackbar?.Add("Loading wormhole node db error", Severity.Error); + return false; + } + } + return false; + } + + private async Task HandleDeleteKey(Blazor.Diagrams.Core.Events.KeyboardEventArgs eventArgs) + { + if (eventArgs.Code == "Delete") + { + if (!MapId.HasValue) + { + Logger.LogError("OnDiagramKeyDown, no map selected to delete node or link"); + Snackbar?.Add("No map selected to delete node or link", Severity.Error); + return false; + } + + if (SelectedSystemNode != null && _selectedSystemNodes != null && _selectedSystemNodes.Count > 0) + { + await HandleNodeDeletion(); + return true; + } + + if (SelectedSystemLink != null && _selectedSystemLinks != null && _selectedSystemLinks.Count > 0) + { + await HandleLinkDeletion(); + return true; + } + } + return false; + } + + private async Task HandleNodeDeletion() + { + if(_selectedSystemNodes==null || !_selectedSystemNodes.Any() || !MapId.HasValue) + { + return; + } + + await TrackerServices.StopTracking(); + _currentSolarSystem = null; + foreach (var node in _selectedSystemNodes) + { + if (node.Locked) + { + Snackbar?.Add($"{node.Name} wormhole is locked. You can't remove it.", Severity.Warning); + } + else + { + if (!await DeletedNodeOnMap(MapId.Value, node)) + Snackbar?.Add("Remove wormhole node db error", Severity.Error); + } + } + SelectedSystemNode = null; + await TrackerServices.StartTracking(); + } + + private async Task HandleLinkDeletion() + { + if(_selectedSystemLinks==null || !_selectedSystemLinks.Any() || !MapId.HasValue) + return; + + await TrackerServices.StopTracking(); + foreach (var link in _selectedSystemLinks) + { + if (!await DeletedLinkOnMap(MapId.Value, link)) + Snackbar?.Add("Remove wormhole link db error", Severity.Error); + } + _selectedSystemLink = null; + await TrackerServices.StartTracking(); + } + #endregion + + #endregion + + #region Diagram Mouse Events + private async Task OnDiagramPointerUp(Blazor.Diagrams.Core.Models.Base.Model? item, Blazor.Diagrams.Core.Events.PointerEventArgs eventArgs) + { + if (item == null || item.GetType() != typeof(EveSystemNodeModel)) + return; + + await _semaphoreSlim.WaitAsync(); + try + { + var node = (EveSystemNodeModel)item; + var wh = await DbWHSystems.GetById(node.IdWH); + if (wh != null) + { + await UpdateNodePositionIfNeeded(MapId,node, wh); + } + else + { + Logger.LogError("On Mouse pointer up, unable to find moved wormhole node db error"); + Snackbar?.Add("Unable to find moved wormhole node db error", Severity.Error); + } + } + catch (Exception ex) + { + Logger.LogError(ex, "Mouse Pointer Up"); + } + finally + { + _semaphoreSlim.Release(); + } + } + + private async Task UpdateNodePositionIfNeeded(int? mapId,EveSystemNodeModel node, WHSystem wh) + { + if(!mapId.HasValue) + { + Logger.LogError("UpdateNodePositionIfNeeded mapId is null"); + return; + } + + if (Math.Abs(wh.PosX - node.Position.X) >= EPSILON || Math.Abs(wh.PosY - node.Position.Y) >= EPSILON) + { + wh.PosX = node.Position.X; + wh.PosY = node.Position.Y; + + if (await DbWHSystems.Update(node.IdWH, wh) == null) + { + Snackbar?.Add("Update wormhole node position db error", Severity.Error); + } + + await EveMapperRealTime.NotifyWormholeMoved(mapId.Value, wh.Id, wh.PosX, wh.PosY); + } + } + #endregion + + #endregion + + #region WHSystemNode Events + private void OnWHSystemNodeLocked(EveSystemNodeModel whNodeModel) + { + if (whNodeModel != null) + { + Task.Run(async () => await EveMapperRealTime.NotifyWormholeLockChanged(whNodeModel.IdWHMap, whNodeModel.IdWH, whNodeModel.Locked)); + } + } + + private void OnWHSystemStatusChange(EveSystemNodeModel whNodeModel) + { + if (whNodeModel != null) + { + Task.Run(async ()=>await EveMapperRealTime.NotifyWormholeSystemStatusChanged(whNodeModel.IdWHMap, whNodeModel.IdWH, whNodeModel.SystemStatus)); + } + } + #endregion + + #region Diagram Actions + + + private Task GetSystemNode(int id) + { + if (_blazorDiagram == null || _blazorDiagram.Nodes == null || _blazorDiagram.Nodes.Count == 0) + { + Logger.LogWarning("GetNodeById, no node in diagram"); + return Task.FromResult(null as EveSystemNodeModel); + } + var res = _blazorDiagram.Nodes + .FirstOrDefault(x => ((EveSystemNodeModel)x).IdWH == id) as EveSystemNodeModel + ?? null; + + return Task.FromResult(res); + } + + private Task GetNodeBySolarSystemId(int solarSystemId) + { + if (_blazorDiagram == null || _blazorDiagram.Nodes == null || _blazorDiagram.Nodes.Count == 0) + { + Logger.LogWarning("GetNodeBySolarSystemId, no node in diagram"); + return Task.FromResult(null as EveSystemNodeModel); + } + var res = _blazorDiagram.Nodes + .FirstOrDefault(x => ((EveSystemNodeModel)x).SolarSystemId == solarSystemId) as EveSystemNodeModel + ?? null; + + return Task.FromResult(res); + } + + private Task GetLink(EveSystemNodeModel src, EveSystemNodeModel target) + { + try + { + if (src == null || target == null) + { + Logger.LogError("LinkExist src or target is null"); + return Task.FromResult(null as EveSystemLinkModel); + } + + var whLink = _blazorDiagram.Links.FirstOrDefault(x => + ((((EveSystemNodeModel)x.Source!.Model!).IdWH == src.IdWH) && (((EveSystemNodeModel)x.Target!.Model!).IdWH == target.IdWH)) + || + ((((EveSystemNodeModel)x.Source!.Model!).IdWH == target.IdWH) && (((EveSystemNodeModel)x.Target!.Model!).IdWH == src.IdWH))); + + return Task.FromResult(whLink as EveSystemLinkModel); + } + catch (Exception ex) + { + Logger.LogError(ex, "Get Link error"); + return Task.FromResult(null as EveSystemLinkModel); + } + } + + private async Task IsLinkExist(EveSystemNodeModel src, EveSystemNodeModel target) + { + try + { + var link = await GetLink(src, target); + + if (link == null) + return false; + else + return true; + } + catch (Exception ex) + { + Logger.LogError(ex, "Is Link Exist error"); + return false; + } + + } + + private async Task AddSystemNode(int? mapId,SystemEntity node,double nodePositionX=0,double nodePositionY=0) + { + return await AddSystemNode(mapId, null, node,nodePositionX,nodePositionY,true); + } + + private async Task AddSystemNode(int? mapId,SystemEntity? src,SystemEntity target,double nodePositionX=0,double nodePositionY=0,bool isManual=false) + { + EveSystemNodeModel? previousSystemNode = null; + WHSystem? newWHSystem= null; + double defaultNewSystemPosX = nodePositionX; + double defaultNewSystemPosY = nodePositionY; + char extension; + int nbSameWHClassLink =0; + + try + { + if(!mapId.HasValue) + { + Logger.LogError("AddSystemNode mapId is null"); + return false; + } + + //determine position on map. depends of previous system , todo refactor + if (src != null) + { + previousSystemNode = await GetNodeBySolarSystemId(src.Id); + + if(previousSystemNode!=null) + { + defaultNewSystemPosX = previousSystemNode.Position!.X + previousSystemNode.Size!.Width + 10; + defaultNewSystemPosY = previousSystemNode.Position!.Y + previousSystemNode!.Size!.Height + 10; + } + else + { + defaultNewSystemPosX=10; + defaultNewSystemPosY=10; + } + } + + //determine if source have same system link and get next unique ident + if(src != null && await MapperServices.IsRouteViaWH(src, target)) //check if HS/LS/NS to HS/LS/NS via WH not gate + { + + //get whClass an determine if another connection to another wh with same class exist from previous system. Increment extension value in that case + EveSystemType whClass = await MapperServices.GetWHClass(target); + var sameWHClassWHList = _blazorDiagram?.Links?.Where(x => ((EveSystemNodeModel)(x.Target!.Model!)).SystemType == whClass && ((EveSystemNodeModel)x.Source!.Model!).SolarSystemId == src.Id); + + if(sameWHClassWHList!=null) + nbSameWHClassLink = sameWHClassWHList.Count(); + else + nbSameWHClassLink=0; + + if (nbSameWHClassLink > 0) + { + extension = (Char)(Convert.ToUInt16('A') + nbSameWHClassLink); + newWHSystem = await DbWHSystems.Create(new WHSystem(mapId.Value, target.Id, target.Name, extension, target.SecurityStatus, defaultNewSystemPosX, defaultNewSystemPosY)); + } + else + newWHSystem = await DbWHSystems.Create(new WHSystem(mapId.Value, target.Id, target.Name, target.SecurityStatus, defaultNewSystemPosX, defaultNewSystemPosY)); + + } + else + newWHSystem = await DbWHSystems.Create(new WHSystem(mapId.Value,target.Id,target.Name, target.SecurityStatus, defaultNewSystemPosX, defaultNewSystemPosY)); + + if (newWHSystem!=null) + { + var newSystemNode = await MapperServices.DefineEveSystemNodeModel(newWHSystem); + newSystemNode.OnLocked += OnWHSystemNodeLocked; + newSystemNode.OnSystemStatusChanged += OnWHSystemStatusChange; + + if(!isManual) + { + await newSystemNode.AddConnectedUser(_userName); + } + + _blazorDiagram?.Nodes?.Add(newSystemNode); + await EveMapperRealTime.NotifyWormoleAdded(mapId.Value, newWHSystem.Id); + + + if (previousSystemNode != null && !isManual) + { + //remove ConnectedUser on previous system + await previousSystemNode.RemoveConnectedUser(_userName); + previousSystemNode.Refresh(); + } + + _blazorDiagram?.SelectModel(newSystemNode, true); + return true; + } + else + { + Logger.LogError("AddSystemNode db error"); + return false; + } + + + } + catch(Exception ex) + { + Logger.LogError(ex, "AddSystemNode error"); + return false; + } + } + private async Task AddSystemNodeLink(int? mapId, SystemEntity src, SystemEntity target) + { + if (_blazorDiagram == null  || !mapId.HasValue || src == null || target == null) + { + Logger.LogError("CreateLink map or src or target is null"); + return false; + } + + EveSystemNodeModel? srcNode = await GetNodeBySolarSystemId(src.Id); + EveSystemNodeModel? targetNode = await GetNodeBySolarSystemId(target.Id); + + return await AddSystemNodeLink(mapId.Value,srcNode,targetNode); + } + private async Task AddSystemNodeLink(int mapId, EveSystemNodeModel? srcNode, EveSystemNodeModel? targetNode,bool isManual=false) + { + try + { + if(srcNode==null || targetNode ==null) + { + Logger.LogError("CreateLink src or target node is null"); + return false; + } + + if(srcNode.SolarSystemId==targetNode.SolarSystemId) + { + Logger.LogError("CreateLink src and target node are the same"); + return false; + } + + var newLink = await DbWHSystemLinks.Create(new WHSystemLink(mapId, srcNode.IdWH, targetNode.IdWH)); + + if (newLink != null) + { + await AddSystemNodeLinkLog(newLink,isManual); + + _blazorDiagram?.Links?.Add(new EveSystemLinkModel(newLink, srcNode, targetNode)); + await EveMapperRealTime.NotifyLinkAdded(mapId, newLink.Id); + return true; + } + return false; + } + catch(Exception ex) + { + Logger.LogError(ex, "AddSystemNodeLink error"); + return false; + } + } + private async Task AddSystemNodeLinkLog(int whSystemLinkID,bool isManual=false) + { + if(_currentShip==null || _currentShipInfos==null) + { + Logger.LogError("AddSystemNodeLinkLog currentShip or currentShipInfos is null"); + return false; + } + WHJumpLog? jumpLog = null; + + if(isManual) + jumpLog = await DbWHJumpLogs.Create(new WHJumpLog(whSystemLinkID,_characterId)); + else + jumpLog = await DbWHJumpLogs.Create(new WHJumpLog(whSystemLinkID,_characterId,_currentShip.ShipTypeId,_currentShip.ShipItemId,_currentShipInfos.Mass)); + + if(jumpLog==null) + { + Logger.LogError("AddSystemNodeLinkLog jumpLog is null"); + return false; + } + + return true; + + } + private async Task AddSystemNodeLinkLog(WHSystemLink? link,bool isManual=false) + { + if(link==null) + { + Logger.LogError("AddSystemNodeLinkLog link is null"); + return false; + } + + return await AddSystemNodeLinkLog(link.Id,isManual); + } + private async Task DeletedNodeOnMap(int? mapId, EveSystemNodeModel node) + { + try + { + if (!mapId.HasValue || node == null) + { + Logger.LogError("DeletedNodeOnMap map or node is null"); + return false; + } + + if (await DbWHSystems.DeleteById(node.IdWH))//db link will be automatically delete via db foreignkey cascade + { + await EveMapperRealTime.NotifyWormholeRemoved(mapId.Value, node.IdWH); + return true; + } + + return false; + } + catch (Exception ex) + { + Logger.LogError(ex, "Deleted node on map error"); + return false; + } + } + private async Task DeletedLinkOnMap(int? mapId, EveSystemLinkModel link) + { + try + { + if (!mapId.HasValue || link == null) + { + Logger.LogError("DeletedLinkOnMap map or link is null"); + return false; + } + + if(await DbWHSystemLinks.DeleteById(link.Id)) + { + await EveMapperRealTime.NotifyLinkRemoved(mapId.Value, link.Id); + return true; + } + + return false; + } + catch (Exception ex) + { + Logger.LogError(ex, "Deleted link on map error"); + return false; + } + + } + private async Task IncrementOrDecrementNodeExtensionNameOnMap(int? mapId, EveSystemNodeModel node,bool increment) + { + try + { + if (!mapId.HasValue || node == null) + { + Logger.LogError("IncrementOrDecrementNodeExtensionNameOnMap map or node is null"); + return false; + } + + var wh = await DbWHSystems.GetById(node.IdWH); + if (wh != null) + { + if (increment) + node.IncrementNameExtension(); + else + node.DecrementNameExtension(); + + if (node.NameExtension == null) + wh.NameExtension = 0; + else + wh.NameExtension = ((byte)((node.NameExtension.ToCharArray())[0])); + + wh = await DbWHSystems.Update(wh.Id, wh); + + + if (wh != null) + { + await EveMapperRealTime.NotifyWormholeNameExtensionChanged(mapId.Value, wh.Id, increment); + return true; + } + } + + return false; + + } + catch (Exception ex) + { + Logger.LogError(ex, "Increment Or Decrement node extension name error"); + return false; + } + } + + #endregion + + #region Tracker Events + private Task OnShipChanged(Ship ship,ShipEntity shipInfos) + { + _currentShip=ship; + _currentShipInfos=shipInfos; + + return Task.CompletedTask; + } + private async Task OnSystemChanged(SystemEntity? targetSoloarSystem) + { + EveSystemNodeModel? srcNode = null; + EveSystemNodeModel? targetNode = null; + + if(_blazorDiagram==null) + { + Logger.LogError("Error OnSystemChanged, blazorDiagram is nullable"); + throw new NullReferenceException("Blazor Diagram is null"); + } + + if(MapId.HasValue==false) + { + Logger.LogError("Error OnSystemChanged, selectedWHMap is nullable"); + throw new NullReferenceException("Selected WH Map is null"); + } + + if(targetSoloarSystem==null) + { + Logger.LogError("Error OnSystemChanged, targetSoloarSystem is nullable"); + throw new NullReferenceException("Target Solar System is null"); + } + + if(_currentSolarSystem!=null && _currentSolarSystem.Id==targetSoloarSystem.Id) + { + Logger.LogWarning("On System Changed, target system is the same as current system"); + return; + } + + await _semaphoreSlim.WaitAsync(); + try + { + + if(_currentSolarSystem!=null) + { + srcNode=await GetNodeBySolarSystemId(_currentSolarSystem.Id); + } + targetNode = await GetNodeBySolarSystemId(targetSoloarSystem.Id); + + + if (targetNode== null)//System is not added + { + if(await AddSystemNode(MapId.Value,_currentSolarSystem,targetSoloarSystem))//add system node if system is not added + { + if (_currentSolarSystem != null) + { + if(!await AddSystemNodeLink(MapId.Value, _currentSolarSystem, targetSoloarSystem))//create if new target system added from src + { + Logger.LogError("Add Wormhole Link error"); + Snackbar?.Add("Add Wormhole Link error", Severity.Error); + } + else + { + targetNode = await GetNodeBySolarSystemId(targetSoloarSystem.Id); + } + } + + if(MapId.HasValue && targetNode!=null) + await EveMapperRealTime.NotifyUserPosition(this.MapId.Value, targetNode.IdWH); + } + else + { + Logger.LogError("Add System Node error"); + Snackbar?.Add("Add System Node error", Severity.Error); + } + } + else// tartget system already added + { + //check if link already exist, if not create if + if(srcNode!=null && !await IsLinkExist(srcNode,targetNode)) + { + if((_currentSolarSystem==null) || (!await AddSystemNodeLink(MapId.Value, _currentSolarSystem, targetSoloarSystem)))//create if new target system added from src + { + Logger.LogError("Add Wormhole Link error"); + Snackbar?.Add("Add Wormhole Link error", Severity.Error); + } + } + else//log jump + { + if(srcNode!=null && targetNode!=null) + { + var link = await GetLink(srcNode,targetNode); + + if(link!=null && !await AddSystemNodeLinkLog(link.Id)) + { + Logger.LogError("Add Wormhole Link Log error"); + Snackbar?.Add("Add Wormhole Link Log error", Severity.Error); + } + } + } + + + srcNode?.RemoveConnectedUser(_userName); + targetNode?.AddConnectedUser(_userName); + if(this.MapId.HasValue && targetNode!=null) + await EveMapperRealTime.NotifyUserPosition(this.MapId.Value, targetNode.IdWH); + + } + + _currentSolarSystem = targetSoloarSystem; + if(targetNode!=null) + _blazorDiagram?.SelectModel(targetNode, true); + } + catch (Exception ex) + { + Logger.LogError(ex, "On System Changed"); + } + finally + { + _semaphoreSlim.Release(); + } + } + + #endregion + + #region Menu Actions + + #region Selected Node Menu Actions + private async Task SetSelectedSystemDestinationWaypoint() + { + try + { + if(SelectedSystemNode==null) + { + Logger.LogError("Set system status error, no node selected"); + return false; + } + int solarSystemId = SelectedSystemNode.SolarSystemId; + if (solarSystemId>0) + { + await EveServices.UserInterfaceServices.SetWaypoint(solarSystemId, false, true); + return true; + + } + + return false; + } + catch (Exception ex) + { + Logger.LogError(ex, "Set destination waypoint error"); + return false; + } + } + + private async Task ToggleSystemLock() + { + try + { + if(SelectedSystemNode==null) + { + Logger.LogError("Set system status error, no node selected"); + return false; + } + + var whSystem = await DbWHSystems.GetById(SelectedSystemNode.IdWH); + if (whSystem != null && whSystem.Id==SelectedSystemNode.IdWH) + { + whSystem.Locked = !whSystem.Locked; + whSystem = await DbWHSystems.Update(whSystem.Id, whSystem); + if (whSystem == null) + { + Logger.LogError("Update lock system status error"); + return false; + } + SelectedSystemNode.Locked = whSystem.Locked; + SelectedSystemNode.Refresh(); + return true; + } + else + { + return false; + } + } + catch (Exception ex) + { + Logger.LogError(ex, "Toggle system lock error"); + return false; + } + + } + private async Task SetSelectedSystemStatus(WHSystemStatus systemStatus) + { + try + { + if(!MapId.HasValue) + { + Logger.LogError("Set system status error, no map selected"); + return false; + } + + + if(SelectedSystemNode==null) + { + Logger.LogError("Set system status error, no node selected"); + return false; + } + int solarSystemId = SelectedSystemNode.SolarSystemId; + if (solarSystemId>0) + { + var note = await DbNotes.Get(MapId.Value,solarSystemId); + + if(note == null) + { + note = await DbNotes.Create(new WHNote(MapId.Value, solarSystemId, systemStatus)); + } + else + { + note.SystemStatus = systemStatus; + note = await DbNotes.Update(note.Id, note); + } + + + if(note==null) + { + Logger.LogError("Could not update system status"); + return false; + } + + SelectedSystemNode.SystemStatus = systemStatus; + SelectedSystemNode.Refresh(); + return true; + } + else + { + Logger.LogError("Set system status error, no node selected"); + return false; + } + } + catch (Exception ex) + { + Logger.LogError(ex, "Set system status error"); + return false; + } + } + #endregion + private async Task ToggleSlectedSystemLinkEOL() + { + try + { + if (MapId.HasValue && SelectedSystemLink != null) + { + WHSystemLink? link = await DbWHSystemLinks.GetById(SelectedSystemLink.Id); + if (link != null) + { + link.IsEndOfLifeConnection = !link.IsEndOfLifeConnection; + link = await DbWHSystemLinks.Update(SelectedSystemLink.Id, link); + if(link!=null) + { + SelectedSystemLink.IsEoL = link.IsEndOfLifeConnection; + SelectedSystemLink.Refresh(); + await EveMapperRealTime.NotifyLinkChanged(MapId.Value, link.Id, link.IsEndOfLifeConnection, link.Size,link.MassStatus); + return true; + } + else + { + Logger.LogError("Toggle system link eol db error"); + return false; + } + } + else + { + return false; + } + } + else + { + return false; + } + } + catch(Exception ex) + { + Logger.LogError(ex, "Toggle system link eol error"); + return false; + } + } + + private async Task SetSelectedSystemLinkStatus(SystemLinkMassStatus massStatus) + { + try + { + if (MapId.HasValue && SelectedSystemLink != null) + { + WHSystemLink? link = await DbWHSystemLinks.GetById(SelectedSystemLink.Id); + if (link != null) + { + link.MassStatus = massStatus; + link = await DbWHSystemLinks.Update(SelectedSystemLink.Id, link); + if(link!=null) + { + SelectedSystemLink.MassStatus = link.MassStatus; + SelectedSystemLink.Refresh(); + await EveMapperRealTime.NotifyLinkChanged(MapId.Value, link.Id, link.IsEndOfLifeConnection, link.Size, link.MassStatus); + return true; + } + else + { + Logger.LogError("Set system link status db error"); + return false; + } + } + else + { + return false; + } + } + else + { + return false; + } + } + catch(Exception ex) + { + Logger.LogError(ex, "System link status error"); + return false; + } + } + + private async Task SetSelectedSystemLinkSize(SystemLinkSize size) + { + try + { + if (MapId.HasValue && SelectedSystemLink != null) + { + WHSystemLink? link = await DbWHSystemLinks.GetById(SelectedSystemLink.Id); + if (link != null) + { + link.Size = size; + link = await DbWHSystemLinks.Update(SelectedSystemLink.Id, link); + if(link!=null) + { + //update link size on diagram (refresh link + SelectedSystemLink.Size = link.Size; + SelectedSystemLink.Refresh(); + await EveMapperRealTime.NotifyLinkChanged(MapId.Value, link.Id, link.IsEndOfLifeConnection, link.Size, link.MassStatus); + + return true; + } + else + { + Logger.LogError("Set system link size db error"); + return false; + } + + } + } + + return false; + } + catch(Exception ex) + { + Logger.LogError(ex, "System link size error"); + return false; + } + } + + private async Task OpenSearchAndAddDialog(ItemClickEventArgs e) + { + DialogOptions disableBackdropClick = new DialogOptions() + { + BackdropClick=false, + Position = DialogPosition.Center, + MaxWidth = MaxWidth.Medium, + FullWidth = true + }; + var parameters = new DialogParameters(); + + var dialog = await DialogService.ShowAsync("Search and Add System Dialog", parameters, disableBackdropClick); + DialogResult? result = await dialog.Result; + + if (result != null && !result.Canceled && result.Data != null) + { + if (MapId.HasValue && result.Data!=null) + { + SystemEntity solarSystem = (SystemEntity)result.Data; + if(await AddSystemNode(MapId.Value,solarSystem,e.MouseEvent.ClientX,e.MouseEvent.ClientY)) + { + Snackbar?.Add(String.Format("{0} solar system successfully added",solarSystem.Name), Severity.Success); + } + else + { + Snackbar?.Add("Add solar system error", Severity.Error); + } + } + else + { + Logger.LogError("OpenSearchAndAddDialog, unable to find selected map to notify wormhole added"); + Snackbar?.Add("Unable to find selected map to notify wormhole added", Severity.Warning); + } + } + + return true; + + } + #endregion + + #region RealTime Events + + private Task OnUserOnMapConnected(string user, int mapId) + { + if (MapId.HasValue && MapId.Value == mapId) + { + Snackbar?.Add($"{user} are connected", Severity.Info); + } + return Task.CompletedTask; + } + + private async Task OnUserOnMapDisconnected(string user, int mapId) + { + if (MapId.HasValue && MapId.Value == mapId) + { + Snackbar?.Add($"{user} are disconnected", Severity.Info); + await OnUserDisconnected(user); + } + } + + private async Task OnUserDisconnected(string user) + { + try + { + EveSystemNodeModel? userSystem = (EveSystemNodeModel?)_blazorDiagram?.Nodes?.FirstOrDefault(x => ((EveSystemNodeModel)x)!.ConnectedUsers.Contains(user)); + if (userSystem != null) + { + await userSystem.RemoveConnectedUser(user); + userSystem.Refresh(); + } + } + catch (Exception ex) + { + Logger.LogError(ex, "On NotifyUserDisconnected error"); + } + } + + private async Task OnUserPositionChanged(string user, int mapId, int wormholeId) + { + try + { + if(this.MapId.HasValue && this.MapId.Value == mapId) + { + EveSystemNodeModel? userSystem = (EveSystemNodeModel?)_blazorDiagram?.Nodes?.FirstOrDefault(x => ((EveSystemNodeModel)x)!.ConnectedUsers.Contains(user)); + if (userSystem != null) + { + await userSystem.RemoveConnectedUser(user); + userSystem.Refresh(); + } + + EveSystemNodeModel? systemToAddUser = (EveSystemNodeModel?)_blazorDiagram?.Nodes?.FirstOrDefault(x => ((EveSystemNodeModel)x)!.IdWH == wormholeId); + if (systemToAddUser != null) + { + await systemToAddUser.AddConnectedUser(user); + systemToAddUser.Refresh(); + } + else + { + Logger.LogWarning("On NotifyUserPosition, unable to find system to add user"); + } + } + } + catch (Exception ex) + { + Logger.LogError(ex, "On NotifyUserPositionChanged error"); + } + } + + private async Task OnWormholeAdded(string user,int mapId, int whId) + { + try + { + if (MapId.HasValue && MapId.Value == mapId) + { + var wh = await DbWHSystems.GetById(whId); + if (wh != null) + { + var newSystemNode = await MapperServices.DefineEveSystemNodeModel(wh); + newSystemNode.OnLocked += OnWHSystemNodeLocked; + newSystemNode.OnSystemStatusChanged += OnWHSystemStatusChange; + _blazorDiagram?.Nodes?.Add(newSystemNode); + } + else + { + Logger.LogWarning("On NotifyWormholeAdded, unable to find added wormhole"); + } + } + } + catch (Exception ex) + { + Logger.LogError(ex, "On NotifyWormholeAdded error"); + } + } + private async Task OnWormholeRemoved(string user,int mapId, int whId) + { + try + { + if (MapId.HasValue && MapId.Value == mapId) + { + var node = await GetSystemNode(whId); + if (node != null) + { + _blazorDiagram?.Nodes?.Remove(node); + } + else + { + Logger.LogWarning("On NotifyWormholeRemoved, unable to find removed wormhole"); + } + } + } + catch (Exception ex) + { + Logger.LogError(ex, "On NotifyWormholeRemoved error"); + } + } + + private async Task OnWormholeMoved(string user,int mapId, int whId, double posX, double posY) + { + try + { + if (MapId.HasValue && MapId.Value == mapId) + { + var node = await GetSystemNode(whId); + if (node != null) + { + node.SetPosition(posX, posY); + } + else + { + Logger.LogWarning("On NotifyWormholeMoved, unable to find moved wormhole"); + } + } + } + catch (Exception ex) + { + Logger.LogError(ex, "On NotifyWormholeMoved error"); + } + } + + private async Task OnLinkAdded(string user,int mapId, int linkId) + { + try + { + if (MapId.HasValue && MapId.Value == mapId) + { + var link = await DbWHSystemLinks.GetById(linkId); + if (link != null) + { + var srcNode = await GetSystemNode(link.IdWHSystemFrom); + var targetNode = await GetSystemNode(link.IdWHSystemTo); + if (srcNode != null && targetNode != null) + { + _blazorDiagram?.Links?.Add(new EveSystemLinkModel(link, srcNode, targetNode)); + } + else + { + Logger.LogWarning("On NotifyLinkAdded, unable to find added link nodes"); + } + } + else + { + Logger.LogWarning("On NotifyLinkAdded, unable to find added link"); + } + } + } + catch (Exception ex) + { + Logger.LogError(ex, "On NotifyLinkAdded error"); + } + } + + private async Task OnLinkRemoved(string user,int mapId, int linkId) + { + try + { + if (MapId.HasValue && MapId.Value == mapId) + { + var link = await DbWHSystemLinks.GetById(linkId); + if (link != null) + { + var linkToRemove = _blazorDiagram?.Links?.FirstOrDefault(x => ((EveSystemLinkModel)x).Id == linkId); + if (linkToRemove != null) + { + _blazorDiagram?.Links?.Remove(linkToRemove); + } + else + { + Logger.LogWarning("On NotifyLinkRemoved, unable to find removed link"); + } + } + else + { + Logger.LogWarning("On NotifyLinkRemoved, unable to find removed link"); + } + } + } + catch (Exception ex) + { + Logger.LogError(ex, "On NotifyLinkRemoved error"); + } + } + + private async Task OnLinkChanged(string user,int mapId, int linkId, bool isEoL, SystemLinkSize size, SystemLinkMassStatus massStatus) + { + try + { + if (MapId.HasValue && MapId.Value == mapId) + { + var link = await DbWHSystemLinks.GetById(linkId); + if (link != null) + { + var linkToChange = _blazorDiagram?.Links?.FirstOrDefault(x => ((EveSystemLinkModel)x).Id == linkId); + if (linkToChange != null) + { + ((EveSystemLinkModel)linkToChange).IsEoL = isEoL; + ((EveSystemLinkModel)linkToChange).Size = size; + ((EveSystemLinkModel)linkToChange).MassStatus = massStatus; + linkToChange.Refresh(); + } + else + { + Logger.LogWarning("On NotifyLinkChanged, unable to find changed link"); + } + } + else + { + Logger.LogWarning("On NotifyLinkChanged, unable to find changed link"); + } + } + } + catch (Exception ex) + { + Logger.LogError(ex, "On NotifyLinkChanged error"); + } + } + + private async Task OnWormholeLockChanged(string user,int mapId, int whId, bool locked) + { + try + { + if (MapId.HasValue && MapId.Value == mapId) + { + var node = await GetSystemNode(whId); + if (node != null) + { + node.Locked = locked; + node.Refresh(); + } + else + { + Logger.LogWarning("On NotifyWormholeLockChanged, unable to find changed wormhole"); + } + } + } + catch (Exception ex) + { + Logger.LogError(ex, "On NotifyWormholeLockChanged error"); + } + } + + private async Task OnWormholeSystemStatusChanged(string user,int mapId, int whId, WHSystemStatus systemStatus) + { + try + { + if (MapId.HasValue && MapId.Value == mapId) + { + var node = await GetSystemNode(whId); + if (node != null) + { + node.SystemStatus = systemStatus; + node.Refresh(); + } + else + { + Logger.LogWarning("On NotifyWormholeSystemStatusChanged, unable to find changed wormhole"); + } + } + } + catch (Exception ex) + { + Logger.LogError(ex, "On NotifyWormholeSystemStatusChanged error"); + } + } + + private async Task OnWormholeNameExtensionChanged(string user,int mapId, int whId, bool increment) + { + try + { + if (MapId.HasValue && MapId.Value == mapId) + { + var node = await GetSystemNode(whId); + if (node != null) + { + if (increment) + node.IncrementNameExtension(); + else + node.DecrementNameExtension(); + node.Refresh(); + } + else + { + Logger.LogWarning("On NotifyWormholeNameExtensionChanged, unable to find changed wormhole"); + } + } + } + catch (Exception ex) + { + Logger.LogError(ex, "On NotifyWormholeNameExtensionChanged error"); + } + } + +#endregion + +} diff --git a/src/WHMapper/Pages/Mapper/Map/Overview.razor b/src/WHMapper/Pages/Mapper/Map/Overview.razor new file mode 100644 index 00000000..50a8690f --- /dev/null +++ b/src/WHMapper/Pages/Mapper/Map/Overview.razor @@ -0,0 +1,99 @@ +@using Blazor.Diagrams.Core; +@using Blazor.Diagrams.Core.Geometry; +@using Blazor.Diagrams.Core.Models; +@using Blazor.Diagrams.Components; +@using Blazor.Diagrams.Algorithms; +@using Blazor.Diagrams.Components.Widgets; +@using WHMapper.Models.Db.Enums + + + + + + + +@if (SelectedSystemLink == null && SelectedSystemNode == null) +{ + Add System +} + +@if (SelectedSystemLink != null) +{ + Toggle EOL + Status + + Normal + Critical + Verge + + + Size + + Small + Medium + Large + XLarge + + +} + +@if(SelectedSystemNode !=null) +{ + Set Destination + if(SelectedSystemNode.Locked) + { + UnLock + } + else + { + Lock + } + + System Status + + Unknown + Occupied + Hostile + Friendly + + +} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/WHMapper/Pages/Mapper/Notes/Overview.cs b/src/WHMapper/Pages/Mapper/Notes/Overview.cs index b812f57e..56ff8ae6 100644 --- a/src/WHMapper/Pages/Mapper/Notes/Overview.cs +++ b/src/WHMapper/Pages/Mapper/Notes/Overview.cs @@ -1,6 +1,5 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Components; -using Microsoft.AspNetCore.Components.Web; using MudBlazor; using WHMapper.Models.Custom.Node; using WHMapper.Models.Db; @@ -39,6 +38,9 @@ public partial class Overview : ComponentBase,IDisposable [Inject] private IWHNoteRepository DbWHNotes { get; set; } = null!; + [Parameter] + public int? CurrentMapId { get; set; } = -1; + [Parameter] public EveSystemNodeModel CurrentSystemNode { get; set; } = null!; @@ -49,9 +51,11 @@ protected async override Task OnParametersSetAsync() _solarSystemComment = string.Empty; _previousValue=string.Empty; //load system saved notes - if (DbWHNotes != null) + + + if (DbWHNotes != null && CurrentMapId.HasValue) { - _note = await DbWHNotes.GetBySolarSystemId(CurrentSystemNode.SolarSystemId); + _note = await DbWHNotes.Get(CurrentMapId.Value,CurrentSystemNode.SolarSystemId); if (_note == null) _solarSystemComment = string.Empty; else @@ -75,7 +79,6 @@ protected Task OnNoteChanged() private async Task HandleTimerAsync() { - if (_timer != null) { _previousValue = _solarSystemComment; @@ -113,16 +116,25 @@ private async Task HandleTimerAsync() } else { + + if(_previousValue==_solarSystemComment) { - - var note = await DbWHNotes.GetBySolarSystemId(CurrentSystemNode.SolarSystemId); + if(!CurrentMapId.HasValue) + { + Logger.LogError("CurrentMapId is null"); + throw new NullReferenceException("CurrentMapId is null"); + } + + + + var note = await DbWHNotes.Get(CurrentMapId.Value,CurrentSystemNode.SolarSystemId); if (note == null) { try { - _note = await DbWHNotes.Create(new WHNote(CurrentSystemNode.SolarSystemId, _solarSystemComment)); + _note = await DbWHNotes.Create(new WHNote(CurrentMapId.Value,CurrentSystemNode.SolarSystemId, _solarSystemComment)); if (_note != null) Snackbar.Add(MSG_SOLAR_SYSTEM_COMMENT_AUTOSAVE_SUCCESS, Severity.Success); else @@ -201,6 +213,8 @@ protected virtual void Dispose(bool disposing) { this._timer?.Dispose(); this._cts?.Dispose(); + this._timer = null; + this._cts = null; } } } diff --git a/src/WHMapper/Pages/Mapper/Overview.cs b/src/WHMapper/Pages/Mapper/Overview.cs index 709838fd..b0795c5c 100644 --- a/src/WHMapper/Pages/Mapper/Overview.cs +++ b/src/WHMapper/Pages/Mapper/Overview.cs @@ -1,1829 +1,354 @@ using Microsoft.AspNetCore.Components; -using WHMapper.Models.Custom.Node; -using WHMapper.Models.DTO.EveAPI.Location; -using WHMapper.Models.DTO.EveAPI.Universe; -using WHMapper.Pages.Mapper.CustomNode; -using WHMapper.Services.Anoik; -using WHMapper.Services.EveAPI; using Microsoft.AspNetCore.Components.Authorization; using WHMapper.Repositories.WHMaps; using WHMapper.Models.Db; -using WHMapper.Repositories.WHSystems; using MudBlazor; -using Blazor.Diagrams; -using WHMapper.Models.Db.Enums; -using WHMapper.Repositories.WHSystemLinks; -using Microsoft.AspNetCore.SignalR.Client; using Microsoft.AspNetCore.Authorization; -using WHMapper.Models.DTO; -using WHMapper.Services.EveOnlineUserInfosProvider; using ComponentBase = Microsoft.AspNetCore.Components.ComponentBase; -using System.Data; -using Microsoft.AspNetCore.Components.Web; -using WHMapper.Services.WHSignature; using WHMapper.Services.EveMapper; -using Blazor.Diagrams.Core.Behaviors; -using WHMapper.Models.DTO.EveMapper.Enums; -using WHMapper.Repositories.WHJumpLogs; -using Npgsql.EntityFrameworkCore.PostgreSQL.ValueGeneration.Internal; -using BlazorContextMenu; -using WHMapper.Repositories.WHNotes; -using WHMapper.Services.WHColor; -using WHMapper.Models.DTO.EveMapper.EveEntity; -namespace WHMapper.Pages.Mapper -{ - - - [Authorize(Policy = "Access")] - public partial class Overview : ComponentBase, IAsyncDisposable - { - private const float EPSILON = 0.0001f; // or some other small value - - protected BlazorDiagram _blazorDiagram = null!; - private WHMapper.Pages.Mapper.Signatures.Overview WHSignaturesView { get; set; } = null!; - - private EveSystemNodeModel? _selectedSystemNode = null; - private EveSystemLinkModel? _selectedSystemLink = null; - - private ICollection? _selectedSystemNodes = null; - private ICollection? _selectedSystemLinks = null; - - private readonly SemaphoreSlim _semaphoreSlim = new SemaphoreSlim(1, 1); - - private HubConnection _hubConnection=null!; - - - [Inject] - AuthenticationStateProvider AuthState { get; set; } = null!; - - [Inject] - TokenProvider TokenProvider { get; set; } = null!; - - [Inject] - IEveUserInfosServices UserInfos { get; set; } = null!; - - [Inject] - IWHMapRepository DbWHMaps { get; set; } = null!; - - [Inject] - IWHSystemRepository DbWHSystems { get; set; } = null!; - - [Inject] - IWHSystemLinkRepository DbWHSystemLinks { get; set; } = null!; - - [Inject] - IWHNoteRepository DbNotes { get; set; } = null!; - - [Inject] - IWHJumpLogRepository DbWHJumpLogs { get; set; } = null!; - - [Inject] - IEveAPIServices EveServices { get; set; } = null!; - - [Inject] - public ISnackbar Snackbar { get; set; } = null!; - - [Inject] IWHSignatureHelper SignatureHelper { get; set; } = null!; - - [Inject] - public NavigationManager Navigation { get; set; } = null!; - - [Inject] - public ILogger Logger { get; set; } = null!; - - [Inject] - private IDialogService DialogService { get; set; } = null!; - - [Inject] - private IEveMapperHelper MapperServices { get; set; } = null!; - - [Inject] - private IEveMapperTracker TrackerServices { get; set; } = null!; - - [Inject] - private IPasteServices PasteServices {get;set;}=null!; - - - private string _userName = string.Empty; - private int _characterId = 0; - - private IEnumerable? WHMaps { get; set; } = new List(); - private WHMap? _selectedWHMap = null!; - - private int _selectedWHMapIndex = 0; - private int SelectedWHMapIndex - { - get - { - return _selectedWHMapIndex; - } - set - { - if (_selectedWHMapIndex != value) - { - _selectedWHMapIndex = value; - if(WHMaps!=null) - _selectedWHMap = WHMaps.ElementAtOrDefault(value); - } - } - } - - private bool _loading = true; - public bool IsConnected => _hubConnection?.State == HubConnectionState.Connected; - - //private bool _isAdmin = false; - - - private SystemEntity? _currentSolarSystem = null!; - private Ship? _currentShip = null!; - private ShipEntity? _currentShipInfos = null!; - - protected override async Task OnInitializedAsync() - { - _userName = await UserInfos.GetUserName(); - _characterId = await UserInfos.GetCharactedID(); - if(await InitDiagram()) - { - _ = Task.Run(Init); - } - else - { - Snackbar?.Add("Mapper Initialization error", Severity.Error); - } - } - - private async Task Init() - { - if (await Restore()) - { - if (await InitNotificationHub()) - { - InitTrackerServices(); - await TrackerServices.StartTracking(); - InitPasteServices(); - } - - InitBlazorDiagramEvents(); - - _loading = false; - await InvokeAsync(StateHasChanged); - } - else - { - Snackbar?.Add("Mapper restore error", Severity.Error); - } - } - - private void InitTrackerServices() - { - TrackerServices.SystemChanged += OnSystemChanged; - TrackerServices.ShipChanged += OnShipChanged; - } - - private void InitPasteServices() - { - PasteServices.Pasted += OnPasted; - } - - private void InitBlazorDiagramEvents() - { - _blazorDiagram.SelectionChanged += async (item) => await OnDiagramSelectionChanged(item); - _blazorDiagram.KeyDown += async (kbevent) => await OnDiagramKeyDown(kbevent); - _blazorDiagram.PointerUp += async (item, pointerEvent) => await OnDiagramPointerUp(item, pointerEvent); - } - - #region Hub methodes - private async Task InitNotificationHub() - { - - try - { - if (TokenProvider != null && !string.IsNullOrEmpty(TokenProvider.AccessToken) && _hubConnection == null) - { - _hubConnection = new HubConnectionBuilder() - .WithUrl(Navigation.ToAbsoluteUri("/whmappernotificationhub"), options => - { - options.AccessTokenProvider = () => Task.FromResult(TokenProvider.AccessToken); - }).Build(); - - _hubConnection.On("NotifyUserConnected", (user) => - { - try - { - Snackbar?.Add($"{user} are connected", Severity.Info); - } - catch(Exception ex) - { - Logger.LogError(ex, "On NotifyUserConnected error"); - } - }); - - _ = _hubConnection.On("NotifyUserDisconnected", async (user) => - { - try - { - EveSystemNodeModel? userSystem = (EveSystemNodeModel?)_blazorDiagram?.Nodes?.FirstOrDefault(x => ((EveSystemNodeModel)x)!.ConnectedUsers.Contains(user)); - if (userSystem != null) - { - await userSystem.RemoveConnectedUser(user); - userSystem.Refresh(); - } - Snackbar?.Add($"{user} are disconnected", Severity.Info); - } - catch (Exception ex) - { - Logger.LogError(ex, "On NotifyUserDisconnected error"); - } - }); - - _hubConnection.On("NotifyUserPosition", async (user, systemName) => - { - try - { - EveSystemNodeModel? previousSytem = (EveSystemNodeModel?)(_blazorDiagram?.Nodes?.FirstOrDefault(x => ((EveSystemNodeModel)x)!.ConnectedUsers.Contains(user))); - if (previousSytem != null) - { - await previousSytem.RemoveConnectedUser(user); - previousSytem.Refresh(); - } - - - EveSystemNodeModel? systemToAddUser = (EveSystemNodeModel?)_blazorDiagram?.Nodes?.FirstOrDefault(x => ((EveSystemNodeModel)x)!.Title == systemName); - if (systemToAddUser != null) - { - await systemToAddUser.AddConnectedUser(user); - systemToAddUser.Refresh(); - } - else - { - Logger.LogWarning("On NotifyUserPosition, unable to find system to add user"); - } - } - catch (Exception ex) - { - Logger.LogError(ex, "On NotifyUserPosition error"); - } - }); - - _hubConnection.On>("NotifyUsersPosition", async (usersPosition) => - { - try - { - await Parallel.ForEachAsync(usersPosition, async (item, cancellationToken) => - { - if(!string.IsNullOrEmpty(item.Value)) - { - EveSystemNodeModel? systemToAddUser = (EveSystemNodeModel?)_blazorDiagram?.Nodes?.FirstOrDefault(x => ((EveSystemNodeModel)x).Title == item.Value); - if(systemToAddUser!=null) - { - await systemToAddUser.AddConnectedUser(item.Key); - systemToAddUser.Refresh(); - } - } - }); - } - catch (Exception ex) - { - Logger.LogError(ex, "On NotifyUserPosition error"); - } - }); - - _hubConnection.On("NotifyWormoleAdded", async (user, mapId, wormholeId) => - { - try - { - if (wormholeId > 0 && mapId == _selectedWHMap?.Id) - { - var newWHSystem = await DbWHSystems.GetById(wormholeId); - while (newWHSystem == null) - newWHSystem = await DbWHSystems.GetById(wormholeId); - - var newSystemNode = await MapperServices.DefineEveSystemNodeModel(newWHSystem); - newSystemNode.OnLocked += OnWHSystemNodeLocked; - newSystemNode.OnSystemStatusChanged += OnWHSystemStatusChange; - _selectedWHMap.WHSystems.Add(newWHSystem); - _blazorDiagram?.Nodes?.Add(newSystemNode); - } - } - catch (Exception ex) - { - Logger.LogError(ex, "On NotifyWormoleAdded error"); - } - - }); - - _hubConnection.On("NotifyWormholeRemoved", async (user, mapId, wormholeId) => - { - try - { - if (DbWHMaps!=null && _selectedWHMap!=null && wormholeId > 0 && _selectedWHMap.Id== mapId) - { - _selectedWHMap = await DbWHMaps.GetById(mapId); - var systemNodeToDelete = _blazorDiagram.Nodes?.FirstOrDefault(x => ((EveSystemNodeModel)x).IdWH == wormholeId); - if (systemNodeToDelete != null) - _blazorDiagram.Nodes?.Remove(systemNodeToDelete); - else - { - Logger.LogWarning("On NotifyWormholeRemoved, unable to find system to remove"); - Snackbar?.Add("On NotifyWormholeRemoved, unable to find system to remove", Severity.Warning); - - } - } - } - catch (Exception ex) - { - Logger.LogError(ex, "On NotifyWormholeRemoved error"); - } - }); - - _hubConnection.On("NotifyLinkAdded", async (user, mapId, linKId) => - { - try - { - if (DbWHMaps != null && linKId > 0 && _selectedWHMap!=null && _selectedWHMap?.Id== mapId ) - { - _selectedWHMap = await DbWHMaps.GetById(mapId); - var link = _selectedWHMap?.WHSystemLinks.Where(x => x.Id == linKId).SingleOrDefault(); - if (link != null) - { - EveSystemNodeModel? newSystemNodeFrom = (EveSystemNodeModel?)(_blazorDiagram?.Nodes?.FirstOrDefault(x => (x as EveSystemNodeModel)!.IdWH == link.IdWHSystemFrom)); - EveSystemNodeModel? newSystemNodeTo = (EveSystemNodeModel?)(_blazorDiagram?.Nodes?.FirstOrDefault(x => (x as EveSystemNodeModel)!.IdWH == link.IdWHSystemTo)); - if(newSystemNodeTo!=null && newSystemNodeFrom!=null) - _blazorDiagram?.Links?.Add(new EveSystemLinkModel(link, newSystemNodeFrom, newSystemNodeTo)); - else - { - Logger.LogWarning("On NotifyLinkAdded, unable to find system to add link"); - Snackbar?.Add("On NotifyLinkAdded, unable to find system to add link", Severity.Warning); - } - } - } - } - catch (Exception ex) - { - Logger.LogError(ex, "On NotifyLinkAdded error"); - } - }); - - _hubConnection.On("NotifyLinkRemoved", async (user, mapId, linKId) => - { - try - { - if (DbWHMaps != null && linKId > 0 && _selectedWHMap != null && _selectedWHMap.Id == mapId) - { - _selectedWHMap = await DbWHMaps.GetById(mapId); - - var linkToDel = _blazorDiagram.Links?.FirstOrDefault(x => ((EveSystemLinkModel)x).Id == linKId); - if (linkToDel != null) - _blazorDiagram.Links?.Remove(linkToDel); - else - { - Logger.LogWarning("On NotifyLinkRemoved, unable to find link to remove"); - Snackbar?.Add("On NotifyLinkRemoved, unable to find link to remove", Severity.Warning); - } - - } - } - catch (Exception ex) - { - Logger.LogError(ex, "On NotifyLinkRemoved error"); - } - }); - - _hubConnection.On("NotifyWormoleMoved", async (user, mapId, wormholeId, posX, posY) => - { - try - { - if (DbWHMaps != null && _selectedWHMap != null && wormholeId > 0 && _selectedWHMap.Id == mapId) - { - _selectedWHMap = await DbWHMaps.GetById(mapId); - - var whToMoved = _blazorDiagram?.Nodes?.FirstOrDefault(x => ((EveSystemNodeModel)x).IdWH == wormholeId); - if (whToMoved != null) - whToMoved.SetPosition(posX, posY); - else - { - Logger.LogWarning("On NotifyWormoleMoved, unable to find wormhole to move"); - Snackbar?.Add("On NotifyWormoleMoved, unable to find wormhole to move", Severity.Warning); - } - } - } - catch (Exception ex) - { - Logger.LogError(ex, "On NotifyWormoleMoved error"); - } - }); - - _hubConnection.On("NotifyLinkChanged",async (user, mapId, linkId, eol, size, mass) => - { - try - { - if (DbWHMaps != null && linkId > 0 && _selectedWHMap != null && _selectedWHMap.Id == mapId) - { - _selectedWHMap = await DbWHMaps.GetById(mapId); - var linkToChanged = _blazorDiagram?.Links?.FirstOrDefault(x => ((EveSystemLinkModel)x).Id == linkId); - if (linkToChanged != null) - { - ((EveSystemLinkModel)linkToChanged).IsEoL = eol; - ((EveSystemLinkModel)linkToChanged).Size = size; - ((EveSystemLinkModel)linkToChanged).MassStatus = mass; - ((EveSystemLinkModel)linkToChanged).Refresh(); - } - else - { - Logger.LogWarning("On NotifyLinkChanged, unable to find link to change"); - Snackbar?.Add("On NotifyLinkChanged, unable to find link to change", Severity.Warning); - } - } - } - catch (Exception ex) - { - Logger.LogError(ex, "On NotifyLinkChanged error"); - } - }); - - _hubConnection.On("NotifyWormholeNameExtensionChanged", async (user, mapId, wormholeId,increment) => - { - try - { - if (DbWHMaps != null && _selectedWHMap != null && wormholeId > 0 && _selectedWHMap.Id == mapId) - { - _selectedWHMap = await DbWHMaps.GetById(mapId); - EveSystemNodeModel? systemToIncrementNameExtenstion = (EveSystemNodeModel?)_blazorDiagram?.Nodes?.FirstOrDefault(x => ((EveSystemNodeModel)x).IdWH == wormholeId); - if (systemToIncrementNameExtenstion != null) - { - if (increment) - systemToIncrementNameExtenstion.IncrementNameExtension(); - else - systemToIncrementNameExtenstion.DecrementNameExtension(); - - systemToIncrementNameExtenstion.Refresh(); - } - else - { - Logger.LogWarning("On NotifyWormholeNameExtensionChanged, unable to find wormhole to change name extension"); - Snackbar?.Add("On NotifyWormholeNameExtensionChanged, unable to find wormhole to change name extension", Severity.Warning); - } - } - } - catch (Exception ex) - { - Logger.LogError(ex, "On NotifyWormholeNameExtensionChanged error"); - } - - }); - - _hubConnection.On("NotifyWormholeSignaturesChanged", async (user, mapId, wormholeId) => - { - try - { - if (DbWHMaps != null && _selectedWHMap != null && wormholeId > 0 && _selectedWHMap.Id == mapId) - { - _selectedWHMap = await DbWHMaps.GetById(mapId); - if(WHSignaturesView!=null && WHSignaturesView.CurrentSystemNodeId ==wormholeId) - await WHSignaturesView.Restore(); - } - } - catch (Exception ex) - { - Logger.LogError(ex, "On NotifyWormholeSignaturesChanged error"); - } - }); - - - - _ = _hubConnection.On("NotifyWormholeLockChanged", async (user, mapId, wormholeId, locked) => - { - try - { - if (_selectedWHMap != null && wormholeId > 0 && mapId == _selectedWHMap.Id) - { - _selectedWHMap = await DbWHMaps.GetById(mapId); - EveSystemNodeModel? whChangeLock = (EveSystemNodeModel?)(_blazorDiagram?.Nodes?.FirstOrDefault(x => ((EveSystemNodeModel)x).IdWH == wormholeId)); - if (whChangeLock != null) - { - whChangeLock.Locked = locked; - whChangeLock.Refresh(); - } - else - { - Logger.LogWarning("On NotifyWormholeLockChanged, unable to find wormhole to change lock"); - Snackbar?.Add("On NotifyWormholeLockChanged, unable to find wormhole to change lock", Severity.Warning); - } - } - } - catch (Exception ex) - { - Logger.LogError(ex, "On NotifyWormholeLockChanged error"); - } - - }); - - _hubConnection.On("NotifyWormholeSystemStatusChanged", async (user, mapId, wormholeId, systemStatus) => - { - try - { - if (_blazorDiagram!=null && _selectedWHMap != null && wormholeId > 0 && mapId == _selectedWHMap.Id) - { - _selectedWHMap = await DbWHMaps.GetById(mapId); - EveSystemNodeModel? whChangeSystemStatus = _blazorDiagram?.Nodes?.FirstOrDefault(x => ((EveSystemNodeModel)x).IdWH == wormholeId) as EveSystemNodeModel; - if(whChangeSystemStatus!=null) - { - whChangeSystemStatus.SystemStatus = systemStatus; - whChangeSystemStatus.Refresh(); - } - } - } - catch (Exception ex) - { - Logger.LogError(ex, "On NotifyWormholeLockChanged error"); - } - - }); - - await _hubConnection.StartAsync(); - - return true; - } - return false; - } - catch(Exception ex) - { - Logger.LogError(ex, "InitNotificationHub error"); - return false; - } - - } - - private async Task NotifyUserPosition(string systemName) - { - if (_hubConnection is not null) - { - await _hubConnection.SendAsync("SendUserPosition", systemName); - } - } - - private async Task NotifyWormoleAdded(int mapId,int wormholeId) - { - if (_hubConnection is not null) - { - await _hubConnection.SendAsync("SendWormholeAdded", mapId,wormholeId); - } - } - - private async Task NotifyWormholeRemoved(int mapId, int wormholeId) - { - if (_hubConnection is not null) - { - await _hubConnection.SendAsync("SendWormholeRemoved", mapId,wormholeId); - } - } - - private async Task NotifyLinkAdded(int mapId,int linkId) - { - if (_hubConnection is not null) - { - await _hubConnection.SendAsync("SendLinkAdded", mapId, linkId); - } - } - - private async Task NotifyLinkRemoved(int mapId, int linkId) - { - if (_hubConnection is not null) - { - await _hubConnection.SendAsync("SendLinkRemoved", mapId, linkId); - } - } - - private async Task NotifyWormholeMoved(int mapId, int wormholeId,double posX,double posY) - { - if (_hubConnection is not null) - { - await _hubConnection.SendAsync("SendWormholeMoved", mapId, wormholeId, posX, posY); - } - } - - private async Task NotifyLinkChanged(int mapId,int linkId, bool eol, SystemLinkSize size, SystemLinkMassStatus mass) - { - if (_hubConnection is not null) - { - await _hubConnection.SendAsync("SendLinkChanged", mapId, linkId, eol, size, mass); - } - } - - private async Task NotifyWormholeNameExtensionChanged(int mapId, int wormholeId,bool increment) - { - if (_hubConnection is not null) - { - await _hubConnection.SendAsync("SendWormholeNameExtensionChanged", mapId, wormholeId, increment); - } - } - - private async Task NotifyWormholeSignaturesChanged(int mapId, int wormholeId) - { - if (_hubConnection is not null) - { - await _hubConnection.SendAsync("SendWormholeSignaturesChanged", mapId, wormholeId); - } - } - - private async Task NotifyWormholeLockChanged(int mapId, int wormholeId, bool locked) - { - if (_hubConnection is not null) - { - await _hubConnection.SendAsync("SendWormholeLockChanged", mapId, wormholeId, locked); - } - } - - private async Task NotifyWormholeSystemStatusChanged(int mapId, int wormholeId, WHSystemStatus systemStatus) - { - if (_hubConnection is not null) - { - await _hubConnection.SendAsync("SendWormholeSystemStatusChanged", mapId, wormholeId, systemStatus); - } - } - - #endregion - - private Task InitDiagram() - { - try - { - if (_blazorDiagram == null) - { - Logger.LogInformation("Start Init Diagram"); - _blazorDiagram = new BlazorDiagram(); - _blazorDiagram.UnregisterBehavior(); - _blazorDiagram.RegisterBehavior(new CustomDragMovablesBehavior(_blazorDiagram)); - - _blazorDiagram.Options.Zoom.Enabled = true; - _blazorDiagram.Options.Zoom.Inverse = false; - _blazorDiagram.Options.Links.EnableSnapping = false; - _blazorDiagram.Options.AllowMultiSelection = true; - _blazorDiagram.RegisterComponent(); - _blazorDiagram.RegisterComponent(); - } - - return Task.FromResult(true); - } - catch(Exception ex) - { - Logger.LogError(ex, "Init Diagram Error"); - return Task.FromResult(false); - } - } - - private async Task OnDiagramSelectionChanged(Blazor.Diagrams.Core.Models.Base.SelectableModel? item) - { - await _semaphoreSlim.WaitAsync(); - try - { - await InvokeAsync(() => { - - if (item == null) - return; - - var selectedModels = _blazorDiagram.GetSelectedModels(); - _selectedSystemNodes = selectedModels.Where(x => x.GetType() == typeof(EveSystemNodeModel)).Select(x => (EveSystemNodeModel)x).ToList(); - _selectedSystemLinks = selectedModels.Where(x => x.GetType() == typeof(EveSystemLinkModel)).Select(x => (EveSystemLinkModel)x).ToList(); - - - if (item.GetType() == typeof(EveSystemNodeModel)) - { - _selectedSystemLink = null; - - if (((EveSystemNodeModel)item).Selected) - { - _selectedSystemNode = (EveSystemNodeModel)item; - _blazorDiagram.SendToFront(_selectedSystemNode); - } - else - _selectedSystemNode = null; - - StateHasChanged(); - return; - - } - - if (item.GetType() == typeof(EveSystemLinkModel)) - { - _selectedSystemNode = null; - - if (((EveSystemLinkModel)item).Selected) - { - _selectedSystemLink = (EveSystemLinkModel)item; - _blazorDiagram.SendToFront(_selectedSystemLink); - } - else - _selectedSystemLink = null; - - - StateHasChanged(); - return; - } - - }); - } - catch (Exception ex) - { - Logger.LogError(ex, "On diagram selection changed error"); - } - finally - { - _semaphoreSlim.Release(); - } - } - - private async Task OnDiagramKeyDown(Blazor.Diagrams.Core.Events.KeyboardEventArgs eventArgs) - { - - await _semaphoreSlim.WaitAsync(); - try - { - //To link systel - if (await OnLinkSystemKeyPressed(eventArgs)) - return; - - - //To increment or decrment node extenstion name - if (await OnIncrementOrDecrementExtensionKeyPressed(eventArgs)) - return; - - - //To Delete selected Node on current map - if (await OnDeleteKeyPressed(eventArgs)) - return; - } - catch (Exception ex) - { - Logger.LogError(ex, "OnDiagramKeyDown error"); - } - finally - { - _semaphoreSlim.Release(); - } - } - - #region Diagram Keyboard Pressed - private async Task OnLinkSystemKeyPressed(Blazor.Diagrams.Core.Events.KeyboardEventArgs eventArgs) - { - if (eventArgs.Code == "KeyL" && _selectedWHMap != null && _selectedSystemNodes != null && _selectedSystemNodes.Count == 2) - { - if (IsLinkExist(_selectedSystemNodes.ElementAt(0), _selectedSystemNodes.ElementAt(1))) - { - Snackbar.Add("Nodes are already linked", Severity.Warning); - return false; - } - else - { - //link create manually, no ship jump - if (!await AddSystemNodeLink(_selectedWHMap, _selectedSystemNodes.ElementAt(0), _selectedSystemNodes.ElementAt(1),true)) - { - Logger.LogError("Add Wormhole Link db error"); - Snackbar.Add("Add Wormhole Link db error", Severity.Error); - return false; - } - else - return true; - } - - } - return false; - - } - - private async Task OnIncrementOrDecrementExtensionKeyPressed(Blazor.Diagrams.Core.Events.KeyboardEventArgs eventArgs) - { - if ((eventArgs.Code == "NumpadAdd" || eventArgs.Code == "NumpadSubtract" || eventArgs.Code == "ArrowUp" || eventArgs.Code == "ArrowDown") && _selectedWHMap != null && _selectedSystemNode != null) - { - bool res = false; - if (eventArgs.Code == "NumpadAdd" || eventArgs.Code == "ArrowUp") - res = await IncrementOrDecrementNodeExtensionNameOnMap(_selectedWHMap, _selectedSystemNode, true); - else - res = await IncrementOrDecrementNodeExtensionNameOnMap(_selectedWHMap, _selectedSystemNode, false); - - if (res) - { - _selectedSystemNode.Refresh(); - return true; - } - else - { - Snackbar?.Add("Loading wormhole node db error", Severity.Error); - return false; - } - } - return false; - } - - private async Task OnDeleteKeyPressed(Blazor.Diagrams.Core.Events.KeyboardEventArgs eventArgs) - { - if (eventArgs.Code == "Delete") - { - if (_selectedWHMap == null) - { - Logger.LogError("OnDiagramKeyDown, no map selected to delete node or link"); - Snackbar?.Add("No map selected to delete node or link", Severity.Error); - return false; - } - - if (_selectedSystemNode != null && _selectedSystemNodes != null && _selectedSystemNodes.Count() > 0) - { - await TrackerServices.StopTracking(); - _currentSolarSystem=null; - foreach (var node in _selectedSystemNodes) - { - if (node.Locked) - { - Snackbar?.Add(string.Format("{0} wormhole is locked.You can't remove it.",node.Name), Severity.Warning); - } - else - { - if (!await DeletedNodeOnMap(_selectedWHMap, node)) - Snackbar?.Add("Remove wormhole node db error", Severity.Error); - } - } - _selectedSystemNode = null; - StateHasChanged(); - await TrackerServices.StartTracking(); - return true; - } - - if (_selectedSystemLink != null && _selectedSystemLinks != null && _selectedSystemLinks.Count() > 0) - { - foreach (var link in _selectedSystemLinks) - { - if (!await DeletedLinkOnMap(_selectedWHMap, link)) - Snackbar?.Add("Remove wormhole link db error", Severity.Error); - - } - _selectedSystemLink = null; - StateHasChanged(); - - return true; - - } - - - } - return false; - } - - #endregion - - private async Task OnDiagramPointerUp(Blazor.Diagrams.Core.Models.Base.Model? item, Blazor.Diagrams.Core.Events.PointerEventArgs eventArgs) - { - if (item == null) - return; - - if (item.GetType() == typeof(EveSystemNodeModel)) - { - await _semaphoreSlim.WaitAsync(); - try - { - - var wh = await DbWHSystems.GetById(((EveSystemNodeModel)item).IdWH); - if (wh != null) - { - if(Math.Abs(wh.PosX - ((EveSystemNodeModel)item).Position.X) >= EPSILON || Math.Abs(wh.PosY - ((EveSystemNodeModel)item).Position.Y) >= EPSILON) - { - wh.PosX = ((EveSystemNodeModel)item).Position.X; - wh.PosY = ((EveSystemNodeModel)item).Position.Y; - - if (await DbWHSystems.Update(((EveSystemNodeModel)item).IdWH, wh) == null) - { - Snackbar?.Add("Update wormhole node position db error", Severity.Error); - } - if(_selectedWHMap!=null) - await NotifyWormholeMoved(_selectedWHMap.Id, wh.Id, wh.PosX, wh.PosY); - else - { - Logger.LogWarning("On Mouse pointer up, unable to find selected map to notify wormhole moved"); - Snackbar?.Add("Unable to find selected map to notify wormhole moved", Severity.Warning); - - } - } - } - else - { - Logger.LogError("On Mouse pointer up, unable to find moved wormhole node db error"); - Snackbar?.Add("Unable to find moved wormhole node dd error", Severity.Error); - } - } - catch (Exception ex) - { - Logger.LogError(ex, "Mouse Pointer Up"); - } - finally - { - _semaphoreSlim.Release(); - } - - } - - } - private async Task Restore() - { - try - { - if (DbWHMaps == null) - { - Logger.LogError("DbWHMaps is null"); - return false; - } - - Logger.LogInformation("Beginning Restore Mapper"); - - if (!await RetrieveMaps()) - { - return false; - } - - if (_selectedWHMap != null && _selectedWHMap.WHSystems != null && _selectedWHMap.WHSystems.Count > 0) - { - await InitializeSystemNodes(); - await InitializeSystemLinks(); - } - - Logger.LogInformation("Restore Mapper Success"); - return true; - } - catch (Exception ex) - { - Logger.LogError(ex, "Mapper Restore"); - return false; - } - } - - private async Task RetrieveMaps() - { - WHMaps = await DbWHMaps.GetAll(); - if (WHMaps == null || !WHMaps.Any()) - { - _selectedWHMap = await DbWHMaps.Create(new WHMap("Default Maps")); - if (_selectedWHMap != null) - { - WHMaps = await DbWHMaps.GetAll(); - } - } - else - { - _selectedWHMap = WHMaps.FirstOrDefault(); - } - - return _selectedWHMap != null; - } - - private async Task InitializeSystemNodes() - { - if (_selectedWHMap != null && _selectedWHMap.WHSystems != null) - { - foreach (var dbWHSys in _selectedWHMap.WHSystems) - { - EveSystemNodeModel whSysNode = await MapperServices.DefineEveSystemNodeModel(dbWHSys); - whSysNode.OnLocked += OnWHSystemNodeLocked; - whSysNode.OnSystemStatusChanged += OnWHSystemStatusChange; - _blazorDiagram.Nodes.Add(whSysNode); - } - } - } - - private async Task InitializeSystemLinks() - { - if (_selectedWHMap?.WHSystemLinks == null || _selectedWHMap.WHSystemLinks.Count == 0) - { - return; - } - - foreach (var dbWHSysLink in _selectedWHMap.WHSystemLinks) - { - var whFrom = await DbWHSystems.GetById(dbWHSysLink.IdWHSystemFrom); - var whTo = await DbWHSystems.GetById(dbWHSysLink.IdWHSystemTo); - - if (whFrom != null && whTo != null) - { - await AddLinkToDiagram(dbWHSysLink, whFrom, whTo); - } - else - { - await RemoveInvalidLink(dbWHSysLink); - } - } - - await InvokeAsync(StateHasChanged); - } - - private async Task AddLinkToDiagram(WHSystemLink dbWHSysLink, WHSystem whFrom, WHSystem whTo) - { - var srcNode = GetNodeByTitle(whFrom.Name); - var targetNode = GetNodeByTitle(whTo.Name); - - if (srcNode != null && targetNode != null) - { - _blazorDiagram.Links.Add(new EveSystemLinkModel(dbWHSysLink, srcNode, targetNode)); - } - else - { - Logger.LogWarning("Bad Link, srcNode or Targetnode is null, Auto remove"); - await RemoveInvalidLink(dbWHSysLink); - } - } - - private EveSystemNodeModel? GetNodeByTitle(string title) - { - if (_blazorDiagram == null || _blazorDiagram.Nodes == null || _blazorDiagram.Nodes.Count == 0) - { - Logger.LogWarning("GetNodeByTitle, no node in diagram"); - return null; - } - return _blazorDiagram.Nodes - .FirstOrDefault(x => string.Equals(x.Title, title, StringComparison.OrdinalIgnoreCase)) as EveSystemNodeModel - ?? null; - } - - private async Task RemoveInvalidLink(WHSystemLink dbWHSysLink) - { - if (_selectedWHMap != null && await DbWHSystemLinks.DeleteById(dbWHSysLink.Id)) - { - Logger.LogWarning("Bad Link, Auto remove"); - _selectedWHMap.WHSystemLinks.Remove(dbWHSysLink); - } - } - private async Task DeletedNodeOnMap(WHMap map, EveSystemNodeModel node) - { - try - { - if (map == null || node == null) - { - Logger.LogError("DeletedNodeOnMap map or node is null"); - return false; - } - - if(map.WHSystems.Count>0 && map.WHSystems.FirstOrDefault(x=>x.Id==node.IdWH)==null) - { - Logger.LogError("DeletedNodeOnMap map doesn't contain this node"); - return false; - } - - if (await DbWHSystems.DeleteById(node.IdWH)) - { - var whSystemToDelete = map.WHSystems.FirstOrDefault(x => x.Id == node.IdWH); - if(whSystemToDelete!=null) - map.WHSystems.Remove(whSystemToDelete); - - //db link will be automatically delete via db foreignkey cascade - var whSystemLinksToDetele = map.WHSystemLinks.Where(x => x.IdWHSystemFrom == node.IdWH || x.IdWHSystemTo == node.IdWH); - foreach(var linkToDelete in whSystemLinksToDetele) - map.WHSystemLinks.Remove(linkToDelete); - - await NotifyWormholeRemoved(map.Id, node.IdWH); - return true; - } - - return false; - } - catch (Exception ex) - { - Logger.LogError(ex, "Deleted node on map error"); - return false; - } - } - private async Task DeletedLinkOnMap(WHMap map, EveSystemLinkModel link) - { - try - { - if (map == null || link == null) - { - Logger.LogError("DeletedLinkOnMap map or link is null"); - return false; - } - - if(await DbWHSystemLinks.DeleteById(link.Id)) - { - var whSystemLinkToDelete = map.WHSystemLinks.FirstOrDefault(x => x.Id == link.Id); - if (whSystemLinkToDelete != null) - map.WHSystemLinks.Remove(whSystemLinkToDelete); - - await NotifyLinkRemoved(map.Id, link.Id); - return true; - } - - return false; - } - catch (Exception ex) - { - Logger.LogError(ex, "Deleted link on map error"); - return false; - } - - } - private async Task IncrementOrDecrementNodeExtensionNameOnMap(WHMap map, EveSystemNodeModel node,bool increment) - { - try - { - if (map == null || node == null) - { - Logger.LogError("IncrementOrDecrementNodeExtensionNameOnMap map or node is null"); - return false; - } - - var wh = await DbWHSystems.GetById(node.IdWH); - if (wh != null) - { - if (increment) - node.IncrementNameExtension(); - else - node.DecrementNameExtension(); - - if (node.NameExtension == null) - wh.NameExtension = 0; - else - wh.NameExtension = ((byte)((node.NameExtension.ToCharArray())[0])); - - wh = await DbWHSystems.Update(wh.Id, wh); - - - if (wh != null) - { - await NotifyWormholeNameExtensionChanged(map.Id, wh.Id, increment); - return true; - } - } - - return false; - - } - catch (Exception ex) - { - Logger.LogError(ex, "Increment Or Decrement node extension name error"); - return false; - } - } - - - private EveSystemLinkModel? GetLink(EveSystemNodeModel src, EveSystemNodeModel target) - { - try - { - if (src == null || target == null) - { - Logger.LogError("LinkExist src or target is null"); - return null; - } - - var whLink = _blazorDiagram.Links.FirstOrDefault(x => - ((((EveSystemNodeModel)x.Source!.Model!).IdWH == src.IdWH) && (((EveSystemNodeModel)x.Target!.Model!).IdWH == target.IdWH)) - || - ((((EveSystemNodeModel)x.Source!.Model!).IdWH == target.IdWH) && (((EveSystemNodeModel)x.Target!.Model!).IdWH == src.IdWH))); - - if (whLink == null) - return null; - else - return (EveSystemLinkModel)whLink; - } - catch (Exception ex) - { - Logger.LogError(ex, "Get Link error"); - return null; - } - } - - private bool IsLinkExist(EveSystemNodeModel src, EveSystemNodeModel target) - { - try - { - var link = this.GetLink(src, target); - - if (link == null) - return false; - else - return true; - } - catch (Exception ex) - { - Logger.LogError(ex, "Is Link Exist error"); - return false; - } - - } - - private async Task AddSystemNode(WHMap map,SystemEntity? src,SystemEntity target) - { - EveSystemNodeModel? previousSystemNode = null; - WHSystem? newWHSystem= null; - double defaultNewSystemPosX = 0; - double defaultNewSystemPosY = 0; - char extension; - int nbSameWHClassLink =0; - - try - { - //determine position on map. depends of previous system , todo refactor - if (src != null) - { - previousSystemNode = (EveSystemNodeModel?)(_blazorDiagram?.Nodes?.FirstOrDefault(x => ((EveSystemNodeModel)x).SolarSystemId == src.Id)); - - if(previousSystemNode!=null) - { - defaultNewSystemPosX = previousSystemNode.Position!.X + previousSystemNode.Size!.Width + 10; - defaultNewSystemPosY = previousSystemNode.Position!.Y + previousSystemNode!.Size!.Height + 10; - } - else - { - defaultNewSystemPosX=10; - defaultNewSystemPosY=10; - } - } - - //determine if source have same system link and get next unique ident - if(src != null && await MapperServices.IsRouteViaWH(src, target)) //check if HS/LS/NS to HS/LS/NS via WH not gate - { - - //get whClass an determine if another connection to another wh with same class exist from previous system. Increment extension value in that case - EveSystemType whClass = await MapperServices.GetWHClass(target); - var sameWHClassWHList = _blazorDiagram?.Links?.Where(x => ((EveSystemNodeModel)(x.Target!.Model!)).SystemType == whClass && ((EveSystemNodeModel)x.Source!.Model!).SolarSystemId == src.Id); - - if(sameWHClassWHList!=null) - nbSameWHClassLink = sameWHClassWHList.Count(); - else - nbSameWHClassLink=0; - - if (nbSameWHClassLink > 0) - { - extension = (Char)(Convert.ToUInt16('A') + (nbSameWHClassLink)); - newWHSystem = await DbWHSystems.Create(new WHSystem(map.Id, target.Id, target.Name, extension, target.SecurityStatus, defaultNewSystemPosX, defaultNewSystemPosY)); - } - else - newWHSystem = await DbWHSystems.Create(new WHSystem(map.Id, target.Id, target.Name, target.SecurityStatus, defaultNewSystemPosX, defaultNewSystemPosY)); - - } - else - newWHSystem = await DbWHSystems.Create(new WHSystem(map.Id,target.Id,target.Name, target.SecurityStatus, defaultNewSystemPosX, defaultNewSystemPosY)); - - if (newWHSystem!=null) - { - var newSystemNode = await MapperServices.DefineEveSystemNodeModel(newWHSystem); - newSystemNode.OnLocked += OnWHSystemNodeLocked; - newSystemNode.OnSystemStatusChanged += OnWHSystemStatusChange; - - await newSystemNode.AddConnectedUser(_userName); - - map.WHSystems.Add(newWHSystem); - _blazorDiagram?.Nodes?.Add(newSystemNode); - await NotifyWormoleAdded(map.Id, newWHSystem.Id); - - - if (previousSystemNode != null) - { - //remove ConnectedUser on previous system - await previousSystemNode.RemoveConnectedUser(_userName); - previousSystemNode.Refresh(); - } +namespace WHMapper.Pages.Mapper; +[Authorize(Policy = "Access")] +public partial class Overview : ComponentBase, IAsyncDisposable +{ + private List WHMaps { get; set; } = new List(); - _blazorDiagram?.SelectModel(newSystemNode, true); - return true; - } - else - { - Logger.LogError("Add Wormhole db error"); - return false; - } - - - } - catch(Exception ex) - { - Logger.LogError(ex,"AddSystemNode Error"); - return false; - } + private int _selectedWHMapIndex = 0; + private int SelectedWHMapIndex + { + get + { + return _selectedWHMapIndex; } - private async Task AddSystemNodeLink(WHMap map, SystemEntity src, SystemEntity target) + set { - if (_blazorDiagram == null  || map == null || src == null || target == null) + if (_selectedWHMapIndex != value) { - Logger.LogError("CreateLink map or src or target is null"); - return false; + _selectedWHMapIndex = value; } - - EveSystemNodeModel? srcNode = (EveSystemNodeModel?)(_blazorDiagram?.Nodes?.FirstOrDefault(x => ((EveSystemNodeModel)x).SolarSystemId == src.Id)); - EveSystemNodeModel? targetNode = (EveSystemNodeModel?)(_blazorDiagram?.Nodes?.FirstOrDefault(x => ((EveSystemNodeModel)x).SolarSystemId == target.Id)); - - return await AddSystemNodeLink(map,srcNode,targetNode); } - private async Task AddSystemNodeLink(WHMap map, EveSystemNodeModel? srcNode, EveSystemNodeModel? targetNode,bool isManual=false) - { - try - { - if(srcNode==null || targetNode ==null) - { - Logger.LogError("CreateLink src or target node is null"); - return false; - } + } - if(srcNode.SolarSystemId==targetNode.SolarSystemId) - { - Logger.LogError("CreateLink src and target node are the same"); - return false; - } + private bool _loading = true; - var newLink = await DbWHSystemLinks.Create(new WHSystemLink(map.Id, srcNode.IdWH, targetNode.IdWH)); + [Inject] + public ILogger Logger { get; set; } = null!; + [Inject] + public ISnackbar Snackbar { get; set; } = null!; - if (newLink != null) - { - await AddSystemNodeLinkLog(newLink,isManual); + [Inject] + private AuthenticationStateProvider _authenticationStateProvider {get;set;} = null!; + [Inject] + private IAuthorizationService _authorizationService { get; set; } = null!; - map.WHSystemLinks.Add(newLink); - _blazorDiagram?.Links?.Add(new EveSystemLinkModel(newLink, srcNode, targetNode)); - await NotifyLinkAdded(map.Id, newLink.Id); - return true; - } - return false; - } - catch(Exception ex) - { - Logger.LogError(ex, "AddSystemNodeLink error"); - return false; - } - } - internal async Task AddSystemNodeLinkLog(int whSystemLinkID,bool manuelJump=false) - { - if(_currentShip==null || _currentShipInfos==null) - { - Logger.LogError("AddSystemNodeLinkLog currentShip or currentShipInfos is null"); - return false; - } - WHJumpLog? jumpLog = null; + [Inject] + IEveMapperRealTimeService? RealTimeService {get;set;} = null!; - if(manuelJump) - jumpLog = await DbWHJumpLogs.Create(new WHJumpLog(whSystemLinkID,_characterId)); - else - jumpLog = await DbWHJumpLogs.Create(new WHJumpLog(whSystemLinkID,_characterId,_currentShip.ShipTypeId,_currentShip.ShipItemId,_currentShipInfos.Mass)); - - if(jumpLog==null) - { - Logger.LogError("AddSystemNodeLinkLog jumpLog is null"); - return false; - } + [Inject] + IWHMapRepository DbWHMaps { get; set; } = null!; - return true; + [Inject] + private IEveMapperTracker TrackerServices { get; set; } = null!; - } - private async Task AddSystemNodeLinkLog(WHSystemLink? link,bool isManual=false) - { - if(link==null) - { - Logger.LogError("AddSystemNodeLinkLog link is null"); - return false; - } + [Inject] + private IPasteServices PasteServices { get; set; } = null!; - return await AddSystemNodeLinkLog(link.Id,isManual); - } - private Task OnShipChanged(Ship ship,ShipEntity shipInfos) - { - _currentShip=ship; - _currentShipInfos=shipInfos; + private WHMap? _selectedWHMap = null!; - return Task.CompletedTask; + + protected override async Task OnInitializedAsync() + { + if (!await RestoreMaps()) + { + Snackbar?.Add("Mapper Initialization error", Severity.Error); } - private async Task OnSystemChanged(SystemEntity targetSoloarSystem) + if(!await InitRealTimeService()) { - EveSystemNodeModel? srcNode = null; - EveSystemNodeModel? targetNode = null; + Snackbar?.Add("RealTimeService Initialization error", Severity.Error); + } - if(_blazorDiagram==null || targetSoloarSystem==null) - { - Logger.LogError("Error Diagram or newSoloarSystem is nullable"); - return; - } + + _loading = false; + await base.OnInitializedAsync(); + } - if(_selectedWHMap==null) + private async Task RestoreMaps() + { + var allMaps = await DbWHMaps.GetAll(); + if (allMaps == null || !allMaps.Any()) + { + _selectedWHMap = await DbWHMaps.Create(new WHMap("Default Maps")); + if (_selectedWHMap != null) { - Logger.LogError("Error OnSystemChanged, selectedWHMap is nullable"); - return; + await RestoreMaps(); } - - await _semaphoreSlim.WaitAsync(); - try + } + else + { + WHMaps.Clear(); + var authState = await _authenticationStateProvider.GetAuthenticationStateAsync(); + + foreach (var map in allMaps) { - - if(_currentSolarSystem!=null) - { - srcNode = (EveSystemNodeModel?)(_blazorDiagram?.Nodes?.FirstOrDefault(x => ((EveSystemNodeModel)x).SolarSystemId == _currentSolarSystem.Id)); - } - targetNode = (EveSystemNodeModel?)(_blazorDiagram?.Nodes?.FirstOrDefault(x => ((EveSystemNodeModel)x).SolarSystemId == targetSoloarSystem.Id)); - - - if (targetNode== null)//System is not added + var authorizationResult = await _authorizationService.AuthorizeAsync(authState.User, map.Id, "Map"); + if (authorizationResult.Succeeded) { - if(await AddSystemNode(_selectedWHMap,_currentSolarSystem,targetSoloarSystem))//add system node if system is not added - { - if (_currentSolarSystem != null) - { - if(!await AddSystemNodeLink(_selectedWHMap, _currentSolarSystem, targetSoloarSystem))//create if new target system added from src - { - Logger.LogError("Add Wormhole Link error"); - Snackbar?.Add("Add Wormhole Link error", Severity.Error); - } - else - { - targetNode = (EveSystemNodeModel?)(_blazorDiagram?.Nodes?.FirstOrDefault(x => ((EveSystemNodeModel)x).SolarSystemId == targetSoloarSystem.Id)); - } - } - - await NotifyUserPosition(targetSoloarSystem.Name); - } - else - { - Logger.LogError("Add System Node error"); - Snackbar?.Add("Add System Node error", Severity.Error); - } + WHMaps.Add(map); } - else// tartget system already added - { - //check if link already exist, if not create if - if(srcNode!=null && !IsLinkExist(srcNode,targetNode)) - { - if((_currentSolarSystem==null) || (!await AddSystemNodeLink(_selectedWHMap, _currentSolarSystem, targetSoloarSystem)))//create if new target system added from src - { - Logger.LogError("Add Wormhole Link error"); - Snackbar?.Add("Add Wormhole Link error", Severity.Error); - } - } - else//log jump - { - if(srcNode!=null && targetNode!=null) - { - var link = GetLink(srcNode,targetNode); + } - if(link!=null && !await AddSystemNodeLinkLog(link.Id)) - { - Logger.LogError("Add Wormhole Link Log error"); - Snackbar?.Add("Add Wormhole Link Log error", Severity.Error); - } - } - } + _selectedWHMap = WHMaps.FirstOrDefault(); + } + if(allMaps!=null && allMaps.Any() && _selectedWHMap==null) + return true; + else + return _selectedWHMap != null; + } - srcNode?.RemoveConnectedUser(_userName); - targetNode?.AddConnectedUser(_userName); - await NotifyUserPosition(targetSoloarSystem.Name); + public async ValueTask DisposeAsync() + { + + if (TrackerServices != null) + { + await TrackerServices.StopTracking(); - } + } + } - _currentSolarSystem = targetSoloarSystem; - if(targetNode!=null) - _blazorDiagram?.SelectModel(targetNode, true); - } - catch (Exception ex) - { - Logger.LogError(ex, "On System Changed"); - } - finally + private async Task InitRealTimeService() + { + try + { + if(RealTimeService==null) { - _semaphoreSlim.Release(); + Logger.LogError("RealTimeService is null"); + return false; } + + RealTimeService.MapAdded += OnMapAdded; + RealTimeService.MapRemoved += OnMapRemoved; + RealTimeService.MapNameChanged += OnMapNameChanged; + RealTimeService.AllMapsRemoved += OnAllMapsRemoved; + RealTimeService.MapAccessesAdded+=OnMapAccessesAdded; + RealTimeService.MapAccessRemoved+=OnMapAccessRemoved; + RealTimeService.MapAllAccessesRemoved+=OnMapAllAccessesRemoved; + + return await RealTimeService.Start(); + } + catch (Exception ex) + { + Logger.LogError(ex, "InitRealTimeService error"); + return false; } + } - private async Task OnPasted(string? data) + #region RealTimeService User Events + + private async Task OnMapAdded(string user, int mapId) + { + try { - if((_selectedWHMap!=null) && (_selectedSystemNode!=null)) + var map = await DbWHMaps.GetById(mapId); + if (map != null) { - try - { - string scanUser = await UserInfos.GetUserName(); - if (await SignatureHelper.ImportScanResult(scanUser, _selectedSystemNode.IdWH, data,false)) - { - await WHSignaturesView.Restore(); - Snackbar?.Add("Signatures successfully added/updated", Severity.Success); - await NotifyWormholeSignaturesChanged(_selectedWHMap.Id, _selectedSystemNode.IdWH); - } - else - Snackbar?.Add("No signatures added/updated", Severity.Error); - } - catch(Exception ex) + var authState = await _authenticationStateProvider.GetAuthenticationStateAsync(); + var authorizationResult = await _authorizationService.AuthorizeAsync(authState.User, map.Id, "Map"); + if (authorizationResult.Succeeded) { - Logger.LogError(ex, "Handle Custom Paste error"); - Snackbar?.Add(ex.Message, Severity.Error); + WHMaps.Add(map); + Snackbar?.Add($"Map {map.Name} added", Severity.Info); + await InvokeAsync(StateHasChanged); } } } - public async ValueTask DisposeAsync() + catch (Exception ex) { - if(TrackerServices!=null) - { - await TrackerServices.StopTracking(); - TrackerServices.SystemChanged-=OnSystemChanged; - TrackerServices.ShipChanged-=OnShipChanged; - - } - if (_hubConnection!=null) - { - - await _hubConnection.StopAsync(); - await _hubConnection.DisposeAsync(); - } - - GC.SuppressFinalize(this); + Logger.LogError(ex, "On NotifyMapAdded error"); } - - private void OnWHSystemNodeLocked(EveSystemNodeModel whNodeModel) + } + private async Task OnMapRemoved(string user, int mapId) + { + try { - if (whNodeModel != null) + var map = WHMaps.FirstOrDefault(m => m.Id == mapId); + if (map != null) { - Task.Run(()=>NotifyWormholeLockChanged(whNodeModel.IdWHMap, whNodeModel.IdWH, whNodeModel.Locked)); + WHMaps.Remove(map); + Snackbar?.Add($"Map {map.Name} deleted", Severity.Info); + await InvokeAsync(StateHasChanged); } } - - private void OnWHSystemStatusChange(EveSystemNodeModel whNodeModel) + catch (Exception ex) { - if (whNodeModel != null) - { - Task.Run(()=>NotifyWormholeSystemStatusChanged(whNodeModel.IdWHMap, whNodeModel.IdWH, whNodeModel.SystemStatus)); - } + Logger.LogError(ex, "On NotifyMapDeleted error"); } + } - #region Menu Actions - - #region Selected Node Menu Actions - private async Task SetSelectedSystemDestinationWaypoint() + private async Task OnMapNameChanged(string user, int mapId, string newName) + { + try { - try - { - if(_selectedSystemNode==null) - { - Logger.LogError("Set system status error, no node selected"); - return false; - } - int solarSystemId = _selectedSystemNode.SolarSystemId; - if (solarSystemId>0) - { - await EveServices.UserInterfaceServices.SetWaypoint(solarSystemId, false, true); - return true; - - } - - return false; - } - catch (Exception ex) + var map = WHMaps.FirstOrDefault(m => m.Id == mapId); + if (map != null) { - Logger.LogError(ex, "Set destination waypoint error"); - return false; + map.Name = newName; + Snackbar?.Add($"Map {map.Name} renamed to {newName}", Severity.Info); + await InvokeAsync(StateHasChanged); } } - - private async Task ToggleSystemLock() + catch (Exception ex) { - try - { - if(_selectedSystemNode==null) - { - Logger.LogError("Set system status error, no node selected"); - return false; - } + Logger.LogError(ex, "On NotifyMapNameChanged error"); + } + } - var whSystem = await DbWHSystems.GetById(_selectedSystemNode.IdWH); - if (whSystem != null && whSystem.Id==_selectedSystemNode.IdWH) - { - whSystem.Locked = !whSystem.Locked; - whSystem = await DbWHSystems.Update(whSystem.Id, whSystem); - if (whSystem == null) - { - Logger.LogError("Update lock system status error"); - return false; - } - _selectedSystemNode.Locked = whSystem.Locked; - _selectedSystemNode.Refresh(); - return true; - } - else - { - return false; - } - } - catch (Exception ex) - { - Logger.LogError(ex, "Toggle system lock error"); - return false; - } - + private async Task OnAllMapsRemoved(string user) + { + try + { + WHMaps.Clear(); + Snackbar?.Add($"All maps deleted", Severity.Info); + await InvokeAsync(StateHasChanged); } - private async Task SetSelectedSystemStatus(WHSystemStatus systemStatus) + catch (Exception ex) { - try - { - if(_selectedSystemNode==null) - { - Logger.LogError("Set system status error, no node selected"); - return false; - } - int solarSystemId = _selectedSystemNode.SolarSystemId; - if (solarSystemId>0) - { - var note = await DbNotes.GetBySolarSystemId(solarSystemId); + Logger.LogError(ex, "On NotifyAllMapsRemoved error"); + } + } - if(note == null) - { - note = await DbNotes.Create(new WHNote(solarSystemId, systemStatus)); - } - else - { - note.SystemStatus = systemStatus; - note = await DbNotes.Update(note.Id, note); - } + private async Task OnMapAccessesAdded(string user, int mapId, IEnumerable accessId) + { + try + { + var authState = await _authenticationStateProvider.GetAuthenticationStateAsync(); - - if(note==null) - { - Logger.LogError("Could not update system status"); - return false; - } + var map = WHMaps.FirstOrDefault(m => m.Id == mapId); - _selectedSystemNode.SystemStatus = systemStatus; - _selectedSystemNode.Refresh(); - return true; - } - else - { - Logger.LogError("Set system status error, no node selected"); - return false; - } - } - catch (Exception ex) + var mapWithAccessUpdated = await DbWHMaps.GetById(mapId); + if(mapWithAccessUpdated==null) { - Logger.LogError(ex, "Set system status error"); - return false; + Logger.LogError("Map not found on NotifyMapAccessesAdded"); + Snackbar?.Add("Map not found on NotifyMapAccessesAdded", Severity.Error); + return; } - } - #endregion - private async Task ToggleSlectedSystemLinkEOL() - { - try + var authorizationResult = await _authorizationService.AuthorizeAsync(authState.User, mapWithAccessUpdated.Id, "Map"); + + + if(map!=null) { - if (_selectedWHMap!=null && _selectedSystemLink != null) + if (authorizationResult.Succeeded) { - WHSystemLink? link = await DbWHSystemLinks.GetById(_selectedSystemLink.Id); - if (link != null) + foreach (var accessIdToAdd in accessId) { - link.IsEndOfLifeConnection = !link.IsEndOfLifeConnection; - link = await DbWHSystemLinks.Update(_selectedSystemLink.Id, link); - if(link!=null) - { - _selectedSystemLink.IsEoL = link.IsEndOfLifeConnection; - _selectedSystemLink.Refresh(); - await NotifyLinkChanged(_selectedWHMap.Id, link.Id, link.IsEndOfLifeConnection, link.Size,link.MassStatus); - return true; - } - else + var accessToAdd = mapWithAccessUpdated.WHAccesses.FirstOrDefault(a => a.Id == accessIdToAdd); + if (accessToAdd != null) { - Logger.LogError("Toggle system link eol db error"); - return false; + if(map.WHAccesses.Any(a => a.Id == accessIdToAdd)) + { + continue; + } + map.WHAccesses.Add(accessToAdd); } } - else - { - return false; - } - } - else - { - return false; } } - catch(Exception ex) + else { - Logger.LogError(ex, "Toggle system link eol error"); - return false; - } + if (authorizationResult.Succeeded) + { + WHMaps.Add(mapWithAccessUpdated); + Snackbar?.Add($"Map {mapWithAccessUpdated.Name} added", Severity.Info); + await InvokeAsync(StateHasChanged); + } + } + } + catch (Exception ex) + { + Logger.LogError(ex, "On NotifyMapAccessesAdded error"); } + } - private async Task SetSelectedSystemLinkStatus(SystemLinkMassStatus massStatus) + private async Task OnMapAccessRemoved(string user, int mapId, int accessId) + { + try { - try + var map = WHMaps.FirstOrDefault(m => m.Id == mapId); + if (map != null) { - if (_selectedWHMap!=null && _selectedSystemLink != null) + var accessToRemove = map.WHAccesses.FirstOrDefault(a => a.Id == accessId); + if (accessToRemove != null) { - WHSystemLink? link = await DbWHSystemLinks.GetById(_selectedSystemLink.Id); - if (link != null) - { - link.MassStatus = massStatus; - link = await DbWHSystemLinks.Update(_selectedSystemLink.Id, link); - if(link!=null) - { - _selectedSystemLink.MassStatus = link.MassStatus; - _selectedSystemLink.Refresh(); - await NotifyLinkChanged(_selectedWHMap.Id, link.Id, link.IsEndOfLifeConnection, link.Size, link.MassStatus); - return true; - } - else - { - Logger.LogError("Set system link status db error"); - return false; - } - } - else + map.WHAccesses.Remove(accessToRemove); + + var authState = await _authenticationStateProvider.GetAuthenticationStateAsync(); + + var authorizationResult = await _authorizationService.AuthorizeAsync(authState.User, map.Id, "Map"); + if (!authorizationResult.Succeeded) { - return false; + WHMaps.Remove(map); + Snackbar?.Add($"Access has been removed from map {map.Name}", Severity.Info); + await InvokeAsync(StateHasChanged); } + } - else - { - return false; - } - } - catch(Exception ex) - { - Logger.LogError(ex, "System link status error"); - return false; } } + catch (Exception ex) + { + Logger.LogError(ex, "On NotifyMapAccessRemoved error"); + } + } - private async Task SetSelectedSystemLinkSize(SystemLinkSize size) + private async Task OnMapAllAccessesRemoved(string user, int mapId) + { + try { - try + var map = WHMaps.FirstOrDefault(m => m.Id == mapId); + if (map != null) { - if (_selectedWHMap!=null && _selectedSystemLink != null) + + map.WHAccesses.Clear(); + var authState = await _authenticationStateProvider.GetAuthenticationStateAsync(); + + var authorizationResult = await _authorizationService.AuthorizeAsync(authState.User, map.Id, "Map"); + if (!authorizationResult.Succeeded) { - WHSystemLink? link = await DbWHSystemLinks.GetById(_selectedSystemLink.Id); - if (link != null) - { - link.Size = size; - link = await DbWHSystemLinks.Update(_selectedSystemLink.Id, link); - if(link!=null) - { - //update link size on diagram (refresh link - _selectedSystemLink.Size = link.Size; - _selectedSystemLink.Refresh(); - await NotifyLinkChanged(_selectedWHMap.Id, link.Id, link.IsEndOfLifeConnection, link.Size, link.MassStatus); - - return true; - } - else - { - Logger.LogError("Set system link size db error"); - return false; - } - - } + WHMaps.Remove(map); + Snackbar?.Add($"All accesses removed from map {map.Name}", Severity.Info); + await InvokeAsync(StateHasChanged); } - - return false; - } - catch(Exception ex) - { - Logger.LogError(ex, "System link size error"); - return false; } } - - private async Task OpenSearchAndAddDialog(ItemClickEventArgs e) + catch (Exception ex) { - DialogOptions disableBackdropClick = new DialogOptions() - { - BackdropClick=false, - Position = DialogPosition.Center, - MaxWidth = MaxWidth.Medium, - FullWidth = true - }; - var parameters = new DialogParameters(); - parameters.Add("CurrentDiagram", _blazorDiagram); - parameters.Add("CurrentWHMap", _selectedWHMap); - parameters.Add("MouseX", e.MouseEvent.ClientX); - parameters.Add("MouseY", e.MouseEvent.ClientY); + Logger.LogError(ex, "On NotifyMapAllAccessesRemoved error"); + } + } - var dialog = await DialogService.ShowAsync("Search and Add System Dialog", parameters, disableBackdropClick); - DialogResult? result = await dialog.Result; + #endregion - if (result != null && !result.Canceled && result.Data != null) + #region Map Tab Events + private Task CloseMapTab(MudTabPanel panel) + { + if(panel!=null) { - int whAddedId = (int)result.Data; - if (_selectedWHMap!=null && whAddedId > 0) - await this.NotifyWormoleAdded(_selectedWHMap.Id, whAddedId); - else + int mapId = (int)panel.ID; + var map = WHMaps.FirstOrDefault(m => m.Id == mapId); + if(map!=null) { - Logger.LogError("OpenSearchAndAddDialog, unable to find selected map to notify wormhole added"); - Snackbar?.Add("Unable to find selected map to notify wormhole added", Severity.Warning); + WHMaps.Remove(map); + Logger.LogInformation($"Map {map.Name} closed"); + StateHasChanged(); } + } - - return true; - - } - #endregion - - -#if !DISABLE_MULTI_MAP - #region Tabs Actions - - [Authorize(Policy = "Access")] - private Task AddNewMap() - { return Task.CompletedTask; } - #endregion -#endif - } + #endregion + } \ No newline at end of file diff --git a/src/WHMapper/Pages/Mapper/Overview.razor b/src/WHMapper/Pages/Mapper/Overview.razor index 407d18ae..169bc4b8 100644 --- a/src/WHMapper/Pages/Mapper/Overview.razor +++ b/src/WHMapper/Pages/Mapper/Overview.razor @@ -6,136 +6,44 @@ @using Blazor.Diagrams.Components; @using Blazor.Diagrams.Algorithms; @using WHMapper.Models.Db.Enums; -@using Blazor.Diagrams.Components.Widgets; +@using Blazor.Diagrams.Components.Widgets; - - - - -@if (_selectedSystemLink == null && _selectedSystemNode == null) -{ - Add System -} - -@if (_selectedSystemLink != null) -{ - Toggle EOL - Status - - Normal - Critical - Verge - - - Size - - Small - Medium - Large - XLarge - - -} - -@if(_selectedSystemNode !=null) -{ - Set Destination - if(_selectedSystemNode.Locked) + - - -@if(_loading) +@if (_loading) { -} \ No newline at end of file +} diff --git a/src/WHMapper/Pages/Mapper/RoutePlanner/Add.cs b/src/WHMapper/Pages/Mapper/RoutePlanner/Add.cs deleted file mode 100644 index f5f4c589..00000000 --- a/src/WHMapper/Pages/Mapper/RoutePlanner/Add.cs +++ /dev/null @@ -1,123 +0,0 @@ - - -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Components; -using MudBlazor; -using WHMapper.Models.DTO.SDE; -using WHMapper.Repositories.WHSystems; -using WHMapper.Services.EveAPI; -using WHMapper.Services.EveMapper; -using WHMapper.Services.SDE; - -namespace WHMapper.Pages.Mapper.RoutePlanner -{ - - [Authorize(Policy = "Admin, Access")] - public partial class Add : ComponentBase - { - private const string MSG_SEARCH_ERROR = "Search System Error"; - private const string MSG_BAD_SOLAR_SYSTEM_NAME_ERROR = "Bad solar system name"; - private const string MSG_ADD_ROUTE_DB_ERROR = "Add route db error"; - - private MudForm _formRoutePlanner = null!; - private bool _formSuccessValidation = false; - - - [Inject] - public ILogger Logger { get; set; } = null!; - - [Inject] - private ISnackbar Snackbar { get; set; } = null!; - - [Inject] - private IEveMapperRoutePlannerHelper EveMapperRoutePlannerHelper{ get; set; } = null!; - - [Inject] - private IEveMapperSearch EveMapperSearch { get; set; } = null!; - - - - [CascadingParameter] - MudDialogInstance MudDialog { get; set; } = null!; - - private SDESolarSystem _searchResult = null!; - public bool _global=false; - - private SemaphoreSlim _semaphoreSlim = new SemaphoreSlim(1, 1); - - private async Task Submit() - { - await _formRoutePlanner.Validate(); - - if (_formRoutePlanner.IsValid) - { - await _semaphoreSlim.WaitAsync(); - try - { - if (_searchResult == null) - { - Logger.LogError(MSG_BAD_SOLAR_SYSTEM_NAME_ERROR); - Snackbar?.Add(MSG_BAD_SOLAR_SYSTEM_NAME_ERROR, Severity.Error); - return; - } - - var route = await EveMapperRoutePlannerHelper.AddRoute(_searchResult.SolarSystemID, _global); - - if (route == null) - { - Logger.LogError(MSG_ADD_ROUTE_DB_ERROR); - Snackbar?.Add(MSG_ADD_ROUTE_DB_ERROR, Severity.Error); - return; - } - - - Snackbar?.Add(String.Format("{0} route successfully added",_searchResult.Name), Severity.Success); - MudDialog.Close(DialogResult.Ok(route.Id)); - } - catch (Exception ex) - { - Snackbar?.Add(ex.Message, Severity.Error); - MudDialog.Close(DialogResult.Cancel); - } - finally - { - _semaphoreSlim.Release(); - } - } - else - { - Logger.LogError(MSG_BAD_SOLAR_SYSTEM_NAME_ERROR); - Snackbar?.Add(MSG_BAD_SOLAR_SYSTEM_NAME_ERROR, Severity.Error); - MudDialog.Close(DialogResult.Cancel); - } - } - private void Cancel() - { - MudDialog.Cancel(); - } - -/* - private async Task?> Search(string value,CancellationToken cancellationToken) - { - try - { - return await EveMapperSearch.SearchSystem(value,cancellationToken); - } - catch (OperationCanceledException) - { - Logger.LogInformation($"SearchSystem {value} cancelled"); - return null; - } - catch(Exception ex) - { - Logger.LogError(ex, MSG_SEARCH_ERROR); - Snackbar.Add(MSG_SEARCH_ERROR, Severity.Error); - return null; - } - }*/ - - } -} - - - diff --git a/src/WHMapper/Pages/Mapper/RoutePlanner/Add.razor b/src/WHMapper/Pages/Mapper/RoutePlanner/Add.razor deleted file mode 100644 index b659d92b..00000000 --- a/src/WHMapper/Pages/Mapper/RoutePlanner/Add.razor +++ /dev/null @@ -1,25 +0,0 @@ -@using WHMapper.Models.DTO.SDE - - - - - - - - - - - - - Cancel - Add Route - - - diff --git a/src/WHMapper/Pages/Mapper/RoutePlanner/Overview.cs b/src/WHMapper/Pages/Mapper/RoutePlanner/Overview.cs index 679a4bb0..db33f2ab 100644 --- a/src/WHMapper/Pages/Mapper/RoutePlanner/Overview.cs +++ b/src/WHMapper/Pages/Mapper/RoutePlanner/Overview.cs @@ -1,20 +1,21 @@ - -using System.Collections.Concurrent; -using System.Collections.Frozen; +using System.Collections.Frozen; using Blazor.Diagrams.Core.Layers; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Components; using MudBlazor; using WHMapper.Models.Custom.Node; using WHMapper.Models.DTO.EveAPI.Route.Enums; +using WHMapper.Models.DTO.EveMapper.EveEntity; using WHMapper.Models.DTO.RoutePlanner; -using WHMapper.Services.EveAPI; +using WHMapper.Pages.Mapper.Search; namespace WHMapper.Pages.Mapper.RoutePlanner { [Authorize(Policy = "Access")] public partial class Overview : ComponentBase { + private const string MSG_ADD_ROUTE_DB_ERROR = "Add route db error"; + private bool _loading =true; private IEnumerable? _myRoutes = null; private IEnumerable? _globalRoutes = null; @@ -53,28 +54,32 @@ private RouteType RType { private ILogger _logger {get;set;} = null!; [Parameter] - public EveSystemNodeModel CurrentSystemNode {get;set;} = null!; + public int? CurrentMapId { get; set; } = null!; + [Parameter] + public EveSystemNodeModel CurrentSystemNode {get;set;} = null!; + [Parameter] public LinkLayer CurrentLinks { get; set; } = null!; protected override Task OnParametersSetAsync() { - Task.Run(() => Restore()); + if(CurrentMapId.HasValue) + { + Task.Run(() => Restore()); + } return base.OnParametersSetAsync(); } - - private async Task Restore() { try { var currentSystem = CurrentSystemNode; var currentLinks = CurrentLinks; - if (currentSystem != null && currentLinks!=null) + if (currentSystem != null && currentLinks!=null && CurrentMapId.HasValue) { _loading=true; await InvokeAsync(() => { @@ -99,8 +104,8 @@ await InvokeAsync(() => { _logger.LogInformation("Restore routes from {0}", currentSystem.Name); - var globalRouteTmp= await EveMapperRoutePlannerHelper.GetRoutesForAll(currentSystem.SolarSystemId,RType,mapConnections); - var myRoutesTmp= await EveMapperRoutePlannerHelper.GetMyRoutes(currentSystem.SolarSystemId,RType,mapConnections); + var globalRouteTmp= await EveMapperRoutePlannerHelper.GetRoutesForAll(CurrentMapId.Value,currentSystem.SolarSystemId,RType,mapConnections); + var myRoutesTmp= await EveMapperRoutePlannerHelper.GetMyRoutes(CurrentMapId.Value,currentSystem.SolarSystemId,RType,mapConnections); if(_showedRoute!=null) { @@ -144,8 +149,15 @@ await InvokeAsync(() => { } } - private async Task AddRoute() + private async Task AddRoute(bool global) { + if(!CurrentMapId.HasValue) + { + _logger.LogError("No map selected"); + Snackbar.Add("No map selected", Severity.Error); + return; + } + DialogOptions disableBackdropClick = new DialogOptions() { BackdropClick=false, @@ -155,14 +167,34 @@ private async Task AddRoute() }; var parameters = new DialogParameters(); - var dialog = await DialogService.ShowAsync("Add Route", parameters, disableBackdropClick); + var dialog = await DialogService.ShowAsync("Search and Add Route Dialog", parameters, disableBackdropClick); DialogResult? result = await dialog.Result; - if (result != null && !result.Canceled) + if (result != null && !result.Canceled && result.Data != null) { - await Restore(); + if (CurrentMapId.HasValue && result.Data!=null) + { + SystemEntity solarSystem = (SystemEntity)result.Data; + var route = await EveMapperRoutePlannerHelper.AddRoute(CurrentMapId.Value,solarSystem.Id, global); + + if (route == null) + { + _logger.LogError(MSG_ADD_ROUTE_DB_ERROR); + Snackbar?.Add(MSG_ADD_ROUTE_DB_ERROR, Severity.Error); + return; + } + else + { + Snackbar?.Add(String.Format("{0} route successfully added",solarSystem.Name), Severity.Success); + await Restore(); + } + } + else + { + _logger.LogError("OpenSearchAndAddDialog, unable to find selected map to notify wormhole added"); + Snackbar?.Add("Unable to find selected map to notify wormhole added", Severity.Warning); + } } - StateHasChanged(); } private async Task DelRoute(EveRoute route) diff --git a/src/WHMapper/Pages/Mapper/RoutePlanner/Overview.razor b/src/WHMapper/Pages/Mapper/RoutePlanner/Overview.razor index 29ceb007..ed1acf6b 100644 --- a/src/WHMapper/Pages/Mapper/RoutePlanner/Overview.razor +++ b/src/WHMapper/Pages/Mapper/RoutePlanner/Overview.razor @@ -3,12 +3,20 @@ \ No newline at end of file diff --git a/src/WHMapper/Program.cs b/src/WHMapper/Program.cs index e058ca87..cd06a515 100644 --- a/src/WHMapper/Program.cs +++ b/src/WHMapper/Program.cs @@ -160,6 +160,9 @@ private static void Main(string[] args) options.AddPolicy("Admin", policy => policy.Requirements.Add(new EveMapperAdminRequirement())); + + options.AddPolicy("Map", policy => + policy.Requirements.Add(new EveMapperMapRequirement())); }); builder.Services.AddSingleton(provider => builder.Configuration); @@ -220,12 +223,14 @@ private static void Main(string[] args) builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); + builder.Services.AddScoped(); #endregion builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); + builder.Services.AddScoped(); diff --git a/src/WHMapper/Repositories/ADefaultRepository.cs b/src/WHMapper/Repositories/ADefaultRepository.cs index a3f79da1..776a2065 100644 --- a/src/WHMapper/Repositories/ADefaultRepository.cs +++ b/src/WHMapper/Repositories/ADefaultRepository.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; -using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; namespace WHMapper.Repositories { diff --git a/src/WHMapper/Repositories/WHAccesses/IWHAccessRepository.cs b/src/WHMapper/Repositories/WHAccesses/IWHAccessRepository.cs index 7be3025d..0fc6376d 100644 --- a/src/WHMapper/Repositories/WHAccesses/IWHAccessRepository.cs +++ b/src/WHMapper/Repositories/WHAccesses/IWHAccessRepository.cs @@ -1,9 +1,8 @@ -using System; -using WHMapper.Models.Db; +using WHMapper.Models.Db; namespace WHMapper.Repositories.WHAccesses { - public interface IWHAccessRepository : IDefaultRepository + public interface IWHAccessRepository : IDefaultRepository { } } diff --git a/src/WHMapper/Repositories/WHAccesses/WHAccessRepository.cs b/src/WHMapper/Repositories/WHAccesses/WHAccessRepository.cs index ba56c47a..38f9b6e5 100644 --- a/src/WHMapper/Repositories/WHAccesses/WHAccessRepository.cs +++ b/src/WHMapper/Repositories/WHAccesses/WHAccessRepository.cs @@ -1,10 +1,6 @@ -using System; -using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; using WHMapper.Data; using WHMapper.Models.Db; -using WHMapper.Repositories.WHAdmins; -using WHMapper.Services.EveAPI; -using static MudBlazor.CategoryTypes; namespace WHMapper.Repositories.WHAccesses { diff --git a/src/WHMapper/Repositories/WHAdmins/IWHAdminRepository.cs b/src/WHMapper/Repositories/WHAdmins/IWHAdminRepository.cs index 5a983aa2..5854927b 100644 --- a/src/WHMapper/Repositories/WHAdmins/IWHAdminRepository.cs +++ b/src/WHMapper/Repositories/WHAdmins/IWHAdminRepository.cs @@ -1,9 +1,8 @@ -using System; -using WHMapper.Models.Db; +using WHMapper.Models.Db; namespace WHMapper.Repositories.WHAdmins { - public interface IWHAdminRepository : IDefaultRepository + public interface IWHAdminRepository : IDefaultRepository { } } diff --git a/src/WHMapper/Repositories/WHAdmins/WHAdminRepository.cs b/src/WHMapper/Repositories/WHAdmins/WHAdminRepository.cs index 18865fb6..e446609b 100644 --- a/src/WHMapper/Repositories/WHAdmins/WHAdminRepository.cs +++ b/src/WHMapper/Repositories/WHAdmins/WHAdminRepository.cs @@ -1,14 +1,10 @@ -using System; -using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; using WHMapper.Data; using WHMapper.Models.Db; -using WHMapper.Repositories.WHAccesses; -using WHMapper.Repositories.WHMaps; -using static MudBlazor.CategoryTypes; namespace WHMapper.Repositories.WHAdmins { - public class WHAdminRepository : ADefaultRepository, IWHAdminRepository + public class WHAdminRepository : ADefaultRepository, IWHAdminRepository { public WHAdminRepository(ILogger logger,IDbContextFactory context) : base(logger,context) diff --git a/src/WHMapper/Repositories/WHJumpLogs/WHJumpLogRepository.cs b/src/WHMapper/Repositories/WHJumpLogs/WHJumpLogRepository.cs index cfc38cae..c73ef5d4 100644 --- a/src/WHMapper/Repositories/WHJumpLogs/WHJumpLogRepository.cs +++ b/src/WHMapper/Repositories/WHJumpLogs/WHJumpLogRepository.cs @@ -1,8 +1,6 @@ using Microsoft.EntityFrameworkCore; using WHMapper.Data; using WHMapper.Models.Db; -using WHMapper.Repositories; -using WHMapper.Repositories.WHJumpLogs; namespace WHMapper.Repositories.WHJumpLogs { diff --git a/src/WHMapper/Repositories/WHMaps/IWHMapRepository.cs b/src/WHMapper/Repositories/WHMaps/IWHMapRepository.cs index 9b3f4f5f..ec4f29c7 100644 --- a/src/WHMapper/Repositories/WHMaps/IWHMapRepository.cs +++ b/src/WHMapper/Repositories/WHMaps/IWHMapRepository.cs @@ -1,10 +1,15 @@ -using System; -using WHMapper.Models.Db; +using WHMapper.Models.Db; namespace WHMapper.Repositories.WHMaps { public interface IWHMapRepository : IDefaultRepository { + Task GetByNameAsync(string mapName); + Task DeleteAll(); + Task?> GetMapAccesses(int id); + Task DeleteMapAccess(int mapId, int accessId); + Task DeleteMapAccesses(int mapId); + Task AddMapAccess(int mapId, int accessId); } } diff --git a/src/WHMapper/Repositories/WHMaps/WHMapRepository.cs b/src/WHMapper/Repositories/WHMaps/WHMapRepository.cs index d024908d..fd479bbd 100644 --- a/src/WHMapper/Repositories/WHMaps/WHMapRepository.cs +++ b/src/WHMapper/Repositories/WHMaps/WHMapRepository.cs @@ -1,11 +1,6 @@ -using System; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Logging; -using Microsoft.IdentityModel.Logging; +using Microsoft.EntityFrameworkCore; using WHMapper.Data; using WHMapper.Models.Db; -using WHMapper.Repositories.WHAccesses; -using static MudBlazor.CategoryTypes; namespace WHMapper.Repositories.WHMaps { @@ -17,6 +12,41 @@ public WHMapRepository(ILogger logger, IDbContextFactory DeleteAll() + { + using (var context = _contextFactory.CreateDbContext()) + { + var deleteRow = await context.DbWHMaps.ExecuteDeleteAsync(); + if (deleteRow > 0) + return true; + else + return false; + } + } + + + public async Task GetByNameAsync(string mapName) + { + using (var context = await _contextFactory.CreateDbContextAsync()) + { + try + { + return await context.DbWHMaps.SingleOrDefaultAsync(x => x.Name == mapName); + + } + catch (Exception ex) + { + _logger.LogError(ex, "Impossible to get WHMap by name : {Name}", mapName); + return null; + } + } + + + } + + protected override async Task ACreate(WHMap item) { using (var context = await _contextFactory.CreateDbContextAsync()) @@ -56,11 +86,13 @@ protected override async Task ADeleteById(int id) if (!await context.DbWHMaps.AnyAsync()) return await context.DbWHMaps.OrderBy(x => x.Name).ToListAsync(); else - return await context.DbWHMaps - .Include(x => x.WHSystems) - .Include(x => x.WHSystemLinks) - .ThenInclude(x => x.JumpHistory) - .OrderBy(x => x.Name).ToListAsync(); + return await context.DbWHMaps.AsNoTracking() + .Include(x => x.WHAccesses) + //.Include(x => x.WHSystems) + //.Include(x => x.WHSystemLinks) + // .ThenInclude(x => x.JumpHistory) + .OrderBy(x => x.Name) + .ToListAsync(); } } @@ -68,11 +100,12 @@ protected override async Task ADeleteById(int id) { using (var context = await _contextFactory.CreateDbContextAsync()) { - return await context.DbWHMaps + return await context.DbWHMaps.AsNoTracking() + .Include(x => x.WHAccesses) .Include(x => x.WHSystems) .Include(x => x.WHSystemLinks) .ThenInclude(x => x.JumpHistory) - .SingleOrDefaultAsync(x => x.Id == id);; + .SingleOrDefaultAsync(x => x.Id == id); } } @@ -96,6 +129,74 @@ protected override async Task ADeleteById(int id) } } } + + public async Task?> GetMapAccesses(int id) + { + using (var context = await _contextFactory.CreateDbContextAsync()) + { + var map = await context.DbWHMaps.AsNoTracking() + .Include(x => x.WHAccesses) + .SingleOrDefaultAsync(x => x.Id == id); + + if (map == null) + return null; + else + return map.WHAccesses; + } + } + + public async Task DeleteMapAccess(int mapId, int accessId) + { + using (var context = await _contextFactory.CreateDbContextAsync()) + { + var map = await context.DbWHMaps.Include(x => x.WHAccesses).SingleOrDefaultAsync(x => x.Id == mapId); + if (map == null) + return false; + + var access = map.WHAccesses.SingleOrDefault(x => x.Id == accessId); + if (access == null) + return false; + + map.WHAccesses.Remove(access); + await context.SaveChangesAsync(); + return true; + } + } + + public async Task DeleteMapAccesses(int mapId) + { + using (var context = await _contextFactory.CreateDbContextAsync()) + { + var map = await context.DbWHMaps.Include(x => x.WHAccesses).SingleOrDefaultAsync(x => x.Id == mapId); + if (map == null) + return false; + + map.WHAccesses.Clear(); + await context.SaveChangesAsync(); + return true; + } + } + + public async Task AddMapAccess(int mapId, int accessId) + { + using (var context = await _contextFactory.CreateDbContextAsync()) + { + var map = await context.DbWHMaps.Include(x => x.WHAccesses).SingleOrDefaultAsync(x => x.Id == mapId); + if (map == null) + return false; + + var access = await context.DbWHAccesses.SingleOrDefaultAsync(x => x.Id == accessId); + if (access == null) + return false; + + map.WHAccesses.Add(access); + await context.SaveChangesAsync(); + return true; + } + } + + + } } diff --git a/src/WHMapper/Repositories/WHNotes/IWHNoteRepository.cs b/src/WHMapper/Repositories/WHNotes/IWHNoteRepository.cs index c2526989..ae34fdd8 100644 --- a/src/WHMapper/Repositories/WHNotes/IWHNoteRepository.cs +++ b/src/WHMapper/Repositories/WHNotes/IWHNoteRepository.cs @@ -1,11 +1,10 @@ -using System; -using WHMapper.Models.Db; +using WHMapper.Models.Db; namespace WHMapper.Repositories.WHNotes { - public interface IWHNoteRepository : IDefaultRepository + public interface IWHNoteRepository : IDefaultRepository { - public Task GetBySolarSystemId(int solardSystemId); + public Task Get(int mapId,int solardSystemId); } } diff --git a/src/WHMapper/Repositories/WHNotes/WHNoteRepository.cs b/src/WHMapper/Repositories/WHNotes/WHNoteRepository.cs index 6dd26757..205ccf13 100644 --- a/src/WHMapper/Repositories/WHNotes/WHNoteRepository.cs +++ b/src/WHMapper/Repositories/WHNotes/WHNoteRepository.cs @@ -1,13 +1,10 @@ -using System; -using System.Xml.Linq; -using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; using WHMapper.Data; using WHMapper.Models.Db; -using WHMapper.Repositories.WHSystems; namespace WHMapper.Repositories.WHNotes { - public class WHNoteRepository : ADefaultRepository, IWHNoteRepository + public class WHNoteRepository : ADefaultRepository, IWHNoteRepository { public WHNoteRepository(ILogger logger, IDbContextFactory context) : base(logger, context) @@ -93,11 +90,11 @@ protected override async Task ADeleteById(int id) } } - public async Task GetBySolarSystemId(int solardSystemId) + public async Task Get(int mapid,int solardSystemId) { using (var context = await _contextFactory.CreateDbContextAsync()) { - return await context.DbWHNotes.SingleOrDefaultAsync(x => x.SoloarSystemId == solardSystemId); + return await context.DbWHNotes.SingleOrDefaultAsync(x => x.SoloarSystemId == solardSystemId && x.MapId == mapid); } } } diff --git a/src/WHMapper/Repositories/WHRoutes/IWHRouteRepository.cs b/src/WHMapper/Repositories/WHRoutes/IWHRouteRepository.cs index 059b69be..81237985 100644 --- a/src/WHMapper/Repositories/WHRoutes/IWHRouteRepository.cs +++ b/src/WHMapper/Repositories/WHRoutes/IWHRouteRepository.cs @@ -4,7 +4,7 @@ namespace WHMapper; public interface IWHRouteRepository : IDefaultRepository { - Task> GetRoutesByEveEntityId(int eveEntityId); - Task> GetRoutesForAll(); + Task> GetRoutesByEveEntityId(int mapId,int eveEntityId); + Task> GetRoutesForAll(int mapId); } diff --git a/src/WHMapper/Repositories/WHRoutes/WHRouteRepository.cs b/src/WHMapper/Repositories/WHRoutes/WHRouteRepository.cs index 9cb38d46..cc552ba2 100644 --- a/src/WHMapper/Repositories/WHRoutes/WHRouteRepository.cs +++ b/src/WHMapper/Repositories/WHRoutes/WHRouteRepository.cs @@ -12,19 +12,19 @@ public WHRouteRepository(ILogger logger, IDbContextFactory> GetRoutesByEveEntityId(int eveEntityId) + public async Task> GetRoutesByEveEntityId(int mapId,int eveEntityId) { using (var context = await _contextFactory.CreateDbContextAsync()) { - return await context.DbWHRoutes.Where(x => x.EveEntityId == eveEntityId).ToListAsync(); + return await context.DbWHRoutes.Where(x => x.MapId==mapId && x.EveEntityId == eveEntityId).ToListAsync(); } } - public async Task> GetRoutesForAll() + public async Task> GetRoutesForAll(int mapId) { using (var context = await _contextFactory.CreateDbContextAsync()) { - return await context.DbWHRoutes.Where(x => x.EveEntityId==null).ToListAsync(); + return await context.DbWHRoutes.Where(x => x.MapId==mapId && x.EveEntityId==null).ToListAsync(); } } diff --git a/src/WHMapper/Repositories/WHSignatures/IWHSignatureRepository.cs b/src/WHMapper/Repositories/WHSignatures/IWHSignatureRepository.cs index 0f3d109b..7c7dcabb 100644 --- a/src/WHMapper/Repositories/WHSignatures/IWHSignatureRepository.cs +++ b/src/WHMapper/Repositories/WHSignatures/IWHSignatureRepository.cs @@ -1,5 +1,4 @@ -using System; -using WHMapper.Models.Db; +using WHMapper.Models.Db; namespace WHMapper.Repositories.WHSignatures { diff --git a/src/WHMapper/Repositories/WHSignatures/WHSignatureRepository.cs b/src/WHMapper/Repositories/WHSignatures/WHSignatureRepository.cs index ecd4e409..04dcc4e2 100644 --- a/src/WHMapper/Repositories/WHSignatures/WHSignatureRepository.cs +++ b/src/WHMapper/Repositories/WHSignatures/WHSignatureRepository.cs @@ -1,10 +1,6 @@ -using System; -using Microsoft.EntityFrameworkCore; -using Microsoft.IdentityModel.Logging; +using Microsoft.EntityFrameworkCore; using WHMapper.Data; using WHMapper.Models.Db; -using WHMapper.Repositories.WHAccesses; -using static MudBlazor.CategoryTypes; namespace WHMapper.Repositories.WHSignatures diff --git a/src/WHMapper/Repositories/WHSystemLinks/IWHSystemLinkRepository.cs b/src/WHMapper/Repositories/WHSystemLinks/IWHSystemLinkRepository.cs index 904dc1f3..53e8d528 100644 --- a/src/WHMapper/Repositories/WHSystemLinks/IWHSystemLinkRepository.cs +++ b/src/WHMapper/Repositories/WHSystemLinks/IWHSystemLinkRepository.cs @@ -1,9 +1,8 @@ -using System; -using WHMapper.Models.Db; +using WHMapper.Models.Db; namespace WHMapper.Repositories.WHSystemLinks { - public interface IWHSystemLinkRepository : IDefaultRepository + public interface IWHSystemLinkRepository : IDefaultRepository { } } diff --git a/src/WHMapper/Repositories/WHSystemLinks/WHSystemLinkRepository.cs b/src/WHMapper/Repositories/WHSystemLinks/WHSystemLinkRepository.cs index 4545ddbd..b48030ac 100644 --- a/src/WHMapper/Repositories/WHSystemLinks/WHSystemLinkRepository.cs +++ b/src/WHMapper/Repositories/WHSystemLinks/WHSystemLinkRepository.cs @@ -1,11 +1,6 @@ -using System; -using Microsoft.EntityFrameworkCore; -using Microsoft.IdentityModel.Logging; +using Microsoft.EntityFrameworkCore; using WHMapper.Data; using WHMapper.Models.Db; -using WHMapper.Repositories.WHAccesses; -using WHMapper.Repositories.WHSystems; -using static MudBlazor.CategoryTypes; namespace WHMapper.Repositories.WHSystemLinks { diff --git a/src/WHMapper/Repositories/WHSystems/IWHSystemRepository.cs b/src/WHMapper/Repositories/WHSystems/IWHSystemRepository.cs index 91b88bcd..00ed4c50 100644 --- a/src/WHMapper/Repositories/WHSystems/IWHSystemRepository.cs +++ b/src/WHMapper/Repositories/WHSystems/IWHSystemRepository.cs @@ -1,6 +1,4 @@ -using System; -using System.Threading.Tasks; -using WHMapper.Models.Db; +using WHMapper.Models.Db; namespace WHMapper.Repositories.WHSystems { diff --git a/src/WHMapper/Repositories/WHSystems/WHSystemRepository.cs b/src/WHMapper/Repositories/WHSystems/WHSystemRepository.cs index 8e7fd59d..94b282e4 100644 --- a/src/WHMapper/Repositories/WHSystems/WHSystemRepository.cs +++ b/src/WHMapper/Repositories/WHSystems/WHSystemRepository.cs @@ -1,12 +1,6 @@ -using System; -using System.Security.Cryptography.Xml; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Logging; +using Microsoft.EntityFrameworkCore; using WHMapper.Data; using WHMapper.Models.Db; -using WHMapper.Repositories.WHAccesses; -using YamlDotNet.Core; -using static MudBlazor.CategoryTypes; namespace WHMapper.Repositories.WHSystems { diff --git a/src/WHMapper/Services/EveMapper/AuthorizationPolicies/EveMapperMapHandler.cs b/src/WHMapper/Services/EveMapper/AuthorizationPolicies/EveMapperMapHandler.cs new file mode 100644 index 00000000..25c0ff16 --- /dev/null +++ b/src/WHMapper/Services/EveMapper/AuthorizationPolicies/EveMapperMapHandler.cs @@ -0,0 +1,50 @@ +using Microsoft.AspNetCore.Authorization; +using System; +using System.Security.Claims; + +namespace WHMapper.Services.EveMapper.AuthorizationPolicies; + +public class EveMapperMapHandler: AuthorizationHandler +{ + + private readonly IEveMapperAccessHelper _eveMapperAccessHelper; + + public EveMapperMapHandler(IEveMapperAccessHelper eveMapperAccessHelper) + { + _eveMapperAccessHelper = eveMapperAccessHelper; + } + + protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, EveMapperMapRequirement requirement) + { + var characterId = context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? string.Empty; + + if (string.IsNullOrEmpty(characterId)) + return; + + var pendingRequirements = context.PendingRequirements.ToList(); + if (pendingRequirements.Count > 0) + { + foreach (var pendingRequirement in pendingRequirements) + { + if (pendingRequirement is EveMapperMapRequirement) + { + // get mapId from resource, passed in from blazor + // page component + var resource = context.Resource?.ToString(); + var hasParsed = int.TryParse(resource, out int mapId); + + if (hasParsed) + { + // check if user has access to map + if (await _eveMapperAccessHelper.IsEveMapperMapAccessAuthorized(Convert.ToInt32(characterId),mapId)) + context.Succeed(requirement); + } + } + } + } + + + + return; + } +} diff --git a/src/WHMapper/Services/EveMapper/AuthorizationPolicies/EveMapperMapRequirement.cs b/src/WHMapper/Services/EveMapper/AuthorizationPolicies/EveMapperMapRequirement.cs new file mode 100644 index 00000000..b69fe52e --- /dev/null +++ b/src/WHMapper/Services/EveMapper/AuthorizationPolicies/EveMapperMapRequirement.cs @@ -0,0 +1,11 @@ +using Microsoft.AspNetCore.Authorization; +using System; + +namespace WHMapper.Services.EveMapper.AuthorizationPolicies; + +public class EveMapperMapRequirement: IAuthorizationRequirement +{ + public EveMapperMapRequirement() + { + } +} diff --git a/src/WHMapper/Services/EveMapper/EveMapperAccessHelper.cs b/src/WHMapper/Services/EveMapper/EveMapperAccessHelper.cs index 0c901ca1..2bfdd4cc 100644 --- a/src/WHMapper/Services/EveMapper/EveMapperAccessHelper.cs +++ b/src/WHMapper/Services/EveMapper/EveMapperAccessHelper.cs @@ -1,6 +1,7 @@ using WHMapper.Models.Db.Enums; using WHMapper.Repositories.WHAccesses; using WHMapper.Repositories.WHAdmins; +using WHMapper.Repositories.WHMaps; using WHMapper.Services.EveAPI.Characters; namespace WHMapper.Services.EveMapper @@ -10,11 +11,13 @@ public class EveMapperAccessHelper : IEveMapperAccessHelper private readonly IWHAccessRepository _accessRepo; private readonly IWHAdminRepository _adminRepo; private readonly ICharacterServices _characterServices; + private readonly IWHMapRepository _mapRepo; - public EveMapperAccessHelper(IWHAccessRepository accessRepo, IWHAdminRepository adminRepo, ICharacterServices eveCharacterServices) + public EveMapperAccessHelper(IWHAccessRepository accessRepo, IWHAdminRepository adminRepo,IWHMapRepository mapRepo, ICharacterServices eveCharacterServices) { _accessRepo = accessRepo; _adminRepo = adminRepo; + _mapRepo = mapRepo; _characterServices = eveCharacterServices; } @@ -64,5 +67,37 @@ public async Task IsEveMapperAdminAccessAuthorized(int eveCharacterId) return true; } } + + public async Task IsEveMapperMapAccessAuthorized(int eveCharacterId, int mapId) + { + var userAccesses = await _accessRepo.GetAll(); + + //If there is no user access registered return true, this is the probably the first user using the tool. + if (userAccesses?.Count() == 0) + { + return true; + } + else + { + var character = await _characterServices.GetCharacter(eveCharacterId); + if (character == null) + return false; + + var mapAccess = await _mapRepo.GetMapAccesses(mapId); + + if (mapAccess == null || !mapAccess.Any()) + return false; + else + { + if(mapAccess.FirstOrDefault(x => + (x.EveEntityId == eveCharacterId && x.EveEntity == WHAccessEntity.Character) || + (x.EveEntityId == character.CorporationId && x.EveEntity == WHAccessEntity.Corporation) || + (x.EveEntityId == character.AllianceId && x.EveEntity == WHAccessEntity.Alliance)) == null) + return false; + else + return true; + } + } + } } } diff --git a/src/WHMapper/Services/EveMapper/EveMapperHelper.cs b/src/WHMapper/Services/EveMapper/EveMapperHelper.cs index bf500d95..6039e2e0 100644 --- a/src/WHMapper/Services/EveMapper/EveMapperHelper.cs +++ b/src/WHMapper/Services/EveMapper/EveMapperHelper.cs @@ -674,7 +674,9 @@ public async Task DefineEveSystemNodeModel(WHSystem wh) if (system_region == null) throw new InvalidDataException("Region not found"); - var note = await _noteServices.GetBySolarSystemId(system.Id); + + + var note = await _noteServices.Get(wh.WHMapId,system.Id); if (IsWormhole(wh.Name))//WH system { diff --git a/src/WHMapper/Services/EveMapper/EveMapperRealTimeService.cs b/src/WHMapper/Services/EveMapper/EveMapperRealTimeService.cs new file mode 100644 index 00000000..43c2c8fd --- /dev/null +++ b/src/WHMapper/Services/EveMapper/EveMapperRealTimeService.cs @@ -0,0 +1,421 @@ +using Microsoft.AspNetCore.Components; +using Microsoft.AspNetCore.SignalR.Client; +using WHMapper.Models.Db.Enums; +using WHMapper.Models.DTO; + +namespace WHMapper.Services.EveMapper; + +public class EveMapperRealTimeService : IEveMapperRealTimeService +{ + private readonly HubConnection _hubConnection; + private readonly ILogger _logger; + private readonly TokenProvider _tokenProvider; + private readonly NavigationManager _navigation; + + public event Func? UserConnected; + public event Func? UserDisconnected; + public event Func? UserPosition; + public event Func? WormholeAdded; + public event Func? WormholeRemoved; + public event Func? LinkAdded; + public event Func? LinkRemoved; + public event Func? WormholeMoved; + public event Func? LinkChanged; + public event Func? WormholeNameExtensionChanged; + public event Func? WormholeSignaturesChanged; + public event Func? WormholeLockChanged; + public event Func? WormholeSystemStatusChanged; + public event Func? MapAdded; + public event Func? MapRemoved; + public event Func? MapNameChanged; + public event Func? AllMapsRemoved; + public event Func, Task>? MapAccessesAdded; + public event Func? MapAccessRemoved; + public event Func? MapAllAccessesRemoved; + public event Func? UserOnMapConnected; + public event Func? UserOnMapDisconnected; + + public bool IsConnected => _hubConnection?.State == HubConnectionState.Connected; + + public EveMapperRealTimeService(ILogger logger, NavigationManager navigation, TokenProvider tokenProvider) + { + _logger = logger; + _tokenProvider = tokenProvider; + _navigation = navigation; + + _hubConnection = new HubConnectionBuilder() + .WithUrl(_navigation.ToAbsoluteUri("/whmappernotificationhub"), options => + { + options.AccessTokenProvider = () => Task.FromResult(_tokenProvider.AccessToken); + }).Build(); + + RegisterHubEvents(); + } + + private void RegisterHubEvents() + { + _hubConnection.On("NotifyUserConnected", async (user) => + { + if (UserConnected != null) + { + await UserConnected.Invoke(user); + } + }); + _hubConnection.On("NotifyUserDisconnected", async (user) => + { + if (UserDisconnected != null) + { + await UserDisconnected.Invoke(user); + } + }); + _hubConnection.On("NotifyUserPosition", async (user, mapId,wormholeId) => + { + if (UserPosition != null) + { + await UserPosition.Invoke(user, mapId,wormholeId); + } + }); + _hubConnection.On("NotifyWormoleAdded", async (user, mapId, wormholeId) => + { + if (WormholeAdded != null) + { + await WormholeAdded.Invoke(user, mapId, wormholeId); + } + }); + _hubConnection.On("NotifyWormholeRemoved", async (user, mapId, wormholeId) => + { + if (WormholeRemoved != null) + { + await WormholeRemoved.Invoke(user, mapId, wormholeId); + } + }); + _hubConnection.On("NotifyLinkAdded", async (user, mapId, linkId) => + { + if (LinkAdded != null) + { + await LinkAdded.Invoke(user, mapId, linkId); + } + }); + _hubConnection.On("NotifyLinkRemoved", async (user, mapId, linkId) => + { + if (LinkRemoved != null) + { + await LinkRemoved.Invoke(user, mapId, linkId); + } + }); + _hubConnection.On("NotifyWormoleMoved", async (user, mapId, wormholeId, posX, posY) => + { + if (WormholeMoved != null) + { + await WormholeMoved.Invoke(user, mapId, wormholeId, posX, posY); + } + }); + _hubConnection.On("NotifyLinkChanged", async (user, mapId, linkId, eol, size, mass) => + { + if (LinkChanged != null) + { + await LinkChanged.Invoke(user, mapId, linkId, eol, size, mass); + } + }); + _hubConnection.On("NotifyWormholeNameExtensionChanged", async (user, mapId, wormholeId, increment) => + { + if (WormholeNameExtensionChanged != null) + { + await WormholeNameExtensionChanged.Invoke(user, mapId, wormholeId, increment); + } + }); + _hubConnection.On("NotifyWormholeSignaturesChanged", async (user, mapId, wormholeId) => + { + if (WormholeSignaturesChanged != null) + { + await WormholeSignaturesChanged.Invoke(user, mapId, wormholeId); + } + }); + _hubConnection.On("NotifyWormholeLockChanged", async (user, mapId, wormholeId, locked) => + { + if (WormholeLockChanged != null) + { + await WormholeLockChanged.Invoke(user, mapId, wormholeId, locked); + } + }); + _hubConnection.On("NotifyWormholeSystemStatusChanged", async (user, mapId, wormholeId, systemStatus) => + { + if (WormholeSystemStatusChanged != null) + { + await WormholeSystemStatusChanged.Invoke(user, mapId, wormholeId, systemStatus); + } + }); + _hubConnection.On("NotifyMapAdded", async (user, mapId) => + { + if (MapAdded != null) + { + await MapAdded.Invoke(user, mapId); + } + }); + _hubConnection.On("NotifyMapRemoved", async (user, mapId) => + { + if (MapRemoved != null) + { + await MapRemoved.Invoke(user, mapId); + } + }); + _hubConnection.On("NotifyMapNameChanged", async (user, mapId, newName) => + { + if (MapNameChanged != null) + { + await MapNameChanged.Invoke(user, mapId, newName); + } + }); + _hubConnection.On("NotifyAllMapsRemoved", async (user) => + { + if (AllMapsRemoved != null) + { + await AllMapsRemoved.Invoke(user); + } + }); + _hubConnection.On>("NotifyMapAccessesAdded", async (user, mapId, accessId) => + { + if (MapAccessesAdded != null) + { + await MapAccessesAdded.Invoke(user, mapId, accessId); + } + }); + + _hubConnection.On("NotifyMapAccessRemoved", async (user, mapId, accessId) => + { + if (MapAccessRemoved != null) + { + await MapAccessRemoved.Invoke(user, mapId, accessId); + } + }); + + _hubConnection.On("NotifyMapAllAccessesRemoved", async (user, mapId) => + { + if (MapAllAccessesRemoved != null) + { + await MapAllAccessesRemoved.Invoke(user, mapId); + } + }); + _hubConnection.On("NotifyUserOnMapConnected", async (user, mapId) => + { + if (UserOnMapConnected != null) + { + await UserOnMapConnected.Invoke(user, mapId); + } + }); + _hubConnection.On("NotifyUserOnMapDisconnected", async (user, mapId) => + { + if (UserOnMapDisconnected != null) + { + await UserOnMapDisconnected.Invoke(user, mapId); + } + }); + } + + public async Task Start() + { + try + { + await _hubConnection.StartAsync(); + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to start the real-time service."); + return false; + } + } + + public async Task Stop() + { + try + { + await _hubConnection.StopAsync(); + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to stop the real-time service."); + return false; + } + } + + public async Task NotifyUserPosition(int mapId,int wormholeId) + { + if (_hubConnection is not null) + { + await _hubConnection.SendAsync("SendUserPosition", mapId, wormholeId); + } + } + + public async Task NotifyWormoleAdded(int mapId, int wormholeId) + { + if (_hubConnection is not null) + { + await _hubConnection.SendAsync("SendWormholeAdded", mapId, wormholeId); + } + } + + public async Task NotifyWormholeRemoved(int mapId, int wormholeId) + { + if (_hubConnection is not null) + { + await _hubConnection.SendAsync("SendWormholeRemoved", mapId, wormholeId); + } + } + + public async Task NotifyLinkAdded(int mapId, int linkId) + { + if (_hubConnection is not null) + { + await _hubConnection.SendAsync("SendLinkAdded", mapId, linkId); + } + } + + public async Task NotifyLinkRemoved(int mapId, int linkId) + { + if (_hubConnection is not null) + { + await _hubConnection.SendAsync("SendLinkRemoved", mapId, linkId); + } + } + + public async Task NotifyWormholeMoved(int mapId, int wormholeId, double posX, double posY) + { + if (_hubConnection is not null) + { + await _hubConnection.SendAsync("SendWormholeMoved", mapId, wormholeId, posX, posY); + } + } + + public async Task NotifyLinkChanged(int mapId, int linkId, bool eol, SystemLinkSize size, SystemLinkMassStatus mass) + { + if (_hubConnection is not null) + { + await _hubConnection.SendAsync("SendLinkChanged", mapId, linkId, eol, size, mass); + } + } + + public async Task NotifyWormholeNameExtensionChanged(int mapId, int wormholeId, bool increment) + { + if (_hubConnection is not null) + { + await _hubConnection.SendAsync("SendWormholeNameExtensionChanged", mapId, wormholeId, increment); + } + } + + public async Task NotifyWormholeSignaturesChanged(int mapId, int wormholeId) + { + if (_hubConnection is not null) + { + await _hubConnection.SendAsync("SendWormholeSignaturesChanged", mapId, wormholeId); + } + } + + public async Task NotifyWormholeLockChanged(int mapId, int wormholeId, bool locked) + { + if (_hubConnection is not null) + { + await _hubConnection.SendAsync("SendWormholeLockChanged", mapId, wormholeId, locked); + } + } + + public async Task NotifyWormholeSystemStatusChanged(int mapId, int wormholeId, WHSystemStatus systemStatus) + { + if (_hubConnection is not null) + { + await _hubConnection.SendAsync("SendWormholeSystemStatusChanged", mapId, wormholeId, systemStatus); + } + } + + public async Task?>> GetConnectedUsersPosition() + { + if (_hubConnection is not null) + { + return await _hubConnection.InvokeAsync?>>("GetConnectedUsersPosition"); + } + + return new Dictionary?>(); + } + + public async Task NotifyMapAdded(int mapId) + { + if (_hubConnection is not null) + { + await _hubConnection.SendAsync("SendMapAdded", mapId); + } + } + + public async Task NotifyMapRemoved(int mapId) + { + if (_hubConnection is not null) + { + await _hubConnection.SendAsync("SendMapRemoved", mapId); + } + } + + public async Task NotifyMapNameChanged(int mapId, string newName) + { + if (_hubConnection is not null) + { + await _hubConnection.SendAsync("SendMapNameChanged", mapId, newName); + } + } + + public async Task NotifyAllMapsRemoved() + { + if (_hubConnection is not null) + { + await _hubConnection.SendAsync("SendAllMapsRemoved"); + } + } + + public async Task NotifyMapAccessesAdded(int mapId, IEnumerable accessId) + { + if (_hubConnection is not null) + { + await _hubConnection.SendAsync("SendMapAccessesAdded", mapId, accessId); + } + } + + public async Task NotifyMapAccessRemoved(int mapId, int accessId) + { + if (_hubConnection is not null) + { + await _hubConnection.SendAsync("SendMapAccessRemoved", mapId, accessId); + } + } + + public async Task NotifyMapAllAccessesRemoved(int mapId) + { + if (_hubConnection is not null) + { + await _hubConnection.SendAsync("SendMapAllAccessesRemoved", mapId); + } + } + + public async Task NotifyUserOnMapConnected(int mapId) + { + if (_hubConnection is not null) + { + await _hubConnection.SendAsync("SendUserOnMapConnected", mapId); + } + } + + public async Task NotifyUserOnMapDisconnected(int mapId) + { + if (_hubConnection is not null) + { + await _hubConnection.SendAsync("SendUserOnMapDisconnected", mapId); + } + } + + public async ValueTask DisposeAsync() + { + if (_hubConnection != null) + { + await _hubConnection.StopAsync(); + await _hubConnection.DisposeAsync(); + } + } +} diff --git a/src/WHMapper/Services/EveMapper/EveMapperRoutePlannerHelper.cs b/src/WHMapper/Services/EveMapper/EveMapperRoutePlannerHelper.cs index 9a0aa984..14e41e30 100644 --- a/src/WHMapper/Services/EveMapper/EveMapperRoutePlannerHelper.cs +++ b/src/WHMapper/Services/EveMapper/EveMapperRoutePlannerHelper.cs @@ -23,7 +23,7 @@ public EveMapperRoutePlannerHelper(ILogger logger, _sdeServices = sdeServices; } - public async Task?> GetMyRoutes(int fromSolarSystemId, RouteType routeType, IEnumerable? extraConnections = null) + public async Task?> GetMyRoutes(int mapId,int fromSolarSystemId, RouteType routeType, IEnumerable? extraConnections = null) { if (_eveUserInfosServices == null) { @@ -31,10 +31,10 @@ public EveMapperRoutePlannerHelper(ILogger logger, return null; } - return await GetRoutes(fromSolarSystemId, routeType, extraConnections, false); + return await GetRoutes(mapId,fromSolarSystemId, routeType, extraConnections, false); } - public async Task?> GetRoutesForAll(int fromSolarSystemId, RouteType routeType, IEnumerable? extraConnections = null) + public async Task?> GetRoutesForAll(int mapId,int fromSolarSystemId, RouteType routeType, IEnumerable? extraConnections = null) { if (_routeRepository == null) { @@ -42,22 +42,22 @@ public EveMapperRoutePlannerHelper(ILogger logger, return null; } - return await GetRoutes(fromSolarSystemId, routeType, extraConnections, true); + return await GetRoutes(mapId,fromSolarSystemId, routeType, extraConnections, true); } - private async Task?> GetRoutes(int fromSolarSystemId, RouteType routeType, IEnumerable? extraConnections, bool global) + private async Task?> GetRoutes(int mapId,int fromSolarSystemId, RouteType routeType, IEnumerable? extraConnections, bool global) { IList routes = new List(); IEnumerable whRoutes; if (global) { - whRoutes = await _routeRepository.GetRoutesForAll(); + whRoutes = await _routeRepository.GetRoutesForAll(mapId); } else { var characterId = await _eveUserInfosServices.GetCharactedID(); - whRoutes = await _routeRepository.GetRoutesByEveEntityId(characterId); + whRoutes = await _routeRepository.GetRoutesByEveEntityId(mapId,characterId); } foreach (var whRoute in whRoutes) @@ -228,13 +228,13 @@ private float getCost(RouteType type, float security) } } - public async Task AddRoute(int soloarSystemId, bool global) + public async Task AddRoute(int mapId,int soloarSystemId, bool global) { WHRoute? route = null; if (global) { - route = await _routeRepository.Create(new WHRoute(soloarSystemId)); + route = await _routeRepository.Create(new WHRoute(mapId,soloarSystemId)); } else { @@ -244,7 +244,7 @@ private float getCost(RouteType type, float security) return null; } var characterId = await _eveUserInfosServices.GetCharactedID(); - route = await _routeRepository.Create(new WHRoute(soloarSystemId, characterId)); + route = await _routeRepository.Create(new WHRoute(mapId,soloarSystemId, characterId)); } if (route == null) diff --git a/src/WHMapper/Services/EveMapper/IEveMapperAccessHelper.cs b/src/WHMapper/Services/EveMapper/IEveMapperAccessHelper.cs index ba3f859f..977dd9dc 100644 --- a/src/WHMapper/Services/EveMapper/IEveMapperAccessHelper.cs +++ b/src/WHMapper/Services/EveMapper/IEveMapperAccessHelper.cs @@ -4,5 +4,6 @@ public interface IEveMapperAccessHelper { public Task IsEveMapperUserAccessAuthorized(int eveCharacterId); public Task IsEveMapperAdminAccessAuthorized(int eveCharacterId); + public Task IsEveMapperMapAccessAuthorized(int eveCharacterId, int mapId); } } diff --git a/src/WHMapper/Services/EveMapper/IEveMapperRealTimeService.cs b/src/WHMapper/Services/EveMapper/IEveMapperRealTimeService.cs new file mode 100644 index 00000000..cc41b6ae --- /dev/null +++ b/src/WHMapper/Services/EveMapper/IEveMapperRealTimeService.cs @@ -0,0 +1,369 @@ +using WHMapper.Models.Db.Enums; + +namespace WHMapper.Services.EveMapper; + +/// +/// Interface for the Eve Mapper synchronization service. +/// +public interface IEveMapperRealTimeService : IAsyncDisposable +{ + /// + /// Triggered when a user connects. + /// + /// The username of the connected user. + event Func UserConnected; + + /// + /// Triggered when a user disconnects. + /// + /// The username of the disconnected user. + event Func UserDisconnected; + + /// + /// Triggered when a user updates their position. + /// + /// The username of the user. + /// The ID of the map where the user is located. + /// The ID of the wormhole where the user is located. + event Func UserPosition; + +/* + /// + /// Triggered when there is an update of users' positions. + /// + /// A dictionary containing usernames and their corresponding system names. + event Func, Task> UsersPosition; +*/ + /// + /// Triggered when a wormhole is added. + /// + /// The username of the user who added the wormhole. + /// The ID of the map where the wormhole was added. + /// The ID of the added wormhole. + event Func WormholeAdded; + + /// + /// Triggered when a wormhole is removed. + /// + /// The username of the user who removed the wormhole. + /// The ID of the map where the wormhole was removed. + /// The ID of the removed wormhole. + event Func WormholeRemoved; + + /// + /// Triggered when a link is added. + /// + /// The username of the user who added the link. + /// The ID of the map where the link was added. + /// The ID of the added link. + event Func LinkAdded; + + /// + /// Triggered when a link is removed. + /// + /// The username of the user who removed the link. + /// The ID of the map where the link was removed. + /// The ID of the removed link. + event Func LinkRemoved; + + /// + /// Triggered when a wormhole is moved. + /// + /// The username of the user who moved the wormhole. + /// The ID of the map where the wormhole was moved. + /// The ID of the moved wormhole. + /// The new X position of the wormhole. + /// The new Y position of the wormhole. + event Func WormholeMoved; + + /// + /// Triggered when a link is changed. + /// + /// The username of the user who changed the link. + /// The ID of the map where the link was changed. + /// The ID of the changed link. + /// Indicates if the link is at the end of its life. + /// The size of the link. + /// The mass status of the link. + event Func LinkChanged; + + /// + /// Triggered when a wormhole name extension is changed. + /// + /// The username of the user who changed the wormhole name extension. + /// The ID of the map where the wormhole name extension was changed. + /// The ID of the wormhole with the changed name extension. + /// Indicates if the name extension was incremented. + event Func WormholeNameExtensionChanged; + + /// + /// Triggered when a wormhole signature is changed. + /// + /// The username of the user who changed the wormhole signature. + /// The ID of the map where the wormhole signature was changed. + /// The ID of the wormhole with the changed signature. + event Func WormholeSignaturesChanged; + + /// + /// Triggered when a wormhole is locked or unlocked. + /// + /// The username of the user who changed the lock status of the wormhole. + /// The ID of the map where the wormhole lock status was changed. + /// The ID of the wormhole with the changed lock status. + /// Indicates if the wormhole is locked. + event Func WormholeLockChanged; + + /// + /// Triggered when a wormhole system status is changed. + /// + /// The username of the user who changed the wormhole system status. + /// The ID of the map where the wormhole system status was changed. + /// The ID of the wormhole with the changed system status. + /// The new system status of the wormhole. + event Func WormholeSystemStatusChanged; + + /// + /// Triggered when a map is added. + /// + /// The username of the user who added the map. + /// The ID of the added map. + event Func MapAdded; + + /// + /// Triggered when a map is removed. + /// + /// The username of the user who removed the map. + /// The ID of the removed map. + event Func MapRemoved; + + /// + /// Triggered when a map name is changed. + /// + /// The username of the user who changed the map name. + /// The ID of the map with the changed name. + event Func MapNameChanged; + + + /// + /// Triggered when all maps are removed. + /// + /// The username of the user who removed all maps. + event Func AllMapsRemoved; + + /// + /// Triggered when accesses are added to a map. + /// + event Func, Task> MapAccessesAdded; + + /// + /// Triggered when an access is removed from a map. + /// + /// The username of the user who removed the access. + event Func MapAccessRemoved; + + /// + /// Triggered when all accesses are removed from a map. + /// + /// The username of the user who removed all accesses. + event Func MapAllAccessesRemoved; + + /// + /// Triggered when a user connects to a map. + /// + /// The username of the user who connected to the map. + /// The ID of the map where the user connected. + event Func UserOnMapConnected; + + /// + /// Triggered when a user disconnects from a map. + /// + /// The username of the user who disconnected from the map. + /// The ID of the map where the user disconnected. + event Func UserOnMapDisconnected; + + /// + /// Gets a value indicating whether the real-time service is connected. + /// + bool IsConnected { get; } + + /// + /// Starts the real-time service. + /// + /// A task that represents the asynchronous operation. The task result contains a boolean indicating success or failure. + Task Start(); + + /// + /// Stops the real-time service. + /// + /// A task that represents the asynchronous operation. The task result contains a boolean indicating success or failure. + Task Stop(); + + /// + /// Notifies the server of the user's position. + /// + /// The ID of the map where the user is located. + /// The ID of the wormhole where the user is located. + /// A task that represents the asynchronous operation. + Task NotifyUserPosition(int mapId,int wormholeId); + + /// + /// Notifies the server that a wormhole has been added. + /// + /// The ID of the map where the wormhole was added. + /// The ID of the added wormhole. + /// A task that represents the asynchronous operation. + Task NotifyWormoleAdded(int mapId, int wormholeId); + + /// + /// Notifies the server that a wormhole has been removed. + /// + /// The ID of the map where the wormhole was removed. + /// The ID of the removed wormhole. + /// A task that represents the asynchronous operation. + Task NotifyWormholeRemoved(int mapId, int wormholeId); + + /// + /// Notifies the server that a link has been added. + /// + /// The ID of the map where the link was added. + /// The ID of the added link. + /// A task that represents the asynchronous operation. + Task NotifyLinkAdded(int mapId, int linkId); + + /// + /// Notifies the server that a link has been removed. + /// + /// The ID of the map where the link was removed. + /// The ID of the removed link. + /// A task that represents the asynchronous operation. + Task NotifyLinkRemoved(int mapId, int linkId); + + /// + /// Notifies the server that a wormhole has been moved. + /// + /// The ID of the map where the wormhole was moved. + /// The ID of the moved wormhole. + /// The new X position of the wormhole. + /// The new Y position of the wormhole. + /// A task that represents the asynchronous operation. + Task NotifyWormholeMoved(int mapId, int wormholeId, double posX, double posY); + + /// + /// Notifies the server that a link has been changed. + /// + /// The ID of the map where the link was changed. + /// The ID of the changed link. + /// Indicates if the link is at the end of its life. + /// The size of the link. + /// The mass status of the link. + /// A task that represents the asynchronous operation. + Task NotifyLinkChanged(int mapId, int linkId, bool eol, SystemLinkSize size, SystemLinkMassStatus mass); + + /// + /// Notifies the server that a wormhole name extension has been changed. + /// + /// The ID of the map where the wormhole name extension was changed. + /// The ID of the wormhole with the changed name extension. + /// Indicates if the name extension was incremented. + /// A task that represents the asynchronous operation. + Task NotifyWormholeNameExtensionChanged(int mapId, int wormholeId, bool increment); + + /// + /// Notifies the server that a wormhole signature has been changed. + /// + /// The ID of the map where the wormhole signature was changed. + /// The ID of the wormhole with the changed signature. + /// A task that represents the asynchronous operation. + Task NotifyWormholeSignaturesChanged(int mapId, int wormholeId); + + /// + /// Notifies the server that a wormhole lock status has been changed. + /// + /// The ID of the map where the wormhole lock status was changed. + /// The ID of the wormhole with the changed lock status. + /// Indicates if the wormhole is locked. + /// A task that represents the asynchronous operation. + Task NotifyWormholeLockChanged(int mapId, int wormholeId, bool locked); + + /// + /// Notifies the server that a wormhole system status has been changed. + /// + /// The ID of the map where the wormhole system status was changed. + /// The ID of the wormhole with the changed system status. + /// The new system status of the wormhole. + /// A task that represents the asynchronous operation. + Task NotifyWormholeSystemStatusChanged(int mapId, int wormholeId, WHSystemStatus systemStatus); + + /// + /// Gets the position of connected users. + /// + /// + Task?>> GetConnectedUsersPosition(); + + + /// + /// Notifies the server that a map has been added. + /// + /// + /// + Task NotifyMapAdded(int mapId); + + /// + /// Notifies the server that a map has been removed. + /// + /// + /// + Task NotifyMapRemoved(int mapId); + + /// + /// Notifies the server that a map name has been changed. + /// + /// + /// + /// + Task NotifyMapNameChanged(int mapId, string newName); + + /// + /// Notifies the server that all maps have been removed. + /// + /// + Task NotifyAllMapsRemoved(); + + /// + /// Notifies the server that accesses have been added to a map. + /// + /// + /// + /// + Task NotifyMapAccessesAdded(int mapId, IEnumerable accessIds); + + /// + /// Notifies the server that an access has been removed from a map. + /// + /// + /// + /// + Task NotifyMapAccessRemoved(int mapId, int accessId); + + /// + /// Notifies the server that all accesses have been removed from a map. + /// + /// + /// + Task NotifyMapAllAccessesRemoved(int mapId); + + /// + /// Notifies the server that a user has connected to a map. + /// + /// + /// + Task NotifyUserOnMapConnected(int mapId); + + + /// + /// Notifies the server that a user has disconnected from a map. + /// + /// + /// + Task NotifyUserOnMapDisconnected(int mapId); +} \ No newline at end of file diff --git a/src/WHMapper/Services/EveMapper/IEveMapperRoutePlannerHelper.cs b/src/WHMapper/Services/EveMapper/IEveMapperRoutePlannerHelper.cs index 95e5f8a8..67cf8631 100644 --- a/src/WHMapper/Services/EveMapper/IEveMapperRoutePlannerHelper.cs +++ b/src/WHMapper/Services/EveMapper/IEveMapperRoutePlannerHelper.cs @@ -12,7 +12,7 @@ public interface IEveMapperRoutePlannerHelper /// /// /// - Task?> GetRoutesForAll(int fromSolarSystemId, RouteType routeType, IEnumerable? extraConnections); + Task?> GetRoutesForAll(int mapId,int fromSolarSystemId, RouteType routeType, IEnumerable? extraConnections); /// /// Get my favorites routes from selected system @@ -20,9 +20,9 @@ public interface IEveMapperRoutePlannerHelper /// /// /// - Task?> GetMyRoutes(int fromSolarSystemId, RouteType routeType, IEnumerable? extraConnections); + Task?> GetMyRoutes(int mapId,int fromSolarSystemId, RouteType routeType, IEnumerable? extraConnections); - Task AddRoute(int soloarSystemId, bool global); + Task AddRoute(int mapId,int soloarSystemId, bool global); Task DeleteRoute(int routeId); } diff --git a/src/WHMapper/Shared/AccessControl.razor b/src/WHMapper/Shared/AccessControl.razor index d75758be..033d10b9 100644 --- a/src/WHMapper/Shared/AccessControl.razor +++ b/src/WHMapper/Shared/AccessControl.razor @@ -12,6 +12,7 @@ Add Account Access List + Map Logout diff --git a/src/WHMapper/Shared/MainLayout.razor b/src/WHMapper/Shared/MainLayout.razor index 129d3067..75ed2582 100644 --- a/src/WHMapper/Shared/MainLayout.razor +++ b/src/WHMapper/Shared/MainLayout.razor @@ -1,4 +1,7 @@ -@inherits LayoutComponentBase +@using WHMapper.Services.WHSignature +@inherits LayoutComponentBase + + @@ -23,7 +26,7 @@ -} + } else { @@ -34,6 +37,11 @@ + + "Authorization in progress,please wait ...") + + + @Body @@ -54,6 +62,9 @@ [Inject] private IPasteServices PasteServices {get;set;} =null!; + [Inject] + private IWHSignatureHelper SignatureService {get;set;} =null!; + [Inject] private Services.SDE.ISDEServiceManager SDEServices {get;set;} =null!; protected override Task OnInitializedAsync() @@ -158,7 +169,13 @@ private async Task HandleCustomPaste(CustomPasteEventArgs eventArgs) { - await PasteServices.Paste(eventArgs.PastedData); + if(!String.IsNullOrEmpty(eventArgs.PastedData) && !String.IsNullOrWhiteSpace(eventArgs.PastedData)) + { + if(await SignatureService.ValidateScanResult(eventArgs.PastedData)) + { + await PasteServices.Paste(eventArgs.PastedData); + } + } } } \ No newline at end of file diff --git a/src/WHMapper/WHMapper.csproj b/src/WHMapper/WHMapper.csproj index 02970b3b..c9a6301f 100644 --- a/src/WHMapper/WHMapper.csproj +++ b/src/WHMapper/WHMapper.csproj @@ -76,26 +76,26 @@ - - + + - + - - + + - + runtime; build; native; contentfiles; analyzers; buildtransitive all - - - - + + + +