Skip to content

Commit

Permalink
Refactor DungeonRecordController
Browse files Browse the repository at this point in the history
  • Loading branch information
SapiensAnatis committed Aug 7, 2023
1 parent 3a63bba commit f17166f
Show file tree
Hide file tree
Showing 39 changed files with 836 additions and 118 deletions.
25 changes: 0 additions & 25 deletions DragaliaAPI.Database.Test/Repositories/QuestRepositoryTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,29 +49,4 @@ await this.fixture.AddRangeToDatabase(
)
.And.BeEquivalentTo(this.questRepository.Quests);
}

[Fact]
public async Task CompleteQuest_CompletesQuest()
{
DbQuest quest = await this.questRepository.CompleteQuest(3, 1.0f);

quest
.Should()
.BeEquivalentTo(
new DbQuest()
{
DeviceAccountId = "id",
QuestId = 3,
State = 3,
IsMissionClear1 = false,
IsMissionClear2 = false,
IsMissionClear3 = false,
PlayCount = 1,
DailyPlayCount = 1,
WeeklyPlayCount = 1,
IsAppear = true,
BestClearTime = 1.0f,
}
);
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@
namespace DragaliaAPI.Database.Migrations
{
/// <inheritdoc />
#pragma warning disable CS8981 // The type name only contains lower-cased ascii characters. Such names may become reserved for the language.
public partial class questclearparties : Migration
#pragma warning restore CS8981 // The type name only contains lower-cased ascii characters. Such names may become reserved for the language.
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
Expand Down
3 changes: 1 addition & 2 deletions DragaliaAPI.Database/Repositories/IQuestRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,5 @@ public interface IQuestRepository
{
IQueryable<DbQuest> Quests { get; }

Task<DbQuest> CompleteQuest(int questId, float clearTime);
Task UpdateQuestState(int questId, int state);
Task<DbQuest> GetQuestDataAsync(int questId);
}
1 change: 1 addition & 0 deletions DragaliaAPI.Database/Repositories/IUserDataRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,5 @@ public interface IUserDataRepository : IBaseRepository
Task UpdateDewpoint(int quantity);
Task<bool> CheckDewpoint(int quantity);
Task SetDewpoint(int quantity);
IQueryable<DbPlayerUserData> GetMultipleViewerData(IEnumerable<long> viewerIds);
}
5 changes: 5 additions & 0 deletions DragaliaAPI.Database/Repositories/QuestRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,11 @@ public async Task UpdateQuestState(int questId, int state)
questData.State = (byte)state;
}

public async Task<DbQuest> GetQuestDataAsync(int questId)
{
return await this.Quests.SingleAsync(x => x.QuestId == questId);
}

