-
Notifications
You must be signed in to change notification settings - Fork 0
/
GameRepository.cs
199 lines (171 loc) · 7.6 KB
/
GameRepository.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
using Api.Domain;
using MongoDB.Driver;
using MongoDB.Driver.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MongoDB.Thin;
namespace Api.Persistence
{
public class GameRepository : IGameRepository
{
private readonly IMongoCollection<Game> _games;
private readonly IMongoCollection<Player> _players;
private const int MaxItemsReturned = 50;
public GameRepository(IMongoDatabase database)
{
_games = database.Collection<Game>();
_players = database.Collection<Player>();
}
public Task<IEnumerable<Player.Game>> GetPlayerGamesAsync(string playerId)
{
return GetPlayerGamesAsync(playerId, null);
}
public async Task<IEnumerable<Player.Game>> GetPlayerGamesAsync(string playerId, GameStatus? status)
{
var query = _players.AsQueryable()
.Where(p => p.Id == playerId)
.SelectMany(p => p.Games);
if (status != null)
{
query = query.Where(g => g.Status == status);
}
return await query
.OrderByDescending(p => p.AcceptedAt)
.Take(MaxItemsReturned)
.ToListAsync();
}
public async Task<bool> CreatePlayerIfNotExistingAsync(Player player)
{
var result = await _players
.UpdateOneAsync(
p => p.Id == player.Id,
Builders<Player>.Update
.SetOnInsert(p => p.Id, player.Id)
.SetOnInsert(p => p.Name, player.Name)
.SetOnInsert(p => p.SchemaVersion, player.SchemaVersion)
.SetOnInsert(p => p.Games, (IEnumerable<Player.Game>)player.Games ?? Array.Empty<Player.Game>()),
new UpdateOptions { IsUpsert = true });
if (result.MatchedCount == 0)
{
if (result.UpsertedId == null) throw new InsertException();
return true;
}
else // already existing
{
return false;
}
}
public async Task AddOrUpdatePlayerGameAsync(string playerId, Player.Game game)
{
// First try to add it, if not there yet
var updateResult = await _players.UpdateOne()
.Filter(b => b.Match(p => p.Id == playerId && !p.Games.Any(g => g.Id == game.Id)))
.Update(b => b.Modify(p => p.Push(g => g.Games, game)))
.ExecuteAsync();
if (updateResult.MatchedCount == 0) // game is already part of Games array, so we need to update it
{
var command = _players.UpdateOne()
.Filter(b => b.Match(p => p.Id == playerId))
.Options(b => b.WithArrayFilter($"{{ 'x._id' : '{game.Id}' }}"))
.Update(b => b
.Modify($"{{ $set : {{ 'Games.$[x].Status' : {(int)game.Status} }} }}")
.Modify($"{{ $set : {{ 'Games.$[x].PlayerGameStatus' : {(int)game.PlayerGameStatus} }} }}"));
if (game.StartedAt.HasValue)
{
command = command.Update(b => b.Modify($"{{ $set : {{ 'Games.$[x].StartedAt' : '{game.StartedAt.Value.ToIso()}' }} }}"));
}
if (game.EndedAt.HasValue)
{
command = command.Update(b => b.Modify($"{{ $set : {{ 'Games.$[x].EndedAt' : '{game.EndedAt.Value.ToIso()}' }} }}"));
}
updateResult = await command.ExecuteAsync();
if (updateResult.MatchedCount == 0)
{
throw new UpdateException();
}
}
}
public async Task<IEnumerable<Game>> GetPlayableGamesAsync(string playerId, IEnumerable<GameType> gameTypes, IEnumerable<GameStatus> statuses)
{
return await _games.AsQueryable()
.Where(g => !g.Players.Any(p => p.Id == playerId))
.Where(g => gameTypes.Contains(g.GameType) && statuses.Contains(g.Status))
.Take(MaxItemsReturned)
.ToListAsync();
}
public async Task<TGame?> GetAsync<TGame>(string id)
where TGame : Game
{
var game = await _games.FindOneAsync(g => g.Id == id);
if (game != null && !(game is TGame))
{
throw new InvalidOperationException($"Cannot cast game to a different type of game: game with '{id}' is a {game.GetType().Name} not a {typeof(TGame).Name}");
}
return (TGame?)game;
}
public Task<int> GetNumberOfGamesAsync(string playerId)
{
return _games.AsQueryable()
.Where(g => g.Players.Any(p => p.Id == playerId))
.Where(g => g.Status == GameStatus.WaitingForPlayers || g.Status == GameStatus.InGame)
.CountAsync();
}
public async Task<TGame> CreateGameAsync<TGame>(TGame game)
where TGame : Game
{
await _games.InsertOneAsync(game);
return game;
}
public async Task<Game?> AddPlayerToGameIfNotThereAsync(string id, Game.Player player)
{
return await _games.FindOneAndUpdate()
.Filter(b => b.Match(g => g.Id == id && !g.Players.Any(p => p.Id == player.Id) && g.Status == GameStatus.WaitingForPlayers))
.Update(b => b
.Modify(g => g.Push(g => g.Players, player))
.Modify(g => g.Inc(g => g.PlayersCount, 1))
.Modify(g => g.Inc(g => g.Version, 1)))
.ExecuteAsync();
}
public async Task<Game?> AddPlayerToGameAsync(GameType gameType, int? maxPlayers, int? duration, Game.Player player)
{
var command = _games.FindOneAndUpdate();
command.Filter(b => b.Match(g =>
g.GameType == gameType &&
!g.Players.Any(p => p.Id == player.Id) &&
g.Status == GameStatus.WaitingForPlayers));
if (maxPlayers.HasValue)
{
command = command.Filter(b => b.Match(g => g.MaxPlayers <= maxPlayers));
}
if (duration.HasValue)
{
command = command.Filter(b => b.Match(g => g.MaxDuration <= duration));
}
var game = await command.Update(b => b
.Modify(g => g.Push(g => g.Players, player))
.Modify(g => g.Inc(g => g.PlayersCount, 1))
.Modify(g => g.Inc(g => g.Version, 1)))
.ExecuteAsync();
return game;
}
public async Task<Game?> StartGameAsync(string id, IReadOnlyList<int> playerOrders)
{
var command = _games.FindOneAndUpdate()
.Filter(b => b.Match(g => g.Id == id && g.Status == GameStatus.WaitingForPlayers))
.Update(b => b
.Modify(g => g.Status, GameStatus.InGame)
.Modify(g => g.StartedAt, DateTime.UtcNow)
.Modify(g => g.Inc(g => g.Version, 1)));
for (var i = 0; i < playerOrders.Count; i++)
{
var playOrder = playerOrders[i];
command = command.Update(b => b.Modify($"{{ $set : {{ 'Players.{i}.PlayOrder' : {playOrder} }} }}"));
}
return await command.ExecuteAsync();
}
public async Task RemoveAsync(string id) =>
await _games.DeleteOneAsync(g => g.Id == id);
}
}