9dff071b27aca50348cbd376b6be70753c5325f8
[r15k.git] / r15k / server / app / api.py
1 # -*- coding: utf-8 -*-
2
3 import logging
4 import json
5
6 import tornado.web as web
7
8 from r15k.engine.world import World
9 from r15k.engine.game import Game
10 from r15k.engine.game import Player
11 from r15k.server.datastore import Datastore
12
13 logger = logging.getLogger('r15k.api')
14
15 API_ROOT = r"/api"
16 PATTERN_ID = r"([\w\d]+)"
17
18
19 class GamesHandler(web.RequestHandler):
20 API_PATTERN_ITEMS = API_ROOT + r"/games"
21 API_PATTERN_ITEM = API_PATTERN_ITEMS + r"/%s"
22 API_ROUTE_ITEMS = API_PATTERN_ITEMS
23 API_ROUTE_ITEM = API_PATTERN_ITEM % (PATTERN_ID)
24
25 def get(self, id=None):
26 games = Datastore("/tmp/games")
27 if id:
28 if games.has_key(str(id)):
29 self.write(games.get(str(id)).dump())
30 return
31 data = []
32 for k in games.keys():
33 data.append(GamesHandler.API_PATTERN_ITEM % games.get(k).uid)
34 self.write({"games": data})
35
36 def post(self):
37 games = Datastore("/tmp/games")
38 logger.info("GAMES:Got %s" % (self.request.body))
39 data = json.loads(self.request.body)
40 if (data and data.has_key("size") and data.has_key("seed")):
41 W = World()
42 W.create(data)
43 game = Game(W)
44 games.set(game.uid, game)
45 games.commit()
46 self.write(GamesHandler.API_PATTERN_ITEM % game.uid)
47
48 class PlayersHandler(web.RequestHandler):
49 API_PATTERN_ITEMS = API_ROOT + r"/games/%s/players"
50 API_PATTERN_ITEM = API_PATTERN_ITEMS + r"/%s"
51 API_ROUTE_ITEMS = API_PATTERN_ITEMS % (PATTERN_ID)
52 API_ROUTE_ITEM = API_PATTERN_ITEM % (PATTERN_ID, PATTERN_ID)
53
54 def get(self, gameId, playerId=None):
55 games = Datastore("/tmp/games")
56 if gameId:
57 if games.has_key(str(gameId)):
58 if playerId:
59 game = games.get(str(gameId))
60 if game.players.has_key(str(playerId)):
61 self.write(game.players[str(playerId)].dump())
62 return
63 else:
64 dump = games.get(str(gameId)).dump()
65 data = []
66 for k, v in dump["players"].iteritems():
67 data.append(PlayersHandler.API_PATTERN_ITEM % v.uid)
68 self.write({"players": data})
69 return
70 raise web.HTTPError(400)
71
72 def post(self, gameId):
73 games = Datastore("/tmp/games")
74 if gameId:
75 if games.has_key(str(gameId)):
76 game = games.get(str(gameId))
77 data = json.loads(self.request.body)
78 if (data and data.has_key("user") and data.has_key("name")):
79 p = Player(data.get("name"), data.get("user"))
80 game.players[p.uid] = p
81 games.set(game.uid, game)
82 self.write(PlayersHandler.API_PATTERN_ITEM % (gameId, p.uid))
83 return
84 raise web.HTTPError(400)
85
86
87 class OrdersHandler(web.RequestHandler):
88 API_PATTERN_ITEMS = API_ROOT + r"/games/%s/players/%s/orders"
89 API_PATTERN_ITEM = API_PATTERN_ITEMS + r"/%s"
90 API_ROUTE_ITEMS = API_PATTERN_ITEMS % (PATTERN_ID, PATTERN_ID)
91 API_ROUTE_ITEM = API_PATTERN_ITEM % (PATTERN_ID, PATTERN_ID, PATTERN_ID)
92
93 def get(self, gameId, playerId, ordersId):
94 pass
95
96