Rename folder from Shogi.Sockets to Shogi.Api
This commit is contained in:
232
Shogi.Api/Repositories/GameboardRepository.cs
Normal file
232
Shogi.Api/Repositories/GameboardRepository.cs
Normal file
@@ -0,0 +1,232 @@
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Shogi.Contracts.Types;
|
||||
using Shogi.Api.Repositories.CouchModels;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Text;
|
||||
using Session = Shogi.Domain.Session;
|
||||
|
||||
namespace Shogi.Api.Repositories
|
||||
{
|
||||
public interface IGameboardRepository
|
||||
{
|
||||
Task CreateBoardState(Session session);
|
||||
Task CreateUser(Models.User user);
|
||||
Task<Collection<SessionMetadata>> ReadSessionMetadatas();
|
||||
Task<Session?> ReadSession(string name);
|
||||
Task UpdateSession(SessionMetadata session);
|
||||
Task<SessionMetadata?> ReadSessionMetaData(string name);
|
||||
Task<Models.User?> ReadUser(string userName);
|
||||
}
|
||||
|
||||
public class GameboardRepository
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns session, board state, and user documents, grouped by session.
|
||||
/// </summary>
|
||||
private static readonly string View_SessionWithBoardState = "_design/session/_view/session-with-boardstate";
|
||||
/// <summary>
|
||||
/// Returns session and user documents, grouped by session.
|
||||
/// </summary>
|
||||
private static readonly string View_SessionMetadata = "_design/session/_view/session-metadata";
|
||||
private static readonly string View_User = "_design/user/_view/user";
|
||||
private const string ApplicationJson = "application/json";
|
||||
private readonly HttpClient client;
|
||||
private readonly ILogger<GameboardRepository> logger;
|
||||
|
||||
public GameboardRepository(IHttpClientFactory clientFactory, ILogger<GameboardRepository> logger)
|
||||
{
|
||||
client = clientFactory.CreateClient("couchdb");
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
//public async Task<Collection<SessionMetadata>> ReadSessionMetadatas()
|
||||
//{
|
||||
// var queryParams = new QueryBuilder { { "include_docs", "true" } }.ToQueryString();
|
||||
// var response = await client.GetAsync($"{View_SessionMetadata}{queryParams}");
|
||||
// var responseContent = await response.Content.ReadAsStringAsync();
|
||||
// var result = JsonConvert.DeserializeObject<CouchViewResult<JObject>>(responseContent);
|
||||
// if (result != null)
|
||||
// {
|
||||
// var groupedBySession = result.rows.GroupBy(row => row.id);
|
||||
// var sessions = new List<SessionMetadata>(result.total_rows / 3);
|
||||
// foreach (var group in groupedBySession)
|
||||
// {
|
||||
// /**
|
||||
// * A group contains 3 elements.
|
||||
// * 1) The session metadata.
|
||||
// * 2) User document of Player1.
|
||||
// * 3) User document of Player2.
|
||||
// */
|
||||
// var session = group.FirstOrDefault()?.doc.ToObject<SessionDocument>();
|
||||
// var player1 = group.Skip(1).FirstOrDefault()?.doc.ToObject<UserDocument>();
|
||||
// var player2Doc = group.Skip(2).FirstOrDefault()?.doc;
|
||||
// if (session != null && player1 != null && player2Doc != null)
|
||||
// {
|
||||
// var player2 = IsUserDocument(player2Doc)
|
||||
// ? new Models.User(player2Doc.ToObject<UserDocument>()!)
|
||||
// : null;
|
||||
// //sessions.Add(new SessionMetadata(session.Name, session.IsPrivate, player1.Id, player2?.Id));
|
||||
// }
|
||||
// }
|
||||
// return new Collection<SessionMetadata>(sessions);
|
||||
// }
|
||||
// return new Collection<SessionMetadata>(Array.Empty<SessionMetadata>());
|
||||
//}
|
||||
|
||||
private static bool IsUserDocument(JObject player2Doc)
|
||||
{
|
||||
return player2Doc?.SelectToken(nameof(CouchDocument.DocumentType))?.Value<WhichDocumentType>() == WhichDocumentType.User;
|
||||
}
|
||||
|
||||
//public async Task<Session?> ReadSession(string name)
|
||||
//{
|
||||
// static Domain.ValueObjects.Piece? MapPiece(Piece? piece)
|
||||
// {
|
||||
// return piece == null
|
||||
// ? null
|
||||
// : Domain.ValueObjects.Piece.Create(piece.WhichPiece, piece.Owner, piece.IsPromoted);
|
||||
// }
|
||||
|
||||
// var queryParams = new QueryBuilder
|
||||
// {
|
||||
// { "include_docs", "true" },
|
||||
// { "startkey", JsonConvert.SerializeObject(new [] {name}) },
|
||||
// { "endkey", JsonConvert.SerializeObject(new object [] {name, int.MaxValue}) }
|
||||
// }.ToQueryString();
|
||||
// var query = $"{View_SessionWithBoardState}{queryParams}";
|
||||
// logger.LogInformation("ReadSession() query: {query}", query);
|
||||
// var response = await client.GetAsync(query);
|
||||
// var responseContent = await response.Content.ReadAsStringAsync();
|
||||
// var result = JsonConvert.DeserializeObject<CouchViewResult<JObject>>(responseContent);
|
||||
// if (result != null && result.rows.Length > 2)
|
||||
// {
|
||||
// var group = result.rows;
|
||||
// /**
|
||||
// * A group contains multiple elements.
|
||||
// * 0) The session metadata.
|
||||
// * 1) User documents of Player1.
|
||||
// * 2) User documents of Player1.
|
||||
// * 2.a) If the Player2 document doesn't exist, CouchDB will return the SessionDocument instead :(
|
||||
// * Everything Else) Snapshots of the boardstate after every player move.
|
||||
// */
|
||||
// var session = group[0].doc.ToObject<SessionDocument>();
|
||||
// var player1 = group[1].doc.ToObject<UserDocument>();
|
||||
// var player2Doc = group[2].doc;
|
||||
// var boardState = group.Last().doc.ToObject<BoardStateDocument>();
|
||||
|
||||
// if (session != null && player1 != null && boardState != null)
|
||||
// {
|
||||
// var player2 = IsUserDocument(player2Doc)
|
||||
// ? new Models.User(player2Doc.ToObject<UserDocument>()!)
|
||||
// : null;
|
||||
// var metaData = new SessionMetadata(session.Name, session.IsPrivate, player1.Id, player2?.Id);
|
||||
// var shogiBoardState = new BoardState(boardState.Board.ToDictionary(kvp => kvp.Key, kvp => MapPiece(kvp.Value)));
|
||||
// //return new Session(shogiBoardState, metaData);
|
||||
// }
|
||||
// }
|
||||
// return null;
|
||||
//}
|
||||
|
||||
//public async Task<SessionMetadata?> ReadSessionMetaData(string name)
|
||||
//{
|
||||
// var queryParams = new QueryBuilder
|
||||
// {
|
||||
// { "include_docs", "true" },
|
||||
// { "startkey", JsonConvert.SerializeObject(new [] {name}) },
|
||||
// { "endkey", JsonConvert.SerializeObject(new object [] {name, int.MaxValue}) }
|
||||
// }.ToQueryString();
|
||||
// var response = await client.GetAsync($"{View_SessionMetadata}{queryParams}");
|
||||
// var responseContent = await response.Content.ReadAsStringAsync();
|
||||
// var result = JsonConvert.DeserializeObject<CouchViewResult<JObject>>(responseContent);
|
||||
// if (result != null && result.rows.Length > 2)
|
||||
// {
|
||||
// var group = result.rows;
|
||||
// /**
|
||||
// * A group contains 3 elements.
|
||||
// * 1) The session metadata.
|
||||
// * 2) User document of Player1.
|
||||
// * 3) User document of Player2.
|
||||
// */
|
||||
// var session = group[0].doc.ToObject<SessionDocument>();
|
||||
// var player1 = group[1].doc.ToObject<UserDocument>();
|
||||
// var player2Doc = group[2].doc;
|
||||
// if (session != null && player1 != null)
|
||||
// {
|
||||
// var player2 = IsUserDocument(player2Doc)
|
||||
// ? new Models.User(player2Doc.ToObject<UserDocument>()!)
|
||||
// : null;
|
||||
// return new SessionMetadata(session.Name, session.IsPrivate, player1.Id, player2?.Id);
|
||||
// }
|
||||
// }
|
||||
// return null;
|
||||
//}
|
||||
|
||||
/// <summary>
|
||||
/// Saves a snapshot of board state and the most recent move.
|
||||
/// </summary>
|
||||
public async Task CreateBoardState(Session session)
|
||||
{
|
||||
var boardStateDocument = new BoardStateDocument(session.Name, session);
|
||||
var content = new StringContent(JsonConvert.SerializeObject(boardStateDocument), Encoding.UTF8, ApplicationJson);
|
||||
var response = await client.PostAsync(string.Empty, content);
|
||||
response.EnsureSuccessStatusCode();
|
||||
}
|
||||
|
||||
//public async Task<bool> CreateSession(SessionMetadata session)
|
||||
//{
|
||||
// var sessionDocument = new SessionDocument(session);
|
||||
// var sessionContent = new StringContent(JsonConvert.SerializeObject(sessionDocument), Encoding.UTF8, ApplicationJson);
|
||||
// var postSessionDocumentTask = client.PostAsync(string.Empty, sessionContent);
|
||||
|
||||
// var boardStateDocument = new BoardStateDocument(session.Name, new Session());
|
||||
// var boardStateContent = new StringContent(JsonConvert.SerializeObject(boardStateDocument), Encoding.UTF8, ApplicationJson);
|
||||
|
||||
// if ((await postSessionDocumentTask).IsSuccessStatusCode)
|
||||
// {
|
||||
// var response = await client.PostAsync(string.Empty, boardStateContent);
|
||||
// return response.IsSuccessStatusCode;
|
||||
// }
|
||||
|
||||
// return false;
|
||||
//}
|
||||
|
||||
//public async Task UpdateSession(SessionMetadata session)
|
||||
//{
|
||||
// // GET existing session to get revisionId.
|
||||
// var readResponse = await client.GetAsync(session.Name);
|
||||
// readResponse.EnsureSuccessStatusCode();
|
||||
// var sessionDocument = JsonConvert.DeserializeObject<SessionDocument>(await readResponse.Content.ReadAsStringAsync());
|
||||
|
||||
// // PUT the document with the revisionId.
|
||||
// var couchModel = new SessionDocument(session)
|
||||
// {
|
||||
// RevisionId = sessionDocument?.RevisionId
|
||||
// };
|
||||
// var content = new StringContent(JsonConvert.SerializeObject(couchModel), Encoding.UTF8, ApplicationJson);
|
||||
// var response = await client.PutAsync(couchModel.Id, content);
|
||||
// response.EnsureSuccessStatusCode();
|
||||
//}
|
||||
|
||||
//public async Task<bool> PutJoinPublicSession(PutJoinPublicSession request)
|
||||
//{
|
||||
// var content = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, MediaType);
|
||||
// var response = await client.PutAsync(JoinSessionRoute, content);
|
||||
// var json = await response.Content.ReadAsStringAsync();
|
||||
// return JsonConvert.DeserializeObject<PutJoinPublicSessionResponse>(json).JoinSucceeded;
|
||||
//}
|
||||
|
||||
//public async Task<string> PostJoinPrivateSession(PostJoinPrivateSession request)
|
||||
//{
|
||||
// var content = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, MediaType);
|
||||
// var response = await client.PostAsync(JoinSessionRoute, content);
|
||||
// var json = await response.Content.ReadAsStringAsync();
|
||||
// var deserialized = JsonConvert.DeserializeObject<PostJoinPrivateSessionResponse>(json);
|
||||
// if (deserialized.JoinSucceeded)
|
||||
// {
|
||||
// return deserialized.SessionName;
|
||||
// }
|
||||
// return null;
|
||||
//}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user