Compare commits

...

No commits in common. "master" and "new-campaign" have entirely different histories.

33 changed files with 194 additions and 441 deletions

View File

@ -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

View File

@ -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;
}

View File

@ -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;
}
}
}

View File

@ -6,13 +6,13 @@ namespace Sledgemapper.Api.Commands
public class InvitePlayerToCampaignCommand : IRequest<bool>
{
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;
}

View File

@ -48,16 +48,16 @@ namespace Sledgemapper.Api.Controllers
}
[HttpPost]
[Route("{campaignId}/players/{email}")]
public async Task<bool> Invite(Guid campaignId, string email)
[Route("{campaignName}/players/{email}")]
public async Task<bool> 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<List<Player>> GetPlayers(Guid campaignName)
public async Task<List<Player>> GetPlayers(string campaignName)
{
var result = await _mediator.Send(new GetCampaignPlayersCommand(campaignName, UserId));
return result;

View File

@ -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<Session> Get(Guid campaign, Guid mapName)
{

View File

@ -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)

View File

@ -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)
{

View File

@ -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<Session> 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<Room>(mapUpdate.Object);
mapSession.NewRoom(room);
break;
}
}

View File

@ -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<InvitePlayerToCampaignCommand, bool>
{
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<bool> 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;
}
}

View File

@ -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;

View File

@ -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;
}

View File

@ -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<string> { 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();

View File

@ -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<Campaign>().HasOne(e => e.Owner);
modelBuilder.Entity<Campaign>().HasOne(e=>e.Owner);
modelBuilder.Entity<Campaign>().HasMany(e=>e.InvitedUsers).WithMany(e=>e.Campaigns);
modelBuilder.Entity<Campaign>().HasMany(e => e.InvitedUsers).WithMany(e => e.Campaigns);
modelBuilder.Entity<User>() //Use your application user class here
.ToTable("Users"); //Set the table name here
modelBuilder.Entity<User>() //Use your application user class here
.ToTable( "Users" ); //Set the table name here
// // Map table names
// modelBuilder.Entity<MapLog>().ToTable("MapLog", "dbo");

View File

@ -9,19 +9,19 @@
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="8.1.1" />
<PackageReference Include="mediatr" Version="9.0.0" />
<PackageReference Include="mediatr.extensions.microsoft.dependencyinjection" Version="9.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.10" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="5.0.10" />
<PackageReference Include="Microsoft.AspNetCore.Identity.UI" Version="5.0.10" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="5.0.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.10">
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.6" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="5.0.6" />
<PackageReference Include="Microsoft.AspNetCore.Identity.UI" Version="5.0.6" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="5.0.6" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.6">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="5.0.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="5.0.6" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="5.0.2" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.2" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.12.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.10" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.1.4" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.11.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.6" />
</ItemGroup>
<PropertyGroup>

View File

@ -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>("/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<SledgemapperDbContext>(options =>
{
options.UseSqlite("Data Source=db/sledgemapper.db");
options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
});
services.AddDbContext<SledgemapperDbContext>(options => { options.UseSqlite("Data Source=db/sledgemapper.db"); options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking); });
services.Configure<JwtConfig>(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<User>(options => options.SignIn.RequireConfirmedAccount = false)
.AddEntityFrameworkStores<SledgemapperDbContext>();
.AddEntityFrameworkStores<SledgemapperDbContext>();
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<string>()
c.AddSecurityRequirement(new OpenApiSecurityRequirement {
{ new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
Array.Empty<string>()
}
});
});
});
}
// 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>("/sledgemapperhub");
});
}
}
}
}

View File

@ -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"
}
}
}

View File

@ -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"
}
}
}

View File

@ -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; }
}

View File

@ -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<string, string> LinuxKeyRingAttr1 = new KeyValuePair<string, string>("Version", "1");
public static readonly KeyValuePair<string, string> LinuxKeyRingAttr2 = new KeyValuePair<string, string>("ProductGroup", "MyApps");
}
}

View File

@ -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<ApiException>(ex => ex.StatusCode == HttpStatusCode.RequestTimeout)
.Or<HttpRequestException>()
@ -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<IMapApi.AuthResult> 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<AuthenticateResponse>(Encoding.UTF8.GetString(data));
Messenger.Publish(new LoginSuccesfulMessage(this) { UserName = _authenticateResponse.Username, Initials = _authenticateResponse.Initials });
}
catch
{ }
}
}
}
}

