/
api.py
439 lines (409 loc) · 18.7 KB
/
api.py
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
from google.appengine.api import memcache
from models import StringMessage
from google.appengine.ext import db
from google.appengine.api import taskqueue
from settings import WEB_CLIENT_ID
import endpoints
from protorpc import messages, message_types, remote
from models import PlayerForm, Player, ConflictException
from models import Game, GameForm, GamesForm
from models import PlayersRankForm, BooleanMessage
from models import Move, MovesForm
from google.appengine.ext import ndb
from datetime import datetime, timedelta
from google.appengine.api import mail
from google.appengine.api import app_identity
EMAIL_SCOPE = endpoints.EMAIL_SCOPE
API_EXPLORER_CLIENT_ID = endpoints.API_EXPLORER_CLIENT_ID
PLAYER_REQUEST = endpoints.ResourceContainer(
message_types.VoidMessage,
user_name=messages.StringField(1),
email=messages.StringField(2))
PLAYER_MINI_REQUEST = endpoints.ResourceContainer(
message_types.VoidMessage,
player_name=messages.StringField(1))
GAME_CREATE_REQUEST = endpoints.ResourceContainer(
message_types.VoidMessage,
game_name=messages.StringField(1), # give the game a name
player_name=messages.StringField(2)
)
GAME_GET_REQUEST = endpoints.ResourceContainer(
message_types.VoidMessage,
websafeGameKey=messages.StringField(1),
)
GAME_JOIN_REQUEST = endpoints.ResourceContainer(
message_types.VoidMessage,
player_name=messages.StringField(1),
websafeGameKey=messages.StringField(2))
GAME_MOVE_REQUEST = endpoints.ResourceContainer(
message_types.VoidMessage,
websafeGameKey=messages.StringField(1),
positionTaken=messages.IntegerField(2),
player_name=messages.StringField(3)
)
MEMCACHE_ANNOUNCEMENTS_KEY = "Recent Announcements"
DEFAULTS = {
"seatsAvailable": 2,
"gameOver": False,
"gameCurrentMove": 0,
"name": ''
}
@endpoints.api(name='tictactoe',
version='v1',
allowed_client_ids=[WEB_CLIENT_ID, API_EXPLORER_CLIENT_ID],
scopes=[EMAIL_SCOPE])
class TictactoeApi(remote.Service):
"""Tictactoe API v0.1"""
@endpoints.method(request_message=PLAYER_REQUEST,
response_message=PlayerForm,
path='user',
name='create_player',
http_method='POST')
def createPlayer(self, request):
"""
Create a Player. Requires a unique username; (an authenticated Google
user can create multiple Players as long as the entered user_name is
unique.)
"""
if request.user_name is None or request.email is None:
raise endpoints.UnauthorizedException(
'Need user_name and email to create a player.')
if Player.query(Player.displayName == request.user_name).get():
raise endpoints.ConflictException(
'A Player with that name already exists!')
player = Player(displayName=request.user_name, mainEmail=request.email)
player.put()
return player._copyPlayerToForm
@endpoints.method(GAME_CREATE_REQUEST, GameForm,
path='create_game',
http_method='POST',
name='create_game')
def createGame(self, request):
"""
a player creates a game of a unique name
"""
if request.game_name is None:
raise endpoints.UnauthorizedException(
'game_name is required to create a game')
player = Player.query(Player.displayName == request.player_name).get()
if not player:
raise endpoints.NotFoundException(
'No player found with name: {}' .format(request.player_name))
elif Game.query(Game.name == request.game_name).get():
raise endpoints.ConflictException(
'A Game with that name already exists!')
else:
# allocate new Game ID with Player key as parent
# allocate_ids(size=None, max=None, parent=None, **ctx_options)
# returns a tuple with (start, end) for the allocated range,
# inclusive.
p_key = player.key
g_id = Game.allocate_ids(size=1, parent=p_key)[0]
# make Game key from ID; assign initial values to the game entity
g_key = ndb.Key(Game, g_id, parent=p_key)
data = {} # is a dict
data['key'] = g_key
data['name'] = request.game_name
data['board'] = ['' for _ in range(9)]
Game(**data).put()
taskqueue.add(params={'email': player.mainEmail,
'gameInfo': repr(request)},
url='/tasks/send_confirmation_email')
game = g_key.get()
return game._copyGameToForm
@endpoints.method(message_types.VoidMessage, GamesForm,
path='all_games', http_method='GET', name='all_games')
def allGames(self, request):
"""
This returns all games ever created by anyone on this app, sorted by
seatsAvailable.
"""
games = Game.query().fetch()
items = [game._copyGameToForm for game in games if game]
# sort by
sorted_items = sorted(
items, key=lambda gf: gf.seatsAvailable, reverse=True)
return GamesForm(items=sorted_items)
@endpoints.method(GAME_JOIN_REQUEST, GameForm,
path='participate_game/{websafeGameKey}',
http_method='POST',
name='participate_game')
def participateGame(self, request):
"""
Sign a player(identifiable by player_name) up for a game (identifiable
by key); can not play against self
"""
# get the specified game
game_key = ndb.Key(urlsafe=request.websafeGameKey)
game = game_key.get()
if not game:
raise endpoints.NotFoundException(
'No game found with key: {}' .format(request.websafeGameKey))
# get the requested player
player = Player.query(Player.displayName == request.player_name).get()
if not player:
raise endpoints.NotFoundException(
'No player with name {} found' .format(request.player_name))
# check if the player has already signed up
elif game_key.urlsafe() in player.gamesInProgress:
raise ConflictException(
"You have already registered for this game")
# update the specified game
elif game.playerOne is None:
setattr(game, 'playerOne', request.player_name)
player.gamesInProgress.append(game_key.urlsafe())
game.seatsAvailable -= 1
elif game.playerTwo is None:
game.playerTwo = request.player_name
player.gamesInProgress.append(game_key.urlsafe())
game.seatsAvailable -= 1
else:
raise endpoints.UnauthorizedException(
'Sorry, both spots taken!')
game.put()
player.put()
return game._copyGameToForm
@endpoints.method(GAME_GET_REQUEST, GameForm,
path='game/{websafeGameKey}',
http_method='GET', name='get_game')
def getGame(self, request):
"""Return requested game (by websafeGameKey)."""
# get Game object from request; bail if not found
game = ndb.Key(urlsafe=request.websafeGameKey).get()
if not game:
raise endpoints.NotFoundException(
'No game found with key: {}' .format(request.websafeGameKey))
# return GameForm
return game._copyGameToForm
@endpoints.method(GAME_JOIN_REQUEST, GameForm,
path='cancel_game/{websafeGameKey}',
http_method='DELETE', name='cancel_game')
def cancelGame(self, request):
"""
Cancels a user from a game if the game is not complete AND no player
has ever made a first move.
"""
g_key = ndb.Key(urlsafe=request.websafeGameKey)
game = g_key.get()
player = Player.query(Player.displayName == request.player_name).get()
if player is None:
raise endpoints.NotFoundException(
'No player found with name: {}' .format(request.player_name))
elif game is None:
raise endpoints.NotFoundException(
'No game found with key: {}' % request.player_name)
elif g_key.urlsafe() in player.gamesCompleted:
raise endpoints.UnauthorizedException(
'Player can not cancel completed games')
elif game.gameCurrentMove > 0:
raise endpoints.UnauthorizedException(
'Players can not cancel once the first has been made')
elif g_key.urlsafe() in player.gamesInProgress:
# cancel player, add back one seat
player.gamesInProgress.remove(g_key.urlsafe())
game.seatsAvailable += 1
# update game's player status
if player.displayName == game.playerOne:
game.playerOne = None
if player.displayName == game.playerTwo:
game.playerTwo = None
else:
raise endpoints.NotFoundException(
'Player {} is not signed up with game {}' .format(
request.player_name, request.websafeGameKey))
# write things back to the datastore & return
player.put()
game.put()
return game._copyGameToForm
@endpoints.method(PLAYER_MINI_REQUEST, GamesForm,
path='games', http_method='GET', name='get_user_games')
def getPlayerGames(self, request):
"""
This returns all games a player has signed up for but has not
completed, i.e., those in the gamesInProgress list.
"""
if request.player_name is None:
raise endpoints.NotFoundException('You did not enter player_name')
else:
player = Player.query(
Player.displayName == request.player_name).get()
if player is None:
raise endpoints.NotFoundException(
'No player by the name of {}' .format(request.player_name))
else:
game_keys = getattr(player, 'gamesInProgress')
key_objects = [ndb.Key(urlsafe=key) for key in game_keys]
# Use get_multi(array_of_keys) to fetch all games at once.
games = ndb.get_multi(key_objects)
if not games:
raise endpoints.NotFoundException(
'Not a single active game is this player {}' .format(
request.player_name))
return GamesForm(
items=[game._copyGameToForm for game in games if game])
@endpoints.method(GAME_MOVE_REQUEST, GameForm,
path='make_move/{websafeGameKey}/{positionTaken}',
http_method='POST',
name='make_move')
def makeMove(self, request):
"""
authenticated player makes a move, implemented by creating a move,
updating Game and Player
"""
g_key = ndb.Key(urlsafe=request.websafeGameKey)
game = g_key.get()
# set up for a move
m_id = Move.allocate_ids(size=1, parent=g_key)[0]
m_key = ndb.Key(Move, m_id, parent=g_key)
player = Player.query(Player.displayName == request.player_name).get()
next_player_name = game.playerTwo if player.displayName == game.playerOne else game.playerOne
next_player = Player.query(Player.displayName == next_player_name).get()
print('next_player', next_player_name)
if game.gameOver:
raise endpoints.UnauthorizedException('This game is already over.')
# check if game is signed up by two players and by the current player
elif game.playerOne is None or game.playerTwo is None:
raise endpoints.UnauthorizedException(
'Need 2 signed-up players to start')
elif not player:
raise endpoints.NotFoundException('no player found')
elif player.displayName not in [game.playerTwo, game.playerOne]:
raise endpoints.UnauthorizedException('You did not sign up')
# check if the player had played the last move
elif player.displayName != game.nextPlayer is not None:
raise endpoints.UnauthorizedException(
"Player {}, it is your opponent {}'s turn" .format(
player.displayName, game.nextPlayer))
elif game.board[request.positionTaken] != '':
raise endpoints.UnauthorizedException('The game board position {} \
is already taken' .format(request.positionTaken))
else:
data = {}
data['key'] = m_key
data['moveNumber'] = game.gameCurrentMove + 1
data['playerName'] = player.displayName
data['positionTaken'] = request.positionTaken
Move(**data).put()
move = m_key.get()
# Update Game on the position affected by the move, and player
game.gameCurrentMove += 1
game.board[request.positionTaken] = request.player_name
setattr(game, 'nextPlayer', next_player_name)
if game._isWon:
setattr(game, 'gameWinner', getattr(player,'displayName'))
# if no win and game.gameCurrentMove >= 9, it is a tie;
# declare the winner as 'tie'
if game.gameCurrentMove > 9:
setattr(game, 'gameWinner', 'tie')
if game._isWon or game.gameCurrentMove > 9:
setattr(game, 'gameOver', True)
player.gamesInProgress.remove(g_key.urlsafe())
player.gamesCompleted.append(g_key.urlsafe())
next_player.gamesInProgress.remove(g_key.urlsafe())
next_player.gamesCompleted.append(g_key.urlsafe())
# if no winner at step before 9, send a move invite to the opponent
game.put()
player.put()
next_player.put()
return game._copyGameToForm
@endpoints.method(message_types.VoidMessage, BooleanMessage,
path='delete_all_games', http_method='POST',
name='delete_all_games')
def deleteAllGames(self, request):
"""
deleting all Games created by current player, except those that are
played.
"""
# keys_only:All operations return keys instead of entities.
ndb.delete_multi(Game.query().fetch(keys_only=True))
deleted = True
return BooleanMessage(data=deleted)
@endpoints.method(message_types.VoidMessage, PlayersRankForm,
path='players_ranking', http_method='GET',
name='get_user_rankings')
def getPlayerRankings(self, request):
"""
a list consisting of each Player's name and the winning percentage
"""
players = Player.query().fetch()
items = [p._copyPlayerToRankForm for p in players]
sorted_items = sorted(
items, key=lambda prf: prf.percentage, reverse=True)
return PlayersRankForm(items=sorted_items)
@endpoints.method(GAME_GET_REQUEST, MovesForm,
path='game_history/{websafeGameKey}',
http_method='GET', name='get_game_history')
def getGameHistory(self, request):
""" shows a list of all the moves for each game"""
game_key = ndb.Key(urlsafe=request.websafeGameKey)
moves = Move.query(ancestor=game_key).fetch()
if not moves:
raise endpoints.NotFoundException('No moves found')
else:
return MovesForm(items=[move._copyMoveToForm for move in moves])
# - - - Announcements - - - - - - - - - - - - - - - - - - - -
@staticmethod
def _cacheAnnouncement():
"""Create Announcement & assign to memcache; used by
memcache cron job & getAnnouncement().
"""
games = Game.query(Game.seatsAvailable != 0).fetch()
if games:
# If there are games ready for sign up,
# format announcement and set it in memcache
announcement = '{} {}' .format(
'Come play...The following games need more player!',
', '.join(game.name or '' for game in games))
memcache.set(MEMCACHE_ANNOUNCEMENTS_KEY, announcement)
else:
# If there are no available games,
# delete the memcache announcements entry
announcement = ""
memcache.delete(MEMCACHE_ANNOUNCEMENTS_KEY)
return announcement
@staticmethod
def _prepReminder():
games = Game.query(
Game.gameCurrentMove < 9 and Game.gameCurrentMove > 0).fetch()
remindees = ''
if games:
# If there are games ready for sign up,
# format announcement and set it in memcache for each game
for game in games:
last_move = Move.query(
Move.moveNumber==game.gameCurrentMove-1).get()
if last_move:
current_time = datetime.utcnow()
if last_move.moveTime and (current_time - last_move.moveTime > timedelta(days=5)):
next_player = Player.query(Player.displayName == game.nextPlayer).get()
if next_player.mainEmail:
print 'next_player.mainEmail', next_player.mainEmail
remindees.join(next_player.displayName)
mail.send_mail(
'noreply@{}.appspotmail.com' .format(
app_identity.get_application_id()),
next_player.mainEmail,
'Coming back to tic-tac-toe?',
'It has been 5 days since the last move on:\r\n\r\n{}' .format(
game.name)
)
return remindees
@endpoints.method(message_types.VoidMessage, StringMessage,
path='tictactoe/announcement/get',
http_method='GET', name='get_announcement')
def getAnnouncement(self, request):
"""Return Announcement from memcache."""
self._cacheAnnouncement()
announcement = memcache.get(MEMCACHE_ANNOUNCEMENTS_KEY)
if not announcement:
announcement = ""
return StringMessage(data=announcement)
@endpoints.method(message_types.VoidMessage, StringMessage,
path='tictactoe/move_reminders/get',
http_method='GET', name='get_move_reminders')
def getMoveReminder(self, request):
"""Return move reminders."""
reminder = self._prepReminder()
return StringMessage(data='Reminders for {} set up!' .format(reminder))
# registers API
api = endpoints.api_server([TictactoeApi])