Repository navigation
Expand file tree
/
Copy pathdbs.py
More file actions
227 lines (169 loc) · 7.32 KB
/
Copy pathdbs.py
File metadata and controls
227 lines (169 loc) · 7.32 KB
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
import enum
from datetime import datetime, timedelta, timezone
import chess
from sqlalchemy import (
BigInteger,
Column,
DateTime,
Enum,
ForeignKey,
Index,
Integer,
String,
Text,
UniqueConstraint,
func,
)
from sqlalchemy.orm import relationship
from utility import Base, engine
# How long an unfinished puzzle or game review stays in the database.
SESSION_TTL = timedelta(hours=6)
def _expiry():
return datetime.now(timezone.utc) + SESSION_TTL
class GameResult(enum.Enum):
"""The three outcomes python-chess reports from ``Board.result()``."""
WHITE_WINS = "1-0"
BLACK_WINS = "0-1"
DRAW = "1/2-1/2"
class Difficulty(enum.Enum):
EASY = "easy"
MEDIUM = "medium"
HARD = "hard"
# Points awarded for solving a puzzle at each level.
PUZZLE_SCORES = {Difficulty.EASY: 10, Difficulty.MEDIUM: 30, Difficulty.HARD: 80}
def replay(moves, fen=None, parse_san=False):
"""Rebuild a board by replaying a whitespace-separated move list."""
board = chess.Board(fen) if fen else chess.Board()
for token in moves.split():
board.push(board.parse_san(token) if parse_san else chess.Move.from_uci(token))
return board
class Game(Base):
"""A finished game, kept for /view and /stats."""
__tablename__ = "games"
id = Column(Integer, primary_key=True, autoincrement=True)
server_id = Column(BigInteger, nullable=False)
white_id = Column(BigInteger, nullable=False)
black_id = Column(BigInteger, nullable=False)
result = Column(Enum(GameResult), nullable=False)
moves = Column(Text, nullable=False, default="") # space-separated UCI
start_time = Column(DateTime(timezone=True), nullable=False)
end_time = Column(DateTime(timezone=True), nullable=False, server_default=func.now())
# /stats and /view always look a member up within one server.
__table_args__ = (
Index("ix_games_server_white", "server_id", "white_id"),
Index("ix_games_server_black", "server_id", "black_id"),
)
@property
def move_list(self):
return [chess.Move.from_uci(token) for token in self.moves.split()]
@property
def length(self):
return len(self.moves.split())
def board_at(self, ply):
"""The position after ``ply`` half-moves."""
board = chess.Board()
for move in self.move_list[:ply]:
board.push(move)
return board
class ActiveGame(Base):
"""A game currently being played in a channel."""
__tablename__ = "active_games"
id = Column(Integer, primary_key=True, autoincrement=True)
server_id = Column(BigInteger) # null in DMs
channel_id = Column(BigInteger, nullable=False)
message_id = Column(BigInteger, nullable=False)
white_id = Column(BigInteger, nullable=False)
black_id = Column(BigInteger, nullable=False)
moves = Column(Text, nullable=False, default="") # space-separated UCI
start_time = Column(DateTime(timezone=True), nullable=False, server_default=func.now())
last_move_time = Column(DateTime(timezone=True), onupdate=func.now())
__table_args__ = (
# One game per channel, enforced by the database rather than by a
# check-then-insert that two concurrent /challenge calls could both pass.
UniqueConstraint("channel_id", name="uq_active_games_channel"),
Index("ix_active_games_white", "white_id"),
Index("ix_active_games_black", "black_id"),
)
@property
def board(self):
return replay(self.moves)
@property
def ply(self):
return len(self.moves.split())
def push(self, move):
"""Append a move. The board and ply follow from the move list."""
self.moves = f"{self.moves} {move.uci()}".strip()
def has_player(self, user_id):
return user_id in (self.white_id, self.black_id)
class PuzzleSession(Base):
"""A tactic a user is part-way through solving."""
__tablename__ = "puzzle_sessions"
id = Column(Integer, primary_key=True, autoincrement=True)
user_id = Column(BigInteger, nullable=False)
channel_id = Column(BigInteger, nullable=False)
message_id = Column(BigInteger, nullable=False)
difficulty = Column(Enum(Difficulty), nullable=False)
initial_fen = Column(String(90), nullable=False)
solution = Column(Text, nullable=False) # space-separated SAN
ply = Column(Integer, nullable=False, default=0) # solution moves played so far
started_at = Column(DateTime(timezone=True), nullable=False, server_default=func.now())
expires_at = Column(DateTime(timezone=True), nullable=False, default=_expiry)
__table_args__ = (
# One open puzzle per user per channel. Previously duplicates piled up
# and every read had to ORDER BY id DESC to find the live one.
UniqueConstraint("user_id", "channel_id", name="uq_puzzle_user_channel"),
Index("ix_puzzle_sessions_expiry", "expires_at"),
)
@property
def solution_moves(self):
return self.solution.split()
@property
def next_move(self):
"""The SAN of the move the solver has to find, or None if solved."""
moves = self.solution_moves
return moves[self.ply] if self.ply < len(moves) else None
@property
def is_solved(self):
return self.ply >= len(self.solution_moves)
@property
def board(self):
played = " ".join(self.solution_moves[: self.ply])
return replay(played, fen=self.initial_fen, parse_san=True)
@property
def score(self):
return PUZZLE_SCORES[self.difficulty]
class PuzzleAttempt(Base):
"""One solved puzzle. /stats aggregates these rather than reading counters."""
__tablename__ = "puzzle_attempts"
id = Column(Integer, primary_key=True, autoincrement=True)
user_id = Column(BigInteger, nullable=False)
server_id = Column(BigInteger, nullable=False)
difficulty = Column(Enum(Difficulty), nullable=False)
score = Column(Integer, nullable=False)
solved_at = Column(DateTime(timezone=True), nullable=False, server_default=func.now())
__table_args__ = (Index("ix_attempts_user_server", "user_id", "server_id"),)
class ReviewSession(Base):
"""A user stepping through a finished game with the arrow buttons.
Holds a reference to the game and a cursor into it, rather than its own copy
of the board and move list.
"""
__tablename__ = "review_sessions"
id = Column(Integer, primary_key=True, autoincrement=True)
user_id = Column(BigInteger, nullable=False)
channel_id = Column(BigInteger, nullable=False)
message_id = Column(BigInteger, nullable=False)
game_id = Column(Integer, ForeignKey("games.id", ondelete="CASCADE"), nullable=False)
ply = Column(Integer, nullable=False, default=0)
expires_at = Column(DateTime(timezone=True), nullable=False, default=_expiry)
game = relationship("Game")
__table_args__ = (
UniqueConstraint("message_id", "channel_id", name="uq_review_message"),
Index("ix_review_sessions_expiry", "expires_at"),
)
def purge_expired_sessions(session):
"""Drop abandoned puzzle and review rows. Safe to call on a schedule."""
now = datetime.now(timezone.utc)
removed = session.query(PuzzleSession).filter(PuzzleSession.expires_at < now).delete()
removed += session.query(ReviewSession).filter(ReviewSession.expires_at < now).delete()
return removed
Base.metadata.create_all(bind=engine)