View File

@ -42,15 +42,15 @@ namespace Sledgemapper
Task<List<Player>> GetPlayers(Guid campaignName);
[Get("/campaign/{campaignId}/maps")]
Task<List<Session>> GetMaps(Guid campaignId);
[Get("/campaign/{campaignName}/maps")]
Task<List<Session>> GetMaps(Guid campaignName);
[Get("/map/{campaignId}/{mapId}")]
Task<Session> GetMap(Guid campaignId, Guid mapId);
[Get("/map/{campaignName}/{mapName}")]
Task<Session> 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);

View File

@ -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" });

View File

@ -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<Effect>("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<Texture2D>("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),

View File

@ -42,11 +42,7 @@
</ItemGroup> -->
<ItemGroup>
<PackageReference Include="AsyncAwaitBestPractices" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="6.0.0-rc.1.21451.13" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="6.0.0-rc.1.21451.13" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="6.0.0-rc.1.21451.13" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0-rc.1.21451.13" />
<PackageReference Include="Microsoft.Identity.Client.Extensions.Msal" Version="2.19.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0-preview.7.21377.19" />
<PackageReference Include="MonoGame.Extended" Version="3.8.0" />
<PackageReference Include="MonoGame.Framework.DesktopGL" Version="3.8.0.1641" />
<PackageReference Include="MonoGame.Content.Builder.Task" Version="3.8.0.1641" />
@ -58,7 +54,7 @@
<PackageReference Include="polly" Version="7.2.2" />
<PackageReference Include="polly.extensions.http" Version="3.0.0" />
<PackageReference Include="Refit.HttpClientFactory" Version="6.0.94" />
<PackageReference Include="Sentry" Version="3.9.3" />
<PackageReference Include="Sentry" Version="3.9.2" />
<PackageReference Include="TinyMessenger" Version="1.4.0-alpha3">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
@ -91,11 +87,6 @@
<DependentUpon>$([System.String]::Copy(%(Filename)).Replace(".Generated",".cs"))</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -100,7 +100,6 @@ namespace Sledgemapper.UI
_authResponse = await CommunicationManager.Login(new AuthenticateModel
{
Username = TxtEmail.Text,
Email = TxtEmail.Text,
Password = TxtPassword.Text
});
successful = true;

View File

@ -25,18 +25,10 @@ namespace Sledgemapper.UI
public MainWidget(CommunicationManager communicationManager, TinyMessengerHub messenger, GameWindow window)
{
BuildUI();
CommunicationManager = communicationManager;
Window = window;
Messenger = messenger;
Messenger.Subscribe<LoginSuccesfulMessage>(OnLoginSuccesfulMessage);
Messenger.Subscribe<SignalrConnectionUpdateMessage>(OnSignalrConnectionUpdateMessage);
Messenger.Subscribe<MapOpenedMessage>(OnMapOpenedMessage);
Messenger.Subscribe<CenterOnTileMessage>(OnCenterOnTileMessage);
Messenger.Subscribe<CampaignSelectedMessage>(OnCampaignSelectedMessage);
Messenger.Subscribe<ErrorMessage>(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<LoginSuccesfulMessage>(OnLoginSuccesfulMessage);
Messenger.Subscribe<SignalrConnectionUpdateMessage>(OnSignalrConnectionUpdateMessage);
Messenger.Subscribe<MapOpenedMessage>(OnMapOpenedMessage);
Messenger.Subscribe<CenterOnTileMessage>(OnCenterOnTileMessage);
Messenger.Subscribe<CampaignSelectedMessage>(OnCampaignSelectedMessage);
Messenger.Subscribe<ErrorMessage>(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");

View File

@ -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<bool> LoadMaps()

View File

@ -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");
}
}
}

View File

@ -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();
}

View File

@ -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";

View File

@ -1,3 +0,0 @@
{
}

View File

@ -2,6 +2,6 @@
<configuration>
<packageSources>
<add key="BaGet" value="https://baget.michelescandura.com/v3/index.json" />
<!-- <add key="MonogameDev" value="http://teamcity.monogame.net/guestAuth/app/nuget/feed/_Root/default/v3/index.json" /> -->
<add key="MonogameDev" value="http://teamcity.monogame.net/guestAuth/app/nuget/feed/_Root/default/v3/index.json" />
</packageSources>
</configuration>