Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add limit for dragons #792

Merged
merged 5 commits into from
May 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 1 addition & 4 deletions DragaliaAPI/DragaliaAPI.Database.Test/DbTestFixture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,6 @@ public DbTestFixture()
// Unused for creating saves
Mock<ILogger<SavefileService>> mockLogger = new(MockBehavior.Loose);
Mock<IDistributedCache> mockCache = new(MockBehavior.Loose);
// Used but we probably don't want it to actually add characters?
Mock<IUnitRepository> mockUnitRepository = new(MockBehavior.Loose);

SavefileService savefileService =
new(
Expand All @@ -40,8 +38,7 @@ public DbTestFixture()
).CreateMapper(),
mockLogger.Object,
IdentityTestUtils.MockPlayerDetailsService.Object,
Enumerable.Empty<ISavefileUpdate>(),
mockUnitRepository.Object
[]
);
savefileService.Create().Wait();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,19 +27,6 @@ public UserDataRepositoryTest(DbTestFixture fixture)
);
}

[Fact]
public async Task GetPlayerInfo_ValidId_ReturnsInfo()
{
(await this.userDataRepository.UserData.ToListAsync()).Should().NotBeEmpty();
}

[Fact]
public async Task GetPlayerInfo_InvalidId_ReturnsEmptyQueryable()
{
this.mockPlayerIdentityService.SetupGet(x => x.ViewerId).Returns(400);
(await this.userDataRepository.UserData.ToListAsync()).Should().BeEmpty();
}