public async Task<DbQuest> CompleteQuest(int questId, float clearTime)
{
DbQuest? questData = await apiContext.PlayerQuests.SingleOrDefaultAsync(
Expand Down
5 changes: 5 additions & 0 deletions DragaliaAPI.Database/Repositories/UserDataRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,11 @@ public IQueryable<DbPlayerUserData> GetViewerData(long viewerId)
return this.apiContext.PlayerUserData.Where(x => x.ViewerId == viewerId);
}

public IQueryable<DbPlayerUserData> GetMultipleViewerData(IEnumerable<long> viewerIds)
{
return this.apiContext.PlayerUserData.Where(x => viewerIds.Contains(x.ViewerId));
}

public async Task<ISet<int>> GetTutorialFlags()
{
DbPlayerUserData userData = await UserData.SingleAsync();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
namespace DragaliaAPI.Integration.Test.Features.Dungeon;

/// <summary>
/// Tests <see cref="DragaliaAPI.Features.Dungeon.DungeonStartController"/>.
/// Tests <see cref="DragaliaAPI.Features.Dungeon.Start.DungeonStartController"/>.
/// </summary>
public class DungeonStartTest : TestFixture
{
Expand Down
7 changes: 4 additions & 3 deletions DragaliaAPI.Photon.Shared/DragaliaAPI.Photon.Shared.csproj
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="MessagePack" Version="2.5.108" />
<PackageReference Include="System.Text.Json" Version="8.0.0-preview.5.23280.8" />
<PackageReference Include="MessagePack" Version="2.5.108" />
<PackageReference Include="Redis.OM" Version="0.5.2"/>
<PackageReference Include="System.Text.Json" Version="8.0.0-preview.5.23280.8"/>
</ItemGroup>

</Project>
1 change: 1 addition & 0 deletions DragaliaAPI.Photon.Shared/Models/Player.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Redis.OM.Modeling;

namespace DragaliaAPI.Photon.Shared.Models
{
Expand Down
67 changes: 60 additions & 7 deletions DragaliaAPI.Photon.StateManager/Controllers/GetController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,58 +18,111 @@ namespace DragaliaAPI.Photon.StateManager.Controllers;
public class GetController : ControllerBase
{
private readonly IRedisConnectionProvider connectionProvider;
private readonly ILogger<GetController> logger;

private IRedisCollection<RedisGame> Games =>
this.connectionProvider.RedisCollection<RedisGame>();

private IRedisCollection<RedisGame> VisibleGames =>
this.Games.Where(x => x.Visible == true && x.RoomId > 0);

public GetController(IRedisConnectionProvider connectionProvider)
public GetController(IRedisConnectionProvider connectionProvider, ILogger<GetController> logger)
{
this.connectionProvider = connectionProvider;
this.logger = logger;
}

/// <summary>
/// Get a list of all open games.
/// </summary>
/// <returns></returns>
/// <returns>A list of games.</returns>
[HttpGet("[action]")]
[ProducesResponseType(typeof(IEnumerable<ApiGame>), StatusCodes.Status200OK)]
public async Task<ActionResult<IEnumerable<ApiGame>>> GameList([FromQuery] int? questId)
{
this.logger.LogDebug("Retrieving all open games.");

IRedisCollection<RedisGame> query = this.VisibleGames.Where(
x => x.MatchingType == MatchingTypes.Anyone
);

if (questId is not null)
{
this.logger.LogDebug("Filtering by quest ID {id}", questId);
query = query.Where(x => x.QuestId == questId);
}

IEnumerable<ApiGame> games = (await query.ToListAsync())
.Select(x => new ApiGame(x))
.ToList();

IEnumerable<ApiGame> games = (await query.ToListAsync()).Select(x => new ApiGame(x));
this.logger.LogDebug("Found {n} games", games.Count());

return this.Ok(games);
}

/// <summary>
/// Get a room by its room ID.
/// </summary>
/// <param name="roomId">The room ID.</param>
/// <returns>A room with that ID, or a 404 if not found.</returns>
[HttpGet("[action]/{roomId}")]
public async Task<ActionResult<ApiGame>> ById(int roomId)
{
IRedisCollection<RedisGame> query = this.VisibleGames.Where(x => x.RoomId == roomId);
this.logger.LogDebug("Searching for games with ID {roomId}", roomId);

RedisGame? game = await this.VisibleGames.FirstOrDefaultAsync(x => x.RoomId == roomId);

RedisGame? game = await query.FirstOrDefaultAsync();
if (game is null)
{
this.logger.LogDebug("Game not found.");
return this.NotFound();
}

this.logger.LogDebug("Found game: {@game}", game);
return this.Ok(new ApiGame(game));
}

/// <summary>
/// Get a value indicating whether the given <paramref name="viewerId"/> is a host in any room.
/// </summary>
/// <param name="viewerId">The viewer ID.</param>
/// <returns>True if a host, false if not.</returns>
[HttpGet("[action]/{viewerId}")]
public async Task<ActionResult<bool>> IsHost(long viewerId)
{
// TODO: Find out how to execute this query within Redis by sub-indexing the player list
this.logger.LogDebug("Checking whether player {viewerId} is a host in any game", viewerId);

bool result = (await this.Games.ToListAsync()).Any(
x => x.Players.Any(y => y.ActorNr == 1 && y.ViewerId == viewerId)
x => x.Players.Any(y => y.ViewerId == viewerId && y.ActorNr == 1)
);

this.logger.LogDebug("Result: {result}", result);

return this.Ok(result);
}

/// <summary>
/// Get the room that the given <paramref name="viewerId"/> is playing in.
/// </summary>
/// <param name="viewerId">The viewer ID.</param>
/// <returns>The room they are in, or 404 if not found.</returns>
[HttpGet("[action]/{viewerId}")]
public async Task<ActionResult<ApiGame>> ByViewerId(long viewerId)
{
this.logger.LogDebug("Searching for game containing player {viewerId}", viewerId);

RedisGame? game = (
await this.Games.OrderByDescending(x => x.StartEntryTimestamp).ToListAsync()
).FirstOrDefault(x => x.Players.Any(x => x.ViewerId == viewerId));

if (game is null)
{
this.logger.LogDebug("Could not find any game with given player.");
return this.NotFound("No game found.");
}

this.logger.LogDebug("Found player in game {@game}", game);
return new ApiGame(game);
}
}
4 changes: 4 additions & 0 deletions DragaliaAPI.Photon.StateManager/Models/RedisGame.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,14 @@ public class RedisGame : IGame
/// <inheritdoc/>
public DateTimeOffset StartEntryTime { get; set; } = DateTimeOffset.UtcNow;

[Indexed(Sortable = true)]
public long StartEntryTimestamp => StartEntryTime.ToUnixTimeSeconds();

/// <inheritdoc/>
public EntryConditions EntryConditions { get; set; } = new EntryConditions();

/// <inheritdoc/>
[Indexed(CascadeDepth = 1)]
public List<Player> Players { get; set; } = new List<Player>();

/// <summary>
Expand Down
2 changes: 1 addition & 1 deletion DragaliaAPI.Photon.StateManager/Program.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
using DragaliaAPI.Photon.StateManager;
using DragaliaAPI.Photon.StateManager.Authentication;
using DragaliaAPI.Photon.StateManager.Models;
using DragaliaAPI.Services.Health;
using Microsoft.AspNetCore.Authentication;
using Redis.OM;
using Redis.OM.Contracts;
Expand Down
6 changes: 3 additions & 3 deletions DragaliaAPI.Photon.StateManager/RedisHealthCheck.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@
using Redis.OM;
using Redis.OM.Contracts;

namespace DragaliaAPI.Services.Health;
namespace DragaliaAPI.Photon.StateManager;

public class RedisHealthCheck : IHealthCheck
{
private readonly IRedisConnectionProvider connectionprovider;

public RedisHealthCheck(IRedisConnectionProvider connectionProvider)
{
this.connectionprovider = connectionProvider;
connectionprovider = connectionProvider;
}

public async Task<HealthCheckResult> CheckHealthAsync(
Expand All @@ -21,7 +21,7 @@ public async Task<HealthCheckResult> CheckHealthAsync(
{
try
{
RedisReply reply = await this.connectionprovider.Connection.ExecuteAsync("PING");
RedisReply reply = await connectionprovider.Connection.ExecuteAsync("PING");
if (reply.Error)
{
return new HealthCheckResult(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
using DragaliaAPI.Database.Entities;
#if false
using DragaliaAPI.Database.Entities;
using DragaliaAPI.Database.Repositories;
using DragaliaAPI.Features.Dungeon;
using DragaliaAPI.Features.Event;
using DragaliaAPI.Features.Dungeon.Record;
using DragaliaAPI.Features.Missions;
using DragaliaAPI.Features.Player;
using DragaliaAPI.Features.Reward;
Expand Down Expand Up @@ -900,3 +902,4 @@ public MissionCompletionGenerator()
}
}
}
#endif
49 changes: 49 additions & 0 deletions DragaliaAPI/AutoMapper/Profiles/UnitMapProfile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,55 @@ public UnitMapProfile()

this.CreateMap<DbEditSkillData, EditSkillCharaData>();

// Entirely manually mapped, yay
this.CreateMap<DbDetailedPartyUnit, UserSupportList>()
// Manually mapped
.ForMember(x => x.viewer_id, opts => opts.Ignore())
.ForMember(x => x.name, opts => opts.Ignore())
.ForMember(x => x.level, opts => opts.Ignore())
.ForMember(x => x.last_login_date, opts => opts.Ignore())
.ForMember(x => x.emblem_id, opts => opts.Ignore())
.ForMember(x => x.guild, opts => opts.Ignore())
.ForMember(x => x.max_party_power, opts => opts.Ignore())
// Renamed
.ForMember(x => x.support_chara, opts => opts.MapFrom(y => y.CharaData))
.ForMember(x => x.support_weapon_body, opts => opts.MapFrom(y => y.WeaponBodyData))
.ForMember(x => x.support_dragon, opts => opts.MapFrom(y => y.DragonData))
.ForMember(
x => x.support_crest_slot_type_1_list,
opts => opts.MapFrom(y => y.CrestSlotType1CrestList)
)
.ForMember(
x => x.support_crest_slot_type_2_list,
opts => opts.MapFrom(y => y.CrestSlotType2CrestList)
)
.ForMember(
x => x.support_crest_slot_type_3_list,
opts => opts.MapFrom(y => y.CrestSlotType3CrestList)
)
.ForMember(x => x.support_talisman, opts => opts.MapFrom(y => y.TalismanData))
// Deprecated
.ForMember(x => x.support_weapon, opts => opts.Ignore())
.ForMember(x => x.support_amulet, opts => opts.Ignore())
.ForMember(x => x.support_amulet_2, opts => opts.Ignore());

this.CreateMap<DbPlayerCharaData, AtgenSupportChara>()
// No idea what this is
.ForMember(x => x.status_plus_count, opts => opts.Ignore());

this.CreateMap<DbWeaponBody, AtgenSupportWeaponBody>();

this.CreateMap<DbPlayerDragonData, AtgenSupportDragon>()
// Seems important but wasn't required for dungeon_start?
.ForMember(x => x.hp, opts => opts.Ignore())
.ForMember(x => x.attack, opts => opts.Ignore())
// No idea what this is
.ForMember(x => x.status_plus_count, opts => opts.Ignore());

this.CreateMap<DbAbilityCrest, AtgenSupportCrestSlotType1List>();

this.CreateMap<DbTalisman, AtgenSupportTalisman>();

this.DisableConstructorMapping();

this.SourceMemberNamingConvention = DatabaseNamingConvention.Instance;
Expand Down
10 changes: 8 additions & 2 deletions DragaliaAPI/Controllers/Dragalia/FriendController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,13 @@ FriendGetSupportCharaDetailRequest request
AtgenSupportUserDetailList helperDetail =
helperList.support_user_detail_list
.Where(helper => helper.viewer_id == request.support_viewer_id)
.FirstOrDefault() ?? new() { is_friend = false };
.FirstOrDefault()
?? new()
{
is_friend = false,
viewer_id = request.support_viewer_id,
gettable_mana_point = 50,
};

// TODO: when helpers are converted to use other account ids, get the bonuses of that account id
FortBonusList bonusList = await bonusService.GetBonusList();
Expand All @@ -71,7 +77,7 @@ FriendGetSupportCharaDetailRequest request
),
dragon_reliability_level = 30,
is_friend = helperDetail.is_friend,
apply_send_status = 0
apply_send_status = 0,
}
};

Expand Down
Loading

0 comments on commit f17166f

Please sign in to comment.