diff --git a/Assets/migration scripts.txt b/Assets/migration scripts.txt deleted file mode 100644 index 771a499..0000000 --- a/Assets/migration scripts.txt +++ /dev/null @@ -1,52 +0,0 @@ - - -select * from MapLog where SessionId=2 --Ruined Maze D0823E78-15E4-45EE-A396-0A2E891961DC - -select * from MapLog where SessionId=4 --test 6351309A-EFA5-4721-A4BE-AC63995ADB7F - -select * from MapLog where SessionId=5 --daniele 7EB1D6F5-12E2-4A8F-98CD-3351D40F1D26 - -select * from MapLog where SessionId=6 --Psyruque BED7EF13-5823-427A-8C40-8BE94A563638 - - -select * from Sessions -select * from Snapshots -select * from Snapshot where SessionId=2 -select * from Sessions -select * from MapLogs -select * from MapLog -INSERT INTO Snapshots (Object, SessionId, Timestamp) -SELECT Object, "BED7EF13-5823-427A-8C40-8BE94A563638",Timestamp -FROM Snapshot -WHERE SessionId=6 -order by SnapshotId - -INSERT INTO MapLogs (Object, Operation, SessionId, Timestamp, Type, UserId) -SELECT Object, Operation, "6351309A-EFA5-4721-A4BE-AC63995ADB7F", Timestamp, Type, "cd85a137-a5e8-4e4a-81d2-3e1c94ac9470" -FROM MapLog -WHERE SessionId =2 -ORDER BY MapLogId - -INSERT INTO MapLogs (Object, Operation, SessionId, Timestamp, Type, UserId) -SELECT Object, Operation, "D0823E78-15E4-45EE-A396-0A2E891961DC", Timestamp, Type, "cd85a137-a5e8-4e4a-81d2-3e1c94ac9470" -FROM MapLog -WHERE SessionId =4 -ORDER BY MapLogId - -INSERT INTO MapLogs (Object, Operation, SessionId, Timestamp, Type, UserId) -SELECT Object, Operation, "7EB1D6F5-12E2-4A8F-98CD-3351D40F1D26", Timestamp, Type, "cd85a137-a5e8-4e4a-81d2-3e1c94ac9470" -FROM MapLog -WHERE SessionId =5 -ORDER BY MapLogId - -INSERT INTO MapLogs (Object, Operation, SessionId, Timestamp, Type, UserId) -SELECT Object, Operation, "BED7EF13-5823-427A-8C40-8BE94A563638", Timestamp, Type, "cd85a137-a5e8-4e4a-81d2-3e1c94ac9470" -FROM MapLog -WHERE SessionId =6 -ORDER BY MapLogId - ---delete from Snapshots where SessionId="A306DFEE-82A9-4964-942A-1B923B970951" - - -insert into Snapshots ( -select * from Snapshot where SessionId=2 diff --git a/Sledgemapper.Api/Commands/DeleteTileCommand.cs b/Sledgemapper.Api/Commands/DeleteTileCommand.cs index bfc2d31..e55f1dc 100644 --- a/Sledgemapper.Api/Commands/DeleteTileCommand.cs +++ b/Sledgemapper.Api/Commands/DeleteTileCommand.cs @@ -1,4 +1,3 @@ -using System; using Sledgemapper.Shared.Entities; namespace Sledgemapper.Api.Commands @@ -7,7 +6,7 @@ namespace Sledgemapper.Api.Commands { public Tile Tile { get; private set; } - public DeleteTileCommand(Guid campaign, Guid mapName, Tile tile, string userId) : base(campaign, mapName, userId) + public DeleteTileCommand(string sessionName, Tile tile, string userId) : base(sessionName, userId) { Tile = tile; } diff --git a/Sledgemapper.Api/Commands/GetCampaignPlayersCommand.cs b/Sledgemapper.Api/Commands/GetCampaignPlayersCommand.cs index 0b733f7..01fa504 100644 --- a/Sledgemapper.Api/Commands/GetCampaignPlayersCommand.cs +++ b/Sledgemapper.Api/Commands/GetCampaignPlayersCommand.cs @@ -10,7 +10,6 @@ namespace Sledgemapper.Api.Commands public double Timestamp { get; private set; } public string CampaignName { get; private set; } public string UserId { get; private set; } - public Guid CampaignId { get; private set; } public GetCampaignPlayersCommand(string campaingName, string userId) { @@ -18,12 +17,5 @@ namespace Sledgemapper.Api.Commands CampaignName = campaingName; UserId = userId; } - - public GetCampaignPlayersCommand(Guid campaignId, string userId) - { - Timestamp = DateTimeOffset.Now.ToUnixTimeMilliseconds(); - CampaignId = campaignId; - UserId = userId; - } } } \ No newline at end of file diff --git a/Sledgemapper.Api/Commands/InvitePlayerToCampaignCommand.cs b/Sledgemapper.Api/Commands/InvitePlayerToCampaignCommand.cs index de5aa7c..8ecc338 100644 --- a/Sledgemapper.Api/Commands/InvitePlayerToCampaignCommand.cs +++ b/Sledgemapper.Api/Commands/InvitePlayerToCampaignCommand.cs @@ -6,13 +6,13 @@ namespace Sledgemapper.Api.Commands public class InvitePlayerToCampaignCommand : IRequest { public double Timestamp { get; private set; } - public Guid CampaignId { get; private set; } + public string CampaignName { get; private set; } public string Email { get; private set; } public string UserId { get; private set; } - public InvitePlayerToCampaignCommand(Guid campaignId, string email, string userId) + public InvitePlayerToCampaignCommand(string campaingName, string email, string userId) { Timestamp = DateTimeOffset.Now.ToUnixTimeMilliseconds(); - CampaignId = campaignId; + CampaignName = campaingName; UserId = userId; Email = email; } diff --git a/Sledgemapper.Api/Controllers/CampaignController.cs b/Sledgemapper.Api/Controllers/CampaignController.cs index 77a6dc5..6c0313f 100644 --- a/Sledgemapper.Api/Controllers/CampaignController.cs +++ b/Sledgemapper.Api/Controllers/CampaignController.cs @@ -48,16 +48,16 @@ namespace Sledgemapper.Api.Controllers } [HttpPost] - [Route("{campaignId}/players/{email}")] - public async Task Invite(Guid campaignId, string email) + [Route("{campaignName}/players/{email}")] + public async Task Invite(string campaignName, string email) { - var result = await _mediator.Send(new InvitePlayerToCampaignCommand(campaignId, email, UserId)); + var result = await _mediator.Send(new InvitePlayerToCampaignCommand(campaignName, email, UserId)); return result; } [HttpGet] [Route("{campaignName}/players")] - public async Task> GetPlayers(Guid campaignName) + public async Task> GetPlayers(string campaignName) { var result = await _mediator.Send(new GetCampaignPlayersCommand(campaignName, UserId)); return result; diff --git a/Sledgemapper.Api/Controllers/MapController.cs b/Sledgemapper.Api/Controllers/MapController.cs index 361a9a8..683f84a 100644 --- a/Sledgemapper.Api/Controllers/MapController.cs +++ b/Sledgemapper.Api/Controllers/MapController.cs @@ -40,13 +40,6 @@ namespace Sledgemapper.Api.Controllers await _mediator.Send(new DeleteNoteCommand(campaign, mapName, note, UserId)); } - - [HttpDelete("tile")] - public async Task Delete(Guid campaign, Guid mapName, [FromBody] Tile tile) - { - await _mediator.Send(new DeleteTileCommand(campaign, mapName, tile, UserId)); - } - [HttpGet] public async Task Get(Guid campaign, Guid mapName) { diff --git a/Sledgemapper.Api/Handlers/GetCampaignPlayersCommandHandler.cs b/Sledgemapper.Api/Handlers/GetCampaignPlayersCommandHandler.cs index e915643..7b606c5 100644 --- a/Sledgemapper.Api/Handlers/GetCampaignPlayersCommandHandler.cs +++ b/Sledgemapper.Api/Handlers/GetCampaignPlayersCommandHandler.cs @@ -29,20 +29,9 @@ namespace Sledgemapper.Api.Handlers var user = await _dbcontext.Users.FindAsync(command.UserId); _dbcontext.Attach(user); + var campaign = await _dbcontext.Campaigns.Where(campaign => campaign.CampaignName == command.CampaignName && campaign.OwnerId == command.UserId).Include(campaign => campaign.InvitedUsers).FirstAsync(); - var campaign = await _dbcontext - .Campaigns - .Where(campaign => campaign.CampaignId == command.CampaignId) - .Include(c => c.InvitedUsers) - - .Include(c => c.Owner) - .Where(campaign => campaign.OwnerId == command.UserId || campaign.InvitedUsers.Contains(user)).FirstAsync(); - - - - //var campaign = await _dbcontext.Campaigns.Where(campaign => campaign.CampaignId == command.CampaignId && campaign.OwnerId == command.UserId).Include(campaign => campaign.InvitedUsers).FirstAsync(); - - var players = campaign.InvitedUsers.Select(user => new Player { Initials = user.Initials, UserName = user.UserName , UserId = new Guid(user.Id)}).ToList(); + var players = campaign.InvitedUsers.Select(user => new Player { Initials = user.Initials, UserName = user.UserName }).ToList(); return players; } catch (Exception ex) diff --git a/Sledgemapper.Api/Handlers/GetCampaignsCommandHandler.cs b/Sledgemapper.Api/Handlers/GetCampaignsCommandHandler.cs index 666f17f..12b226f 100644 --- a/Sledgemapper.Api/Handlers/GetCampaignsCommandHandler.cs +++ b/Sledgemapper.Api/Handlers/GetCampaignsCommandHandler.cs @@ -28,13 +28,11 @@ namespace Sledgemapper.Api.Handlers { var user = await _dbcontext.Users.FindAsync(command.UserId); _dbcontext.Attach(user); - var campaigns = await _dbcontext.Campaigns - .Include(c => c.InvitedUsers) - .Include(c => c.Owner) - .Where(campaign => campaign.OwnerId == command.UserId || campaign.InvitedUsers.Contains(user)).ToListAsync(); + var campaigns = _dbcontext.Campaigns.Include(c => c.InvitedUsers).Include(c => c.Maps).Include(c => c.Owner).Where(campaign => campaign.OwnerId == command.UserId || campaign.InvitedUsers.Contains(user)); - return campaigns.Select(c => new Campaign { Id = c.CampaignId, Name = c.CampaignName }).ToList(); - + return campaigns. + Select(c => new Campaign { Id = c.CampaignId, Name = c.CampaignName, Maps = c.Maps.Select(m => new Map { SessionName = m.SessionName }).ToList() }) + .ToList(); } catch (Exception ex) { diff --git a/Sledgemapper.Api/Handlers/GetMapSnapshotCommandHandler.cs b/Sledgemapper.Api/Handlers/GetMapSnapshotCommandHandler.cs index 14ad035..e304fa0 100644 --- a/Sledgemapper.Api/Handlers/GetMapSnapshotCommandHandler.cs +++ b/Sledgemapper.Api/Handlers/GetMapSnapshotCommandHandler.cs @@ -5,6 +5,7 @@ using System.Text.Json; using System.Threading; using System.Threading.Tasks; using System.Linq; +using Sledgemapper.Api.Models; using Sledgemapper.Api.Commands; using Sledgemapper.Api.Core.Entities; using Session = Sledgemapper.Shared.Entities.Session; @@ -19,10 +20,11 @@ namespace Sledgemapper.Api.Handlers public async Task Handle(GetMapSnapshotCommand notification, CancellationToken cancellationToken) { + Snapshot snapshot; double timestamp; Session mapSession; var session = _dbcontext.Sessions.First(m => m.SessionId == notification.MapId); - var snapshot = _dbcontext.Snapshots.OrderByDescending(s => s.Timestamp).FirstOrDefault(m => m.SessionId == session.SessionId); + snapshot = _dbcontext.Snapshots.OrderByDescending(s => s.Timestamp).FirstOrDefault(m => m.SessionId == session.SessionId); if (snapshot is null) { @@ -66,6 +68,10 @@ namespace Sledgemapper.Api.Handlers var room = JsonSerializer.Deserialize(mapUpdate.Object); mapSession.NewRoom(room); break; + + + + } } diff --git a/Sledgemapper.Api/Handlers/InvitePlayerToCampaignCommandHandler.cs b/Sledgemapper.Api/Handlers/InvitePlayerToCampaignCommandHandler.cs index aefdac0..c6c6a28 100644 --- a/Sledgemapper.Api/Handlers/InvitePlayerToCampaignCommandHandler.cs +++ b/Sledgemapper.Api/Handlers/InvitePlayerToCampaignCommandHandler.cs @@ -1,53 +1,43 @@ -using System; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; using MediatR; using Microsoft.EntityFrameworkCore; using Sledgemapper.Api.Commands; using Sledgemapper.Api.Infrastructure.Data; +using System; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; namespace Sledgemapper.Api.Handlers { public class InvitePlayerToCampaignCommandHandler : IRequestHandler { - private readonly SledgemapperDbContext _dbContext; private readonly IMediator _mediator; + private readonly SledgemapperDbContext _dbcontext; - public InvitePlayerToCampaignCommandHandler(IMediator mediator, SledgemapperDbContext dbContext) + public InvitePlayerToCampaignCommandHandler(IMediator mediator, SledgemapperDbContext dbcontext) { _mediator = mediator; - _dbContext = dbContext; + _dbcontext = dbcontext; } public async Task Handle(InvitePlayerToCampaignCommand command, CancellationToken cancellationToken) { try { - var user = await _dbContext.Users.FindAsync(command.UserId); + var user = await _dbcontext.Users.FindAsync(command.UserId); - var campaign = await _dbContext - .Campaigns - .Where(campaign => campaign.CampaignId == command.CampaignId) - .Include(c => c.InvitedUsers) - .Where(campaign => campaign.OwnerId == command.UserId || campaign.InvitedUsers.Contains(user)) - .FirstAsync(cancellationToken); - - - var invitedUser = - await _dbContext.Users.FirstOrDefaultAsync(iUser => iUser.Email == command.Email, - cancellationToken); - _dbContext.Attach(invitedUser); - _dbContext.Attach(campaign); + var campaign = await _dbcontext.Campaigns.Where(campaign=>campaign.CampaignName==command.CampaignName && campaign.OwnerId==command.UserId).Include(campaign=>campaign.InvitedUsers).FirstAsync(); + var invitedUser = await _dbcontext.Users.FirstOrDefaultAsync(user=>user.Email==command.Email); + _dbcontext.Attach(invitedUser); + _dbcontext.Attach(campaign); campaign.InvitedUsers.Add(invitedUser); - - await _dbContext.SaveChangesAsync(cancellationToken); + _dbcontext.Campaigns.Update(campaign); + await _dbcontext.SaveChangesAsync(); return true; } catch (Exception ex) { } - return false; } } diff --git a/Sledgemapper.Api/Handlers/NewCampaignCommandHandler.cs b/Sledgemapper.Api/Handlers/NewCampaignCommandHandler.cs index f6b505e..0c61334 100644 --- a/Sledgemapper.Api/Handlers/NewCampaignCommandHandler.cs +++ b/Sledgemapper.Api/Handlers/NewCampaignCommandHandler.cs @@ -23,7 +23,7 @@ namespace Sledgemapper.Api.Handlers { try { - var user = await _dbcontext.Users.FindAsync(new object[] { notification.UserId }, cancellationToken); + var user = await _dbcontext.Users.FindAsync(notification.UserId, cancellationToken); _dbcontext.Attach(user); var campaign = new Core.Entities.Campaign { @@ -39,7 +39,7 @@ namespace Sledgemapper.Api.Handlers } catch (Exception ex) { - + } return false; diff --git a/Sledgemapper.Api/Handlers/NewNoteCommandHandler.cs b/Sledgemapper.Api/Handlers/NewNoteCommandHandler.cs index 8be5287..6390422 100644 --- a/Sledgemapper.Api/Handlers/NewNoteCommandHandler.cs +++ b/Sledgemapper.Api/Handlers/NewNoteCommandHandler.cs @@ -18,7 +18,7 @@ namespace Sledgemapper.Api.Handlers { await CheckAuthorization(command); var jsonString = JsonSerializer.Serialize(command.Note); - var session = await SaveLog(command, "N", "N", jsonString, cancellationToken); + var session = await SaveLog(command, "N", "W", jsonString, cancellationToken); await Mediator.Publish(new NewNoteNotification(session, command.Note, command.UserId), cancellationToken); return true; } diff --git a/Sledgemapper.Api/Hubs/SledgemapperHub.cs b/Sledgemapper.Api/Hubs/SledgemapperHub.cs index 9484d99..847e221 100644 --- a/Sledgemapper.Api/Hubs/SledgemapperHub.cs +++ b/Sledgemapper.Api/Hubs/SledgemapperHub.cs @@ -166,20 +166,9 @@ namespace Sledgemapper.Api.Hubs foreach (var userSession in userSessions) { var session = _dbContext.Sessions.FirstOrDefault(m => m.SessionId == userSession.SessionId); - if (session != null) - { - - try - { - await Clients.GroupExcept(session.SessionId.ToString(), new List { Context.ConnectionId }).RemovePlayer(new Player { UserId = userId }); //send remove player - } - catch (Exception e) - { - Console.WriteLine(e); - } - _dbContext.SessionUsers.Remove(userSession); - } + await Clients.Group(session.SessionName).RemovePlayer(new Player { UserId = userId }); //send remove player + _dbContext.SessionUsers.Remove(userSession); } } await _dbContext.SaveChangesAsync(); diff --git a/Sledgemapper.Api/Infrastructure/Data/SledgemapperDbContext.cs b/Sledgemapper.Api/Infrastructure/Data/SledgemapperDbContext.cs index 195b192..265d446 100644 --- a/Sledgemapper.Api/Infrastructure/Data/SledgemapperDbContext.cs +++ b/Sledgemapper.Api/Infrastructure/Data/SledgemapperDbContext.cs @@ -37,19 +37,19 @@ namespace Sledgemapper.Api.Infrastructure.Data // options.MigrationsAssembly(Assembly.GetExecutingAssembly().FullName); // }); - optionsBuilder.UseSqlite("Filename=db/sledgemapper.db").UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking); + optionsBuilder.UseSqlite("Filename=Sledgemapper.db").UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking); base.OnConfiguring(optionsBuilder); } protected override void OnModelCreating(ModelBuilder modelBuilder) { - modelBuilder.Entity().HasOne(e => e.Owner); + modelBuilder.Entity().HasOne(e=>e.Owner); + +modelBuilder.Entity().HasMany(e=>e.InvitedUsers).WithMany(e=>e.Campaigns); - modelBuilder.Entity().HasMany(e => e.InvitedUsers).WithMany(e => e.Campaigns); - - modelBuilder.Entity() //Use your application user class here - .ToTable("Users"); //Set the table name here + modelBuilder.Entity() //Use your application user class here + .ToTable( "Users" ); //Set the table name here // // Map table names // modelBuilder.Entity().ToTable("MapLog", "dbo"); diff --git a/Sledgemapper.Api/Sledgemapper.Api.csproj b/Sledgemapper.Api/Sledgemapper.Api.csproj index a5dbc63..30d003d 100644 --- a/Sledgemapper.Api/Sledgemapper.Api.csproj +++ b/Sledgemapper.Api/Sledgemapper.Api.csproj @@ -9,19 +9,19 @@ - - - - - + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive all - + - - - + + + diff --git a/Sledgemapper.Api/Startup.cs b/Sledgemapper.Api/Startup.cs index 0928fd3..84bf827 100644 --- a/Sledgemapper.Api/Startup.cs +++ b/Sledgemapper.Api/Startup.cs @@ -1,57 +1,30 @@ using System; -using System.Text; -using MediatR; -using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; -using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Sledgemapper.Api.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; +using MediatR; using Microsoft.IdentityModel.Tokens; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using System.Text; +using Sledgemapper.Api.Hubs; using Microsoft.OpenApi.Models; using Newtonsoft.Json; using Sledgemapper.Api.Core.Entities; -using Sledgemapper.Api.Hubs; -using Sledgemapper.Api.Infrastructure.Data; namespace Sledgemapper.Api { public class Startup { private readonly IWebHostEnvironment _env; - + public IConfiguration Configuration { get; } public Startup(IWebHostEnvironment env, IConfiguration configuration) { Configuration = configuration; _env = env; - } - public IConfiguration Configuration { get; } - - // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - public void Configure(IApplicationBuilder app, IWebHostEnvironment env, SledgemapperDbContext dataContext) - { - // Enable middleware to serve generated Swagger as a JSON endpoint. - app.UseSwagger(); - - // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), - // specifying the Swagger JSON endpoint. - app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); }); - - dataContext.Database.Migrate(); - - app.UseRouting(); - - app.UseCors(x => x - .AllowAnyOrigin() - .AllowAnyMethod() - .AllowAnyHeader()); - app.UseAuthentication(); - app.UseAuthorization(); - - app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); - - app.UseEndpoints(endpoints => { endpoints.MapHub("/sledgemapperhub"); }); } // This method gets called by the runtime. Use this method to add services to the container. @@ -61,16 +34,14 @@ namespace Sledgemapper.Api services.AddControllers().AddNewtonsoftJson(o => { o.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; - }); + }); ; + + services.AddSignalR(); services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); services.AddMediatR(typeof(Startup)); - services.AddDbContext(options => - { - options.UseSqlite("Data Source=db/sledgemapper.db"); - options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking); - }); + services.AddDbContext(options => { options.UseSqlite("Data Source=db/sledgemapper.db"); options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking); }); services.Configure(Configuration.GetSection("JwtConfig")); @@ -78,30 +49,29 @@ namespace Sledgemapper.Api // within this section we are configuring the authentication and setting the default scheme services.AddAuthentication(options => - { - options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; - options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; - options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; - }) - .AddJwtBearer(jwt => - { - var key = Encoding.ASCII.GetBytes(Configuration["JwtConfig:Secret"]); + { + options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; + options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; + options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; + }) + .AddJwtBearer(jwt => + { + var key = Encoding.ASCII.GetBytes(Configuration["JwtConfig:Secret"]); - jwt.SaveToken = true; - jwt.TokenValidationParameters = new TokenValidationParameters - { - ValidateIssuerSigningKey = - true, // this will validate the 3rd part of the jwt token using the secret that we added in the appsettings and verify we have generated the jwt token - IssuerSigningKey = new SymmetricSecurityKey(key), // Add the secret key to our Jwt encryption - ValidateIssuer = false, - ValidateAudience = false, - RequireExpirationTime = false, - ValidateLifetime = true - }; - }); + jwt.SaveToken = true; + jwt.TokenValidationParameters = new TokenValidationParameters + { + ValidateIssuerSigningKey = true, // this will validate the 3rd part of the jwt token using the secret that we added in the appsettings and verify we have generated the jwt token + IssuerSigningKey = new SymmetricSecurityKey(key), // Add the secret key to our Jwt encryption + ValidateIssuer = false, + ValidateAudience = false, + RequireExpirationTime = false, + ValidateLifetime = true + }; + }); services.AddDefaultIdentity(options => options.SignIn.RequireConfirmedAccount = false) - .AddEntityFrameworkStores(); + .AddEntityFrameworkStores(); services.AddSwaggerGen(c => { @@ -117,21 +87,57 @@ namespace Sledgemapper.Api Name = "Authorization", Type = SecuritySchemeType.ApiKey }); - c.AddSecurityRequirement(new OpenApiSecurityRequirement - { - { - new OpenApiSecurityScheme - { - Reference = new OpenApiReference - { - Type = ReferenceType.SecurityScheme, - Id = "Bearer" - } - }, - Array.Empty() + c.AddSecurityRequirement(new OpenApiSecurityRequirement { + { new OpenApiSecurityScheme + { + Reference = new OpenApiReference + { + Type = ReferenceType.SecurityScheme, + Id = "Bearer" + } + }, + Array.Empty() } - }); + }); + }); + + + + } + + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. + public void Configure(IApplicationBuilder app, IWebHostEnvironment env, SledgemapperDbContext dataContext) + { + // Enable middleware to serve generated Swagger as a JSON endpoint. + app.UseSwagger(); + + // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), + // specifying the Swagger JSON endpoint. + app.UseSwaggerUI(c => + { + c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); + }); + + dataContext.Database.Migrate(); + + app.UseRouting(); + + app.UseCors(x => x + .AllowAnyOrigin() + .AllowAnyMethod() + .AllowAnyHeader()); + app.UseAuthentication(); + app.UseAuthorization(); + + app.UseEndpoints(endpoints => + { + endpoints.MapControllers(); + }); + + app.UseEndpoints(endpoints => + { + endpoints.MapHub("/sledgemapperhub"); }); } } -} \ No newline at end of file +} diff --git a/Sledgemapper.Api/appsettings.Development.json b/Sledgemapper.Api/appsettings.Development.json index f66b5e3..996eb73 100644 --- a/Sledgemapper.Api/appsettings.Development.json +++ b/Sledgemapper.Api/appsettings.Development.json @@ -1,12 +1,12 @@ -{ - "ConnectionStrings": { - "WebApiDatabase": "Data Source=db/sledgemapper.db" - }, - "Logging": { - "LogLevel": { - "Default": "Debug", - "System": "Information", - "Microsoft": "Information" - } +{ + "ConnectionStrings": { + "WebApiDatabase": "Data Source=db/LocalDatabase.db" + }, + "Logging": { + "LogLevel": { + "Default": "Debug", + "System": "Information", + "Microsoft": "Information" } + } } diff --git a/Sledgemapper.Api/appsettings.Production.json b/Sledgemapper.Api/appsettings.Production.json index f66b5e3..996eb73 100644 --- a/Sledgemapper.Api/appsettings.Production.json +++ b/Sledgemapper.Api/appsettings.Production.json @@ -1,12 +1,12 @@ -{ - "ConnectionStrings": { - "WebApiDatabase": "Data Source=db/sledgemapper.db" - }, - "Logging": { - "LogLevel": { - "Default": "Debug", - "System": "Information", - "Microsoft": "Information" - } +{ + "ConnectionStrings": { + "WebApiDatabase": "Data Source=db/LocalDatabase.db" + }, + "Logging": { + "LogLevel": { + "Default": "Debug", + "System": "Information", + "Microsoft": "Information" } + } } diff --git a/Sledgemapper.Shared/Entities/Note.cs b/Sledgemapper.Shared/Entities/Note.cs index a89257f..6dac5bb 100644 --- a/Sledgemapper.Shared/Entities/Note.cs +++ b/Sledgemapper.Shared/Entities/Note.cs @@ -1,21 +1,9 @@ -namespace Sledgemapper.Shared.Entities +namespace Sledgemapper.Shared.Entities { public class Note :BaseMapEntity { - public Note(){} - public Note(Note n) - { - X=n.X; - Y=n.Y; - Text=n.Text; - ID = n.ID; - Rotation = n.Rotation; - Timestamp = n.Timestamp; - - } - public string Text { get; set; } } diff --git a/Sledgemapper/CacheSettings.cs b/Sledgemapper/CacheSettings.cs deleted file mode 100644 index 3dd06a5..0000000 --- a/Sledgemapper/CacheSettings.cs +++ /dev/null @@ -1,30 +0,0 @@ -using Microsoft.Identity.Client.Extensions.Msal; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Sledgemapper -{ - public static class CacheSettings - { - // computing the root directory is not very simple on Linux and Mac, so a helper is provided - private static readonly string s_cacheFilePath = - Path.Combine(MsalCacheHelper.UserRootDirectory, "sledgemapper.scandysoft.cache"); - - public static readonly string CacheFileName = Path.GetFileName(s_cacheFilePath); - public static readonly string CacheDir = Path.GetDirectoryName(s_cacheFilePath); - - - public static readonly string KeyChainServiceName = "Scandysoft.Sledgemapper"; - public static readonly string KeyChainAccountName = "MSALCache"; - - public static readonly string LinuxKeyRingSchema = "com.scandysoft.sledgemappertokencache"; - public static readonly string LinuxKeyRingCollection = MsalCacheHelper.LinuxKeyRingDefaultCollection; - public static readonly string LinuxKeyRingLabel = "Sledgemapper API token."; - public static readonly KeyValuePair LinuxKeyRingAttr1 = new KeyValuePair("Version", "1"); - public static readonly KeyValuePair LinuxKeyRingAttr2 = new KeyValuePair("ProductGroup", "MyApps"); - } -} diff --git a/Sledgemapper/CommunicationManager.cs b/Sledgemapper/CommunicationManager.cs index c584097..5ad52d6 100644 --- a/Sledgemapper/CommunicationManager.cs +++ b/Sledgemapper/CommunicationManager.cs @@ -4,8 +4,6 @@ using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; -using System.Text; -using System.Text.Json; using System.Threading.Tasks; using Microsoft.AspNetCore.SignalR.Client; using Polly; @@ -35,13 +33,10 @@ namespace Sledgemapper _queue = new ChannelsQueue(Messenger); #if DEBUG var baseAddress = "http://localhost:5000"; - //baseAddress = "http://hub.michelescandura.com:5001"; #else - var baseAddress = "http://hub.michelescandura.com:5001"; + var baseAddress = "http://hub.michelescandura.com:5000"; #endif - CheckLogin(); - _retryPolicy = Policy .Handle(ex => ex.StatusCode == HttpStatusCode.RequestTimeout) .Or() @@ -297,28 +292,13 @@ namespace Sledgemapper .ConfigureAwait(false); //_authenticateResponse = await Api.Authenticate(authenticateModel).ConfigureAwait(false); - var data = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(_authenticateResponse)); - - Program.helper.SaveUnencryptedTokenCache(JsonSerializer.SerializeToUtf8Bytes(_authenticateResponse)); - - await Connection.StopAsync(); - - State.Instance.CampaignId=Guid.Empty; - State.Instance.CampaignName = string.Empty; - State.Instance.SessionId = Guid.Empty; - State.Instance.MapId = Guid.Empty; - State.Instance.MapName = string.Empty; - SessionData.SessionId = Guid.Empty; - SessionData.SessionName = string.Empty; - SessionData.Players.Clear(); - return _authenticateResponse; } internal async Task Ping(Tile location) { if (Connection is { State: HubConnectionState.Connected }) - await Connection.InvokeAsync("Ping", SessionData.SessionId, location); + await Connection.InvokeAsync("Ping", SessionData.SessionName, location); } public async Task Register(RegisterModel registerModel) @@ -326,20 +306,5 @@ namespace Sledgemapper var result = await Api.Register(registerModel).ConfigureAwait(false); return result; } - - public void CheckLogin() - { - var data = Program.helper.LoadUnencryptedTokenCache(); - if (data != null && data.Any()) - { - try - { - _authenticateResponse = JsonSerializer.Deserialize(Encoding.UTF8.GetString(data)); - Messenger.Publish(new LoginSuccesfulMessage(this) { UserName = _authenticateResponse.Username, Initials = _authenticateResponse.Initials }); - } - catch - { } - } - } } } \ No newline at end of file diff --git a/Sledgemapper/IMapApi.cs b/Sledgemapper/IMapApi.cs index b831739..2c66283 100644 --- a/Sledgemapper/IMapApi.cs +++ b/Sledgemapper/IMapApi.cs @@ -42,15 +42,15 @@ namespace Sledgemapper Task> GetPlayers(Guid campaignName); - [Get("/campaign/{campaignId}/maps")] - Task> GetMaps(Guid campaignId); + [Get("/campaign/{campaignName}/maps")] + Task> GetMaps(Guid campaignName); - [Get("/map/{campaignId}/{mapId}")] - Task GetMap(Guid campaignId, Guid mapId); + [Get("/map/{campaignName}/{mapName}")] + Task GetMap(Guid campaignName, Guid mapName); - [Post("/campaign/{campaignId}/players/{email}")] - Task InvitePlayer(Guid campaignId, string email); + [Post("/campaign/{campaignName}/players/{email}")] + Task InvitePlayer(string campaignName, string email); diff --git a/Sledgemapper/Program.cs b/Sledgemapper/Program.cs index 58eada1..7eb1839 100644 --- a/Sledgemapper/Program.cs +++ b/Sledgemapper/Program.cs @@ -1,47 +1,13 @@ using System; -using System.Text; -using Microsoft.Extensions.Configuration; -using Microsoft.Identity.Client; -using Microsoft.Identity.Client.Extensions.Msal; namespace Sledgemapper { public static class Program { - private static IConfiguration configuration; - public static MsalCacheHelper helper; - [STAThread] static void Main() { - var builder = new ConfigurationBuilder() - .SetBasePath(System.IO.Directory.GetCurrentDirectory()) - .AddJsonFile("appsettings.json"); - - configuration = builder.Build(); - - // Loading PublicClientApplicationOptions from the values set on appsettings.json - - - - // Building StorageCreationProperties - var storageProperties = - new StorageCreationPropertiesBuilder(CacheSettings.CacheFileName, CacheSettings.CacheDir) - .WithLinuxKeyring( - CacheSettings.LinuxKeyRingSchema, - CacheSettings.LinuxKeyRingCollection, - CacheSettings.LinuxKeyRingLabel, - CacheSettings.LinuxKeyRingAttr1, - CacheSettings.LinuxKeyRingAttr2) - .WithMacKeyChain( - CacheSettings.KeyChainServiceName, - CacheSettings.KeyChainAccountName) - .Build(); - // storage = Storage.Create(storageProperties); - - helper = MsalCacheHelper.CreateAsync(storageProperties).Result; - - using (Sentry.SentrySdk.Init("https://973ac1606651454ba7a19f642d0a9bc1@glitchtip.michelescandura.com/1")) + using(Sentry.SentrySdk.Init("https://973ac1606651454ba7a19f642d0a9bc1@glitchtip.michelescandura.com/1")) using (var game = new Sledgemapper()) { Sentry.SentrySdk.CaptureEvent(new Sentry.SentryEvent() { Message = "App starting" }); diff --git a/Sledgemapper/Sledgemapper.cs b/Sledgemapper/Sledgemapper.cs index 57e8de1..1d960db 100644 --- a/Sledgemapper/Sledgemapper.cs +++ b/Sledgemapper/Sledgemapper.cs @@ -57,7 +57,6 @@ namespace Sledgemapper MyraEnvironment.Game = this; - _sessionData = new Session(); IsFixedTimeStep = true; TargetElapsedTime = TimeSpan.FromSeconds(1d / 30d); @@ -137,19 +136,10 @@ namespace Sledgemapper _outlineShader = Content.Load("shaders/OutlineShader"); MyraEnvironment.Game = this; ResetRenderTarget(); - // Inform Myra that external text input is available - // So it stops translating Keys to chars - _desktop.HasExternalTextInput = true; - // Provide that text input - Window.TextInput += (s, a) => - { - _desktop.OnChar(a.Character); - - }; _mainWidget = new MainWidget(_communicationManager, _messenger, Window); - _communicationManager.CheckLogin(); + _wallsContent = Content.LoadContentFolder("walls"); @@ -265,7 +255,7 @@ namespace Sledgemapper else { _sessionData.Notes.TryGetValue(_state.SelectedNote.ToString(), out var n); - _state.SelectedNote = new Note(n); + _state.SelectedNote = n; var viewNoteButton = new TextButton { Text = "View Note", Width = 80, Height = 20, Padding = new Thickness(2), diff --git a/Sledgemapper/Sledgemapper.csproj b/Sledgemapper/Sledgemapper.csproj index 4789d7e..cfb4b66 100644 --- a/Sledgemapper/Sledgemapper.csproj +++ b/Sledgemapper/Sledgemapper.csproj @@ -42,11 +42,7 @@ --> - - - - - + @@ -58,7 +54,7 @@ - + runtime; build; native; contentfiles; analyzers; buildtransitive all @@ -91,11 +87,6 @@ $([System.String]::Copy(%(Filename)).Replace(".Generated",".cs")) - - - PreserveNewest - - \ No newline at end of file diff --git a/Sledgemapper/UI/LoginRegisterWindow.Custom.cs b/Sledgemapper/UI/LoginRegisterWindow.Custom.cs index f565e68..73dee30 100644 --- a/Sledgemapper/UI/LoginRegisterWindow.Custom.cs +++ b/Sledgemapper/UI/LoginRegisterWindow.Custom.cs @@ -100,7 +100,6 @@ namespace Sledgemapper.UI _authResponse = await CommunicationManager.Login(new AuthenticateModel { Username = TxtEmail.Text, - Email = TxtEmail.Text, Password = TxtPassword.Text }); successful = true; diff --git a/Sledgemapper/UI/MainWidget.Custom.cs b/Sledgemapper/UI/MainWidget.Custom.cs index c2b6686..361e63b 100644 --- a/Sledgemapper/UI/MainWidget.Custom.cs +++ b/Sledgemapper/UI/MainWidget.Custom.cs @@ -25,18 +25,10 @@ namespace Sledgemapper.UI public MainWidget(CommunicationManager communicationManager, TinyMessengerHub messenger, GameWindow window) { BuildUI(); + CommunicationManager = communicationManager; Window = window; Messenger = messenger; - - Messenger.Subscribe(OnLoginSuccesfulMessage); - Messenger.Subscribe(OnSignalrConnectionUpdateMessage); - Messenger.Subscribe(OnMapOpenedMessage); - Messenger.Subscribe(OnCenterOnTileMessage); - Messenger.Subscribe(OnCampaignSelectedMessage); - Messenger.Subscribe(OnErrorMessage); - - MenuConnectLogin.Selected += OnMenuConnectLoginSelected; MenuConnectSync.Selected += OnMenuConnectSyncSelected; MenuFileLoad.Selected += OnMenuFileLoadSelected; @@ -70,7 +62,12 @@ namespace Sledgemapper.UI BtnToolbarRoom.Click += OnBtnToolbarRoomClicked; BtnToolbarDelete.Click += OnBtnToolbarDeleteClicked; - + Messenger.Subscribe(OnLoginSuccesfulMessage); + Messenger.Subscribe(OnSignalrConnectionUpdateMessage); + Messenger.Subscribe(OnMapOpenedMessage); + Messenger.Subscribe(OnCenterOnTileMessage); + Messenger.Subscribe(OnCampaignSelectedMessage); + Messenger.Subscribe(OnErrorMessage); } private void CenterOnSelectedTile() @@ -114,6 +111,7 @@ namespace Sledgemapper.UI private void OnBtnToolbarDeleteClicked(object sender, EventArgs e) { + Messenger.Publish(new ErrorMessage(this, "test")); State.Instance.InsertMode = InsertMode.NewDelete; ClearSelection(); @@ -228,15 +226,7 @@ namespace Sledgemapper.UI //MenuConnectJoin.Enabled = true; MenuCampaignOpen.Enabled = true; MenuCampaingNew.Enabled = true; - MenuMapNew.Enabled = false; - MenuMapOpen.Enabled = false; - MenuConnectSync.Enabled = false; - MenuConnectUpload.Enabled = false; - MenuCampaignPlayers.Enabled = false; - lblCampaign.Text = "n/a"; - lblMap.Text = "n/a"; - CommunicationManager.SessionData.MapEntityAdded -= OnMapEntityAdded; - CommunicationManager.SessionData.MapEntityDeleted -= OnMapEntityDeleted; + lblUsername.Text = $"{obj.Initials}"; } @@ -304,7 +294,7 @@ namespace Sledgemapper.UI { if (!((MenuItem)sender).Enabled) return; - var content = new PlayerList(CommunicationManager, Messenger); + var content = new PlayerList(CommunicationManager); if (await content.LoadPlayers()) { content.ShowInModalWindow(Desktop, "Players"); diff --git a/Sledgemapper/UI/MapList.Custom.cs b/Sledgemapper/UI/MapList.Custom.cs index e779da8..58cd13c 100644 --- a/Sledgemapper/UI/MapList.Custom.cs +++ b/Sledgemapper/UI/MapList.Custom.cs @@ -32,13 +32,11 @@ namespace Sledgemapper.UI private void BtnLoadCampaign_Click(object sender, EventArgs e) { - if (!string.IsNullOrWhiteSpace(_selectedMap) && _selectedMapId!=Guid.Empty) - { - State.Instance.MapName = _selectedMap; - State.Instance.MapId = _selectedMapId; - Messenger.Publish(new MapOpenedMessage(this, _selectedMap, _selectedMapId)); - this.GetContainingWindow().Close(); - } + State.Instance.MapName = _selectedMap; + State.Instance.MapId = _selectedMapId; + // var map = CommunicationManager.Api.GetMap(State.Instance.CampaignId, State.Instance.MapId); + Messenger.Publish(new MapOpenedMessage(this, _selectedMap, _selectedMapId)); + this.GetContainingWindow().Close(); } public async Task LoadMaps() diff --git a/Sledgemapper/UI/PlayerList.Custom.cs b/Sledgemapper/UI/PlayerList.Custom.cs index 8fcdfd5..84c238b 100644 --- a/Sledgemapper/UI/PlayerList.Custom.cs +++ b/Sledgemapper/UI/PlayerList.Custom.cs @@ -1,20 +1,15 @@ /* Generated by MyraPad at 28/08/2021 19:49:08 */ using System.Threading.Tasks; -using TinyMessenger; namespace Sledgemapper.UI { public partial class PlayerList { - protected CommunicationManager CommunicationManager { get; } - protected TinyMessengerHub Messenger { get; } + protected readonly CommunicationManager CommunicationManager; - public PlayerList(CommunicationManager communicationManager, TinyMessenger.TinyMessengerHub messenger) + public PlayerList(CommunicationManager communicationManager) { - CommunicationManager = communicationManager; - Messenger = messenger; - BuildUI(); CommunicationManager = communicationManager; BtnInvitePlayer.Click += (s, e) => @@ -43,7 +38,7 @@ namespace Sledgemapper.UI private void ShowAddPLayerWindow() { - new PlayerWindow(CommunicationManager, Messenger).ShowInModalWindow(Desktop, "Invite player"); + new PlayerWindow(CommunicationManager).ShowInModalWindow(Desktop, "Invite player"); } } } \ No newline at end of file diff --git a/Sledgemapper/UI/PlayerWindow.Custom.cs b/Sledgemapper/UI/PlayerWindow.Custom.cs index a81a12d..f314696 100644 --- a/Sledgemapper/UI/PlayerWindow.Custom.cs +++ b/Sledgemapper/UI/PlayerWindow.Custom.cs @@ -1,21 +1,17 @@ /* Generated by MyraPad at 28/08/2021 22:04:11 */ using Myra.Graphics2D.UI; using Sentry; -using Sledgemapper.Messages; using System; -using TinyMessenger; namespace Sledgemapper.UI { public partial class PlayerWindow { - protected CommunicationManager CommunicationManager { get; } - protected TinyMessengerHub Messenger { get; } + protected readonly CommunicationManager CommunicationManager; - public PlayerWindow(CommunicationManager communicationManager, TinyMessenger.TinyMessengerHub messenger) + public PlayerWindow(CommunicationManager communicationManager) { - CommunicationManager = communicationManager; - Messenger = messenger; + CommunicationManager = communicationManager; BuildUI(); BtnNewCampaign.Click += OnButtonInvitePlayerClicked; @@ -33,13 +29,11 @@ namespace Sledgemapper.UI var successful = false; try { - await CommunicationManager.Api.InvitePlayer(State.Instance.CampaignId, localContent.Content.TxtCampaign.Text); + await CommunicationManager.Api.InvitePlayer(State.Instance.CampaignName, localContent.Content.TxtCampaign.Text); } catch (Exception ex) { - Messenger.Publish(new ErrorMessage(this, "Error inviting player")); SentrySdk.CaptureException(ex); - } this.GetContainingWindow().Close(); } diff --git a/Sledgemapper/UI/PlayerWindow.Generated.cs b/Sledgemapper/UI/PlayerWindow.Generated.cs index 509d0b8..62d81ea 100644 --- a/Sledgemapper/UI/PlayerWindow.Generated.cs +++ b/Sledgemapper/UI/PlayerWindow.Generated.cs @@ -45,7 +45,7 @@ namespace Sledgemapper.UI grid1.Widgets.Add(TxtCampaign); BtnNewCampaign = new TextButton(); - BtnNewCampaign.Text = "Invite"; + BtnNewCampaign.Text = "New"; BtnNewCampaign.Padding = new Thickness(10, 5); BtnNewCampaign.HorizontalAlignment = Myra.Graphics2D.UI.HorizontalAlignment.Center; BtnNewCampaign.Id = "BtnNewCampaign"; diff --git a/Sledgemapper/appsettings.json b/Sledgemapper/appsettings.json deleted file mode 100644 index 544b7b4..0000000 --- a/Sledgemapper/appsettings.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - -} \ No newline at end of file diff --git a/nuget.config b/nuget.config index cd4f26c..7749f28 100644 --- a/nuget.config +++ b/nuget.config @@ -2,6 +2,6 @@ - + \ No newline at end of file