[Fact]
public async Task UpdateName_UpdatesName()
{
Expand Down
12 changes: 12 additions & 0 deletions DragaliaAPI/DragaliaAPI.Database/ApiContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,10 @@ IPlayerIdentityService playerIdentityService

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder
.Entity<DbPlayerUserData>()
.HasQueryFilter(x => x.ViewerId == this.playerIdentityService.ViewerId);

modelBuilder
.Entity<DbPlayerCharaData>()
.HasQueryFilter(x => x.ViewerId == this.playerIdentityService.ViewerId);
Expand All @@ -158,5 +162,13 @@ protected override void OnModelCreating(ModelBuilder modelBuilder)
modelBuilder
.Entity<DbPlayerSummonHistory>()
.HasQueryFilter(x => x.ViewerId == this.playerIdentityService.ViewerId);

modelBuilder
.Entity<DbPlayerDragonData>()
.HasQueryFilter(x => x.ViewerId == this.playerIdentityService.ViewerId);

modelBuilder
.Entity<DbPlayerDragonReliability>()
.HasQueryFilter(x => x.ViewerId == this.playerIdentityService.ViewerId);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,15 @@ namespace DragaliaAPI.Database.Entities;
[Table("PlayerDragonData")]
public class DbPlayerDragonData : DbPlayerData, IHasXp
{
public DbPlayerDragonData() { }

public DbPlayerDragonData(long viewerId, Dragons id)
{
this.ViewerId = viewerId;
this.DragonId = id;
this.GetTime = DateTimeOffset.UtcNow;
}

[Column("DragonKeyId")]
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,24 +34,19 @@ public class DbPlayerDragonReliability : DbPlayerData, IHasXp
[Required]
[TypeConverter(typeof(DateTimeOffsetConverter))]
public DateTimeOffset GetTime { get; set; }
}

public static class DbPlayerDragonReliabilityFactory
{
public static DbPlayerDragonReliability Create(long viewerId, Dragons id)
public DbPlayerDragonReliability() { }

public DbPlayerDragonReliability(long viewerId, Dragons id)
{
byte defaultRelLevel = (byte)MasterAsset.DragonData.Get(id).DefaultReliabilityLevel;
defaultRelLevel = defaultRelLevel == default ? (byte)1 : defaultRelLevel;
DbPlayerDragonReliability newReliability =
new()
{
ViewerId = (int)viewerId,
DragonId = id,
Level = defaultRelLevel,
Exp = DragonConstants.BondXpLimits[defaultRelLevel - 1],
GetTime = DateTimeOffset.UtcNow,
LastContactTime = DateTimeOffset.UtcNow
};
return newReliability;

this.ViewerId = (int)viewerId;
this.DragonId = id;
this.Level = defaultRelLevel;
this.Exp = DragonConstants.BondXpLimits[defaultRelLevel - 1];
this.GetTime = DateTimeOffset.UtcNow;
this.LastContactTime = DateTimeOffset.UtcNow;
}
}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,6 @@ public interface IUnitRepository
IQueryable<DbAbilityCrest> AbilityCrests { get; }
IQueryable<DbTalisman> Talismans { get; }

Task<IEnumerable<(Charas id, bool isNew)>> AddCharas(IEnumerable<Charas> idList);

Task<bool> AddCharas(Charas id);

Task<IEnumerable<(Dragons Id, bool IsNew)>> AddDragons(IEnumerable<Dragons> idList);

Task<bool> AddDragons(Dragons id);

Task RemoveDragons(IEnumerable<long> keyIdList);

Task<DbSetUnit?> GetCharaSetData(Charas charaId, int setNo);
Expand Down
199 changes: 9 additions & 190 deletions DragaliaAPI/DragaliaAPI.Database/Repositories/UnitRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,6 @@
using DragaliaAPI.Shared.PlayerDetails;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using CharaNewCheckResult = (
DragaliaAPI.Shared.Definitions.Enums.Charas Id,
bool IsNew,
bool IsStoryNew
);
using DragonNewCheckResult = (
DragaliaAPI.Shared.Definitions.Enums.Dragons Id,
bool IsNew,
bool IsStoryNew
);

namespace DragaliaAPI.Database.Repositories;

Expand All @@ -30,10 +20,7 @@ public UnitRepository(ApiContext apiContext, IPlayerIdentityService playerIdenti
this.playerIdentityService = playerIdentityService;
}

public IQueryable<DbPlayerDragonData> Dragons =>
this.apiContext.PlayerDragonData.Where(x =>
x.ViewerId == this.playerIdentityService.ViewerId
);
public IQueryable<DbPlayerDragonData> Dragons => this.apiContext.PlayerDragonData;

public IQueryable<DbAbilityCrest> AbilityCrests =>
this.apiContext.PlayerAbilityCrests.Where(x =>
Expand All @@ -44,9 +31,7 @@ public UnitRepository(ApiContext apiContext, IPlayerIdentityService playerIdenti
this.apiContext.PlayerWeapons.Where(x => x.ViewerId == this.playerIdentityService.ViewerId);

public IQueryable<DbPlayerDragonReliability> DragonReliabilities =>
this.apiContext.PlayerDragonReliability.Where(x =>
x.ViewerId == this.playerIdentityService.ViewerId
);
this.apiContext.PlayerDragonReliability;

public IQueryable<DbTalisman> Talismans =>
this.apiContext.PlayerTalismans.Where(x =>
Expand Down Expand Up @@ -84,142 +69,6 @@ public UnitRepository(ApiContext apiContext, IPlayerIdentityService playerIdenti
return await apiContext.PlayerWeapons.FindAsync(playerIdentityService.ViewerId, weaponBody);
}

/// <summary>
/// Add a list of characters to the database. Will only add the first instance of any new character.
/// </summary>
/// <returns>A list of tuples which adds an additional dimension onto the input list,
/// where the second item shows whether the given character id was a duplicate.</returns>
public async Task<IEnumerable<(Charas id, bool isNew)>> AddCharas(IEnumerable<Charas> idList)
{
List<Charas> enumeratedIdList = idList.ToList();
IEnumerable<int> storyIdList = GetFirstCharaStories(enumeratedIdList);

// Generate result. The first occurrence of a character in the list should be new (if not in the DB)
// but subsequent results should then not be labelled as new.
List<Charas> ownedCharas = await this
.apiContext.PlayerCharaData.Select(x => x.CharaId)
.Where(x => enumeratedIdList.Contains(x))
.ToListAsync();

List<int> ownedCharaStories = await this
.apiContext.PlayerStoryState.Where(x =>
x.StoryType == StoryTypes.Chara && storyIdList.Contains(x.StoryId)
)
.Select(x => x.StoryId)
.ToListAsync();

// We also mark which stories are new. Ordinarily it is fine to assume if a character is new, then its story
// should be new. However, this has encountered occasional primary key errors from players who import saves
// after removing characters but not their story, which is not possible under normal circumstances.

List<CharaNewCheckResult> newMapping = MarkNewCharas(
ownedCharas,
ownedCharaStories,
enumeratedIdList
);

foreach (CharaNewCheckResult result in newMapping)
{
if (result.IsNew)
{
this.apiContext.PlayerCharaData.Add(
new DbPlayerCharaData(this.playerIdentityService.ViewerId, result.Id)
);
}

if (
result.IsStoryNew
&& MasterAsset.CharaStories.TryGetValue((int)result.Id, out StoryData? story)
)
{
apiContext.PlayerStoryState.Add(
new DbPlayerStoryState
{
ViewerId = this.playerIdentityService.ViewerId,
StoryType = StoryTypes.Chara,
StoryId = story.StoryIds[0],
State = 0
}
);
}
}

return newMapping.Select(x => (x.Id, x.IsNew));

static IEnumerable<int> GetFirstCharaStories(IEnumerable<Charas> charaIdList)
{
foreach (Charas c in charaIdList)
{
if (MasterAsset.CharaStories.TryGetValue((int)c, out StoryData? storyData))
{
yield return storyData.StoryIds[0];
}
}
}
}

public async Task<bool> AddCharas(Charas id)
{
return (await this.AddCharas(new[] { id })).First().isNew;
}

public async Task<IEnumerable<(Dragons Id, bool IsNew)>> AddDragons(IEnumerable<Dragons> idList)
{
List<Dragons> enumeratedIdList = idList.ToList();

List<Dragons> ownedDragons = await Dragons
.Select(x => x.DragonId)
.Where(x => enumeratedIdList.Contains(x))
.ToListAsync();
List<Dragons> ownedReliabilities = await DragonReliabilities
.Select(x => x.DragonId)
.Where(x => enumeratedIdList.Contains(x))
.ToListAsync();

List<DragonNewCheckResult> newMapping = MarkNewDragons(
ownedDragons,
ownedReliabilities,
enumeratedIdList
);

foreach ((Dragons id, _, bool isReliabilityNew) in newMapping)
{
// Not being in the dragon table doesn't mean a reliability doesn't exist
// as the dragon could've been sold
if (isReliabilityNew)
{
this.apiContext.Add(
DbPlayerDragonReliabilityFactory.Create(this.playerIdentityService.ViewerId, id)
);
}
}

this.apiContext.AddRange(
enumeratedIdList.Select(id =>
DbPlayerDragonDataFactory.Create(this.playerIdentityService.ViewerId, id)
)
);

return newMapping.Select(x => (x.Id, x.IsNew));
}

public async Task<bool> AddDragons(Dragons id)
{
return (await this.AddDragons(new[] { id })).First().IsNew;
}

public async Task RemoveDragons(IEnumerable<long> keyIdList)
{
IEnumerable<DbPlayerDragonData> ownedDragons = await Dragons
.Where(x =>
x.ViewerId == this.playerIdentityService.ViewerId
&& keyIdList.Contains(x.DragonKeyId)
)
.ToListAsync();

apiContext.PlayerDragonData.RemoveRange(ownedDragons);
}

public async Task<DbSetUnit?> GetCharaSetData(Charas charaId, int setNo)
{
return await apiContext.PlayerSetUnits.FindAsync(
Expand Down Expand Up @@ -289,47 +138,17 @@ int additionalAttack
.Entity;
}

public void RemoveTalisman(DbTalisman talisman)
{
apiContext.PlayerTalismans.Remove(talisman);
}

private static List<CharaNewCheckResult> MarkNewCharas(
List<Charas> owned,
List<int> ownedStories,
List<Charas> idList
)
public async Task RemoveDragons(IEnumerable<long> keyIdList)
{
List<CharaNewCheckResult> result = new();
foreach (Charas c in idList)
{
bool isCharaNew = !(result.Any(x => x.Id.Equals(c)) || owned.Contains(c));
bool isStoryNew =
isCharaNew
&& MasterAsset.CharaStories.TryGetValue((int)c, out StoryData? storyData)
&& !ownedStories.Contains(storyData.StoryIds[0]);

result.Add((c, isCharaNew, isStoryNew));
}
List<DbPlayerDragonData> ownedDragons = await apiContext
.PlayerDragonData.Where(x => keyIdList.Contains(x.DragonKeyId))
.ToListAsync();

return result;
apiContext.PlayerDragonData.RemoveRange(ownedDragons);
}

private static List<DragonNewCheckResult> MarkNewDragons(
List<Dragons> owned,
List<Dragons> ownedReliabilities,
List<Dragons> idList
)
public void RemoveTalisman(DbTalisman talisman)
{
List<DragonNewCheckResult> result = new();
foreach (Dragons c in idList)
{
bool isDragonNew = !(result.Any(x => x.Id.Equals(c)) || owned.Contains(c));
bool isReliabilityNew = isDragonNew && !ownedReliabilities.Contains(c);

result.Add((c, isDragonNew, isReliabilityNew));
}

return result;
apiContext.PlayerTalismans.Remove(talisman);
}
}
Loading