-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
382 lines (304 loc) · 13.9 KB
/
main.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
#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import datetime
import logging
import webapp2
import json
import urllib
import random
from facebook import *
from google.appengine.api import users
from google.appengine.ext.webapp import template
from facebook import FBRequestHandler
from models import Hacker, Queue, Match, Project, Channel
from channel import broadcast, RequestChannelHandler
from google.appengine.api import channel
#TODO: Investigate JS templating?
#template.register_template_library('verbatimtemplatetag')
def broadcast(match, msg):
for user in match.users:
channel.send_message(user, msg)
def message(user, msg):
channel.send_message(user, msg)
def initChannel(userid):
#Refreshes the channel api
chan = Channel.get_by_key_name(userid)
if not chan:
chan = Channel(key_name = userid)
chan.token = channel.create_channel(userid, duration_minutes=5)
chan.put()
return chan.token
def getCurrentMatchByUser(current_user_id):
#Gets the match the user is currently participating in, or None if no match started.
#TODO: Check & Confirm creation order
hackathon = Match.all().filter("users =", current_user_id).order("-created").get()
if not hackathon or (100 in hackathon.outcome): #Most recent is nonexistant or completed
return None
return hackathon
# -------------- Template pages -----------------
class HomepageHandler(webapp2.RequestHandler):
def post(self):
self.get()
def get(self):
path = os.path.join(os.path.dirname(__file__), 'homepage.html')
self.response.out.write(template.render(path, {}))
class CreationHandler(FBRequestHandler):
""" Handles initial generation of hackers for user selection """
def post(self):
self.get()
def get(self):
self._current_user = self.require_login()
if not self._current_user:
self.authenticate()
return
self._current_user.hackers = Hacker.all().filter("user =", self._current_user.id).fetch(1000)
path = os.path.join(os.path.dirname(__file__), 'create.html')
self.response.out.write(template.render(path, {"user": self._current_user}))
class LoadoutHandler(FBRequestHandler):
def post(self):
self.get()
def get(self):
self._current_user = self.require_login()
if not self._current_user:
self.authenticate()
return
token = initChannel(self._current_user.id)
#Resolve hackers for this user
self._current_user.hackers = Hacker.all().filter("user =", self._current_user.id).fetch(1000)
if len(self._current_user.hackers) == 0:
self.redirect("/create")
path = os.path.join(os.path.dirname(__file__), 'loadout.html')
self.response.out.write(template.render(path, {"user": self._current_user, "token": token}))
class HackathonHandler(FBRequestHandler):
def post(self):
self.get()
def get(self):
self._current_user = self.require_login()
if not self._current_user:
self.authenticate()
return
match = getCurrentMatchByUser(self._current_user.id)
if not match:
self.redirect("/loadout")
return
#Resolve hacker ids to actual hacker data
hacker_list = {}
for hacker in match.hacker_list:
hacker_instance = Hacker.get(hacker)
hacker_list[str(hacker_instance.key())] = {"first_name": hacker_instance.first_name,
"last_name": hacker_instance.last_name,
"talents": hacker_instance.talents,
"imgset": hacker_instance.imageset,
"base": {"energy": hacker_instance.base_energy,
"productivity": hacker_instance.base_productivity,
"teamwork": hacker_instance.base_teamwork}}
#Resolve hackers for this user
self._current_user.hackers = Hacker.all().filter("user =", self._current_user.id).fetch(1000)
#Resolve project
project = Project.get(match.project_id)
#Resolve users
users = [User.get_by_key_name(id) for id in match.users]
#Start appengine channel
token = initChannel(self._current_user.id)
path = os.path.join(os.path.dirname(__file__), 'hackathon.html')
self.response.out.write(template.render(path, {"user": self._current_user,
"users": users,
"hackathon": match,
"hackers": json.dumps(hacker_list),
"project": project,
"token": token}))
# -------------- API calls ----------------
class API_CreateHackerHandler(FBRequestHandler):
def get(self):
self._current_user = self.require_login()
if not self._current_user:
self.response.out.write(json.dumps({"error": "please log in"}))
return
newhacker = Hacker(first_name = self.request.get("first_name"),
last_name = self.request.get("last_name"),
user = self._current_user.id,
catchphrase = self.request.get("catchphrase"),
imageset = self.request.get("image"),
level = 1,
base_energy = int(self.request.get("energy")),
base_productivity = int(self.request.get("productivity")),
base_teamwork = int(self.request.get("teamwork")))
if self.request.get("clss"):
newhacker.talents = [self.request.get("clss")]
newhacker.put()
self.response.out.write(json.dumps({"success": "new hacker created"}))
class API_NodeCompletedHandler(FBRequestHandler):
def get(self, progress):
self._current_user = self.require_login()
if not self._current_user:
self.response.out.write(json.dumps({"error": "please log in"}))
return
match = getCurrentMatchByUser(self._current_user.id)
if not match:
self.response.out.write(json.dumps({"error": "couldn't find current match"}))
return
#Update the match data
userindex = match.users.index(self._current_user.id)
#Add food at the halfway point
if ((match.outcome[userindex] < 50) and (int(progress) >= 50) and int(progress) > match.outcome[userindex]):
in_stock = match.food_stockpile
MAX_STOCK = [3, 4, 2]
match.food_stockpile = [random.randint(in_stock[0], MAX_STOCK[0]),
random.randint(in_stock[1], MAX_STOCK[1]),
random.randint(in_stock[2], MAX_STOCK[2])]
broadcast(match, json.dumps({"food": match.food_stockpile}))
match.outcome[userindex] = int(progress)
match.put()
#Notify all participating users
broadcast(match, json.dumps({"progress": match.outcome}))
self.response.out.write(json.dumps({"success": "node completed"}))
class API_LobbyHandler(FBRequestHandler):
def get(self):
self._current_user = self.require_login()
if not self._current_user:
self.response.out.write(json.dumps({"error": "please log in"}))
return
q = Queue.all().get()
if not q:
q = Queue()
#Push onto queue
if str(self._current_user.id) in q.users:
self.response.out.write(json.dumps({"success": "already in queue"}))
elif len(q.users) == 0:
q.users = [self._current_user.id]
self.response.out.write(json.dumps({"success": "added to queue"}))
else: #Found a match. Pop & Serve
matched = q.users[0]
q.users = q.users[1:]
#Randomly choose a project
projects = Project.all().fetch(1000)
random.seed()
project = random.choice(projects)
#Actually create the match
match = Match(project_id = str(project.key()),
users = [self._current_user.id, matched],
outcome = [0, 0])
hackers = Hacker.all().filter("user IN", match.users).fetch(8)
match.hacker_list = []
for hacker in hackers:
match.hacker_list.append(str(hacker.key()))
match.put()
#Notify the users via socket
broadcast(match, json.dumps({"success": "match found"}))
self.response.out.write("herp")
q.put()
class API_LevelupHandler(FBRequestHandler):
def get(self, hacker_id, skill):
self._current_user = self.require_login()
if not self._current_user:
self.response.out.write(json.dumps({"error": "please log in"}))
return
hacker = Hacker.get_by_id(hacker_id)
if not hacker or hacker.user != self._current_user.id:
self.response.out.write(json.dumps({"error": "could not find hacker or hacker not owned by you"}))
return
hacker.talents.append(skill)
hacker.put()
self.response.out.write(json.dumps({"success": "level up successful"}))
class API_PopulateDatastoreHandler(FBRequestHandler):
def get(self):
#Wipe datastore of all projects
projs = Project.all().fetch(1000)
for proj in projs:
proj.delete()
Project(name="Sendery", graph_json = "asdf", mvp_effect = "lasers").put()
self.response.out.write("done")
class API_EatFoodHandler(FBRequestHandler):
def get(self, food):
self._current_user = self.require_login()
if not self._current_user:
self.response.out.write(json.dumps({"error": "please log in"}))
return
match = getCurrentMatchByUser(self._current_user.id)
if not match:
self.response.out.write(json.dumps({"error": "couldn't find current match"}))
return
foodIndex = ["pizza", "soda", "coffee"].index(food)
if (match.food_stockpile[foodIndex] > 0):
match.food_stockpile[foodIndex] -= 1
match.put()
self.response.out.write(json.dumps({"success": food}))
broadcast(match, json.dumps({"food": match.food_stockpile}))
else:
self.response.out.write(json.dumps({"error": "this food not available"}))
class API_AddFoodHandler(FBRequestHandler):
def get(self):
self._current_user = self.require_login()
if not self._current_user:
self.response.out.write(json.dumps({"error": "please log in"}))
return
match = getCurrentMatchByUser(self._current_user.id)
if not match:
self.response.out.write(json.dumps({"error": "couldn't find current match"}))
return
in_stock = match.food_stockpile
MAX_STOCK = [3, 4, 2]
match.food_stockpile = [random.randint(in_stock[0], MAX_STOCK[0]),
random.randint(in_stock[1], MAX_STOCK[1]),
random.randint(in_stock[2], MAX_STOCK[2])]
match.put()
broadcast(match, json.dumps({"food": match.food_stockpile}))
self.response.out.write(json.dumps({"success": "food added"}))
class ChannelTestHandler(webapp2.RequestHandler):
def get(self):
for chan in Channel.all().fetch(1000):
channel.send_message(chan.key().name(),"hi")
self.response.out.write(str(chan.key().name())+"<br>")
class DBCleanHandler(webapp2.RequestHandler):
def get(self):
for h in Hacker.all().fetch(1000):
h.delete()
for m in Match.all().fetch(1000):
m.delete()
self.response.out.write("Datastore cleared of matches & hackers");
class InviteTestHandler(FBRequestHandler):
def get(self):
self._current_user = self.require_login()
if not self._current_user:
self.response.out.write(json.dumps({"error": "please log in"}))
return
response = sendInvitation(self._current_user, "1374889427")
self.response.out.write(response)
app = webapp2.WSGIApplication([
('/', HomepageHandler),
('/create', CreationHandler),
('/recruit', API_CreateHackerHandler),
('/loadout', LoadoutHandler),
('/hackathon', HackathonHandler),
('/hackathon/node_done/(\d+)', API_NodeCompletedHandler),
('/hackathon/find', API_LobbyHandler),
('/hacker/(\w+)/levelup/(\w+)', API_LevelupHandler),
('/test/populateDatastore', API_PopulateDatastoreHandler),
('/hackathon/eat/(\w+)', API_EatFoodHandler),
('/hackathon/addFood', API_AddFoodHandler),
('/test/channelTest', ChannelTestHandler),
('/test/bork', DBCleanHandler),
('/test/invite', InviteTestHandler)
], debug=True)
def main():
# Set the logging level in the main function
# See the section on Requests and App Caching for information on how
# App Engine reuses your request handlers when you specify a main function
logging.getLogger().setLevel(logging.DEBUG)
webapp.util.run_wsgi_app(application)
if __name__ == '__main__':
main()