DB added and more

This commit is contained in:
2021-10-28 17:03:15 -04:00
parent b56ca46363
commit 28fbc4598e
20 changed files with 453 additions and 21 deletions

View File

@@ -4,7 +4,7 @@ using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using TOOHUCardAPI.Models; using TOOHUCardAPI.DTO;
namespace TOOHUCardAPI.Controllers namespace TOOHUCardAPI.Controllers
{ {

View File

@@ -5,12 +5,16 @@ using System.Linq;
using System.Net.Http; using System.Net.Http;
using System.Reflection; using System.Reflection;
using System.Threading.Tasks; using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using TOOHUCardAPI.Data; using TOOHUCardAPI.Data;
using TOOHUCardAPI.Models; using TOOHUCardAPI.Data.Models;
using TOOHUCardAPI.Data.Repositories;
using TOOHUCardAPI.DTO;
namespace TOOHUCardAPI.Controllers namespace TOOHUCardAPI.Controllers
{ {
@@ -18,6 +22,17 @@ namespace TOOHUCardAPI.Controllers
[ApiController] [ApiController]
public class PlayerDataController : MethodBasedController public class PlayerDataController : MethodBasedController
{ {
private readonly ILogger<PlayerDataController> _logger;
private readonly UserRepository _userRepository;
private readonly IMapper _mapper;
public PlayerDataController(ILogger<PlayerDataController> logger, UserRepository userRepository, IMapper mapper)
{
_logger = logger;
_userRepository = userRepository;
_mapper = mapper;
}
/** /**
* The game uses a single endpoint for player data. * The game uses a single endpoint for player data.
* The object they send has a method field that's used to decide what's being done * The object they send has a method field that's used to decide what's being done
@@ -33,10 +48,17 @@ namespace TOOHUCardAPI.Controllers
} }
[EndpointHandler("get")] [EndpointHandler("get")]
private async Task<object> GetDummy(string body) private async Task<object> Get(string body)
{ {
PlayerDataGetRequestObject requestObject = JsonConvert.DeserializeObject<PlayerDataGetRequestObject>(body); PlayerDataGetRequestObject requestObject = JsonConvert.DeserializeObject<PlayerDataGetRequestObject>(body);
PlayerDataGetResponseObject response = new PlayerDataGetResponseObject(requestObject.Ids.Keys.Count); Dictionary<string, User> users = requestObject.Ids.Aggregate(new Dictionary<string, User>(),
(dictionary, pair) =>
{
User user = _userRepository.GetOrCreateUser(pair.Value);
dictionary[pair.Key] = user;
return dictionary;
});
PlayerDataGetResponseObject response = new PlayerDataGetResponseObject(users, _mapper);
return response; return response;
} }

View File

@@ -2,15 +2,15 @@ using System;
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
using Newtonsoft.Json; using Newtonsoft.Json;
namespace TOOHUCardAPI.Models namespace TOOHUCardAPI.DTO
{ {
/** /**
* GameRules.GameData.code = data.code // "0000" for success * GameRules.GameData.code = data.code // "0000" for success
GameRules.GameData.msg = data.msg // error message if any GameRules.GameData.msg = data.msg // error message if any
GameRules.GameData.game_code = data.game_code or "" GameRules.GameData.game_code = data.game_code or "" // Possibly some incrementing value for the room num
GameRules.GameData.game_msg = data.game_msg or "" GameRules.GameData.game_msg = data.game_msg or "" // message shown on startup
GameRules.GameData.luck_card = data.luck_card or "" GameRules.GameData.luck_card = data.luck_card or "" // card that luck_crit applies to or "all"
GameRules.GameData.luck_crit = data.luck_crit or 0 GameRules.GameData.luck_crit = data.luck_crit or 0 // above
GameRules.GameData.new_card_list = data.new_card_list or "" GameRules.GameData.new_card_list = data.new_card_list or ""
GameRules.GameData.open_day_list = data.open_day_list or "" GameRules.GameData.open_day_list = data.open_day_list or ""
GameRules.GameData.is_open_day = data.is_open_day or 0 GameRules.GameData.is_open_day = data.is_open_day or 0
@@ -19,14 +19,15 @@ namespace TOOHUCardAPI.Models
public class GameConfigResponse public class GameConfigResponse
{ {
private static string SUCCESS_CODE = "0000"; private static string SUCCESS_CODE = "0000";
private static string DEFAULT_GAME_MESSAGE = "Welcome to english Touhou Card";
[JsonProperty("code")] public string Code { get; set; } = SUCCESS_CODE; [JsonProperty("code")] public string Code { get; set; } = SUCCESS_CODE;
[JsonProperty("msg")] public string Message { get; set; } = string.Empty; [JsonProperty("msg")] public string Message { get; set; } = string.Empty;
[JsonProperty("game_code")] public string GameCode { get; set; } = string.Empty; [JsonProperty("game_code")] public string GameCode { get; set; } = string.Empty;
[JsonProperty("game_msg")] public string GameMessage { get; set; } = string.Empty; [JsonProperty("game_msg")] public string GameMessage { get; set; } = DEFAULT_GAME_MESSAGE;
[JsonProperty("luck_card")] public string LuckCard { get; set; } = string.Empty; [JsonProperty("luck_card")] public string LuckCard { get; set; } = string.Empty;
[JsonProperty("luck_crit")] public float LuckCrit { get; set; } [JsonProperty("luck_crit")] public float LuckCrit { get; set; }
[JsonProperty("new_card_list")] public string NewCardList { get; set; } = string.Empty; [JsonProperty("new_card_list")] public string NewCardList { get; set; } = string.Empty;
[JsonProperty("open_day_list")] public string OpenDayList { get; set; } = String.Empty; [JsonProperty("open_day_list")] public string OpenDayList { get; set; } = string.Empty;
[JsonProperty("is_open_day")] public int IsOpenDay { get; set; } [JsonProperty("is_open_day")] public int IsOpenDay { get; set; }
[JsonProperty("server_time")] public string ServerTime { get; set; } = string.Empty; [JsonProperty("server_time")] public string ServerTime { get; set; } = string.Empty;

View File

@@ -1,7 +1,7 @@
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
using Newtonsoft.Json; using Newtonsoft.Json;
namespace TOOHUCardAPI.Models namespace TOOHUCardAPI.DTO
{ {
public interface IMethodBasedRequest public interface IMethodBasedRequest
{ {

View File

@@ -1,6 +1,6 @@
using System.Collections.Generic; using System.Collections.Generic;
namespace TOOHUCardAPI.Models namespace TOOHUCardAPI.DTO
{ {
public class PlayerDataGetRequestObject public class PlayerDataGetRequestObject
{ {

View File

@@ -1,20 +1,35 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using AutoMapper;
using Newtonsoft.Json; using Newtonsoft.Json;
using TOOHUCardAPI.Data.Models;
namespace TOOHUCardAPI.Models namespace TOOHUCardAPI.DTO
{ {
public class PlayerDataGetResponseObject public class PlayerDataGetResponseObject
{ {
public Dictionary<int, PlayerDataGetResponseObjectPlayer> bo { get; set; } [JsonProperty("bo")]
public Dictionary<string, PlayerDataGetResponseObjectPlayer> Players { get; set; }
public PlayerDataGetResponseObject(int players) public PlayerDataGetResponseObject(Dictionary<string, User> users, IMapper mapper)
{ {
this.bo = new Dictionary<int, PlayerDataGetResponseObjectPlayer>(); this.Players = users.Aggregate(new Dictionary<string, PlayerDataGetResponseObjectPlayer>(),
foreach (int i in Enumerable.Range(0, players)) (players, pair) =>
{ {
bo[i] = new PlayerDataGetResponseObjectPlayer(); User user = pair.Value;
} players[pair.Key] = new PlayerDataGetResponseObjectPlayer()
{
EndTime = user.EndTime.ToShortDateString(),
KeyTotal = user.KeyTotal,
KeySaveDate = user.KeySaveDate.ToShortDateString(),
LevelList = user.LevelList,
MaxTeamWave = user.MaxTeamWave,
MaxWave = user.MaxWave,
PetLevel = user.PetLevel,
Point = user.Point
};
return players;
});
} }
} }
/** /**

View File

@@ -0,0 +1,19 @@
using Microsoft.EntityFrameworkCore;
using TOOHUCardAPI.Data.Models;
namespace TOOHUCardAPI.Data
{
public class AppDbContext : DbContext
{
public DbSet<User> Users { get; set; }
public AppDbContext(DbContextOptions options) : base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
}
}
}

View File

@@ -0,0 +1,15 @@
using AutoMapper;
using TOOHUCardAPI.Data.Models;
using TOOHUCardAPI.DTO;
namespace TOOHUCardAPI.Data
{
public class AutomapProfile : Profile
{
public AutomapProfile()
{
CreateMap<User, PlayerDataGetResponseObjectPlayer>();
CreateMap<User, User>();
}
}
}

View File

@@ -0,0 +1,12 @@
using System.ComponentModel.DataAnnotations;
namespace TOOHUCardAPI.Data.Models
{
public class EncodedCardGroup
{
[Key]
public int Id { get; set; }
public int CardGroupNumber { get; set; }
public string EncodedString { get; set; }
}
}

View File

@@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace TOOHUCardAPI.Data.Models
{
public class User
{
[Key]
public string SteamId { get; set; }
public int MaxWave { get; set; }
public int MaxTeamWave { get; set; }
public int PetLevel { get; set; }
public DateTime EndTime { get; set; }
public int KeyTotal { get; set; }
public DateTime KeySaveDate { get; set; }
public bool Vip { get; set; }
public int Point { get; set; }
public string LevelList { get; set; }
public List<EncodedCardGroup> EncodedCardGroups { get; set; }
}
}

View File

@@ -0,0 +1,58 @@
using System;
using System.Linq;
using AutoMapper;
using TOOHUCardAPI.Data.Models;
namespace TOOHUCardAPI.Data.Repositories
{
public class UserRepository
{
private readonly AppDbContext _appDbContext;
private readonly IMapper _mapper;
public UserRepository(AppDbContext appDbContext, IMapper mapper)
{
_appDbContext = appDbContext;
_mapper = mapper;
}
public User GetUser(string steamId)
{
return _appDbContext.Users.Where((user => user.SteamId.Equals(steamId))).FirstOrDefault();
}
public User CreateUser(string steamId)
{
User user = new User()
{
SteamId = steamId,
Vip = true,
EndTime = DateTime.MaxValue,
LevelList = string.Empty,
PetLevel = 1
};
_appDbContext.Users.Add(user);
_appDbContext.SaveChanges();
return user;
}
public User UpdateUser(User user)
{
var trackedUser = _appDbContext.Users.FirstOrDefault(u => u.SteamId == user.SteamId);
if (trackedUser == default)
{
return trackedUser;
}
_appDbContext.Update(user);
_appDbContext.SaveChanges();
return user;
}
public User GetOrCreateUser(string steamId)
{
User user = GetUser(steamId) ?? CreateUser(steamId);
return user;
}
}
}

View File

@@ -0,0 +1,91 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using TOOHUCardAPI.Data;
namespace TOOHUCardAPI.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20211028202203_initial")]
partial class initial
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "5.0.11");
modelBuilder.Entity("TOOHUCardAPI.Data.Models.EncodedCardGroup", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("EncodedString")
.HasColumnType("TEXT");
b.Property<string>("UserSteamId")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("UserSteamId");
b.ToTable("EncodedCardGroup");
});
modelBuilder.Entity("TOOHUCardAPI.Data.Models.User", b =>
{
b.Property<string>("SteamId")
.HasColumnType("TEXT");
b.Property<DateTime>("EndTime")
.HasColumnType("TEXT");
b.Property<DateTime>("KeySaveDate")
.HasColumnType("TEXT");
b.Property<int>("KeyTotal")
.HasColumnType("INTEGER");
b.Property<string>("LevelList")
.HasColumnType("TEXT");
b.Property<int>("MaxTeamWave")
.HasColumnType("INTEGER");
b.Property<int>("MaxWave")
.HasColumnType("INTEGER");
b.Property<int>("PetLevel")
.HasColumnType("INTEGER");
b.Property<int>("Point")
.HasColumnType("INTEGER");
b.Property<bool>("Vip")
.HasColumnType("INTEGER");
b.HasKey("SteamId");
b.ToTable("Users");
});
modelBuilder.Entity("TOOHUCardAPI.Data.Models.EncodedCardGroup", b =>
{
b.HasOne("TOOHUCardAPI.Data.Models.User", null)
.WithMany("EncodedCardGroups")
.HasForeignKey("UserSteamId");
});
modelBuilder.Entity("TOOHUCardAPI.Data.Models.User", b =>
{
b.Navigation("EncodedCardGroups");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,65 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace TOOHUCardAPI.Migrations
{
public partial class initial : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Users",
columns: table => new
{
SteamId = table.Column<string>(type: "TEXT", nullable: false),
MaxWave = table.Column<int>(type: "INTEGER", nullable: false),
MaxTeamWave = table.Column<int>(type: "INTEGER", nullable: false),
PetLevel = table.Column<int>(type: "INTEGER", nullable: false),
EndTime = table.Column<DateTime>(type: "TEXT", nullable: false),
KeyTotal = table.Column<int>(type: "INTEGER", nullable: false),
KeySaveDate = table.Column<DateTime>(type: "TEXT", nullable: false),
Vip = table.Column<bool>(type: "INTEGER", nullable: false),
Point = table.Column<int>(type: "INTEGER", nullable: false),
LevelList = table.Column<string>(type: "TEXT", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Users", x => x.SteamId);
});
migrationBuilder.CreateTable(
name: "EncodedCardGroup",
columns: table => new
{
Id = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
EncodedString = table.Column<string>(type: "TEXT", nullable: true),
UserSteamId = table.Column<string>(type: "TEXT", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_EncodedCardGroup", x => x.Id);
table.ForeignKey(
name: "FK_EncodedCardGroup_Users_UserSteamId",
column: x => x.UserSteamId,
principalTable: "Users",
principalColumn: "SteamId",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_EncodedCardGroup_UserSteamId",
table: "EncodedCardGroup",
column: "UserSteamId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "EncodedCardGroup");
migrationBuilder.DropTable(
name: "Users");
}
}
}

View File

@@ -0,0 +1,89 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using TOOHUCardAPI.Data;
namespace TOOHUCardAPI.Migrations
{
[DbContext(typeof(AppDbContext))]
partial class AppDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "5.0.11");
modelBuilder.Entity("TOOHUCardAPI.Data.Models.EncodedCardGroup", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("EncodedString")
.HasColumnType("TEXT");
b.Property<string>("UserSteamId")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("UserSteamId");
b.ToTable("EncodedCardGroup");
});
modelBuilder.Entity("TOOHUCardAPI.Data.Models.User", b =>
{
b.Property<string>("SteamId")
.HasColumnType("TEXT");
b.Property<DateTime>("EndTime")
.HasColumnType("TEXT");
b.Property<DateTime>("KeySaveDate")
.HasColumnType("TEXT");
b.Property<int>("KeyTotal")
.HasColumnType("INTEGER");
b.Property<string>("LevelList")
.HasColumnType("TEXT");
b.Property<int>("MaxTeamWave")
.HasColumnType("INTEGER");
b.Property<int>("MaxWave")
.HasColumnType("INTEGER");
b.Property<int>("PetLevel")
.HasColumnType("INTEGER");
b.Property<int>("Point")
.HasColumnType("INTEGER");
b.Property<bool>("Vip")
.HasColumnType("INTEGER");
b.HasKey("SteamId");
b.ToTable("Users");
});
modelBuilder.Entity("TOOHUCardAPI.Data.Models.EncodedCardGroup", b =>
{
b.HasOne("TOOHUCardAPI.Data.Models.User", null)
.WithMany("EncodedCardGroups")
.HasForeignKey("UserSteamId");
});
modelBuilder.Entity("TOOHUCardAPI.Data.Models.User", b =>
{
b.Navigation("EncodedCardGroups");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -6,11 +6,14 @@ using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Models;
using TOOHUCardAPI.Data;
using TOOHUCardAPI.Data.Repositories;
namespace TOOHUCardAPI namespace TOOHUCardAPI
{ {
@@ -27,6 +30,12 @@ namespace TOOHUCardAPI
public void ConfigureServices(IServiceCollection services) public void ConfigureServices(IServiceCollection services)
{ {
services.AddControllers().AddNewtonsoftJson(); services.AddControllers().AddNewtonsoftJson();
services.AddDbContext<AppDbContext>(opt =>
{
opt.UseSqlite(Configuration.GetConnectionString("Sqlite"));
});
services.AddScoped<UserRepository>();
services.AddAutoMapper(typeof(AutomapProfile));
services.AddSwaggerGen(c => services.AddSwaggerGen(c =>
{ {
c.SwaggerDoc("v1", new OpenApiInfo {Title = "TOOHUCardAPI", Version = "v1"}); c.SwaggerDoc("v1", new OpenApiInfo {Title = "TOOHUCardAPI", Version = "v1"});

View File

@@ -6,9 +6,20 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="AutoMapper" Version="10.1.1" />
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="8.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="5.0.11" /> <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="5.0.11" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.11">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="5.0.11" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="5.0.2" /> <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="5.0.2" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.6.3" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="5.6.3" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Folder Include="Migrations" />
</ItemGroup>
</Project> </Project>

View File

@@ -1,4 +1,7 @@
{ {
"ConnectionStrings": {
"Sqlite": "Data Source=test.db"
},
"Logging": { "Logging": {
"LogLevel": { "LogLevel": {
"Default": "Information", "Default": "Information",

BIN
TOOHUCardAPI/test.db Normal file

Binary file not shown.

BIN
TOOHUCardAPI/test.db-shm Normal file

Binary file not shown.

BIN
TOOHUCardAPI/test.db-wal Normal file

Binary file not shown.