Permalink
Switch branches/tags
Nothing to show
Find file
Fetching contributors…
Cannot retrieve contributors at this time
296 lines (277 sloc) 9.05 KB
import re
import datetime
import logging
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
import demjson
from models import *
class Json(webapp.RequestHandler):
def __init__(self):
self.account = users.get_current_user()
self.user = User.all().filter('who =', self.account).get()
pass
def error(self, message):
self.response.out.write('{"error": "%s"}' % message)
def warning(self, message):
self.response.out.write('{"warning": "%s"}' % message)
def info(self, message):
self.response.out.write('{"info": "%s"}' % message)
def json(self, obj):
self.response.out.write('{"info": %s}' % demjson.encode(obj))
def users_only(self):
if not self.user:
self.error('You are not logged in')
return True
return False
@staticmethod
def simplify(model):
simple_model = {}
simple_model['key'] = str(model.key())
for prop in model.__class__.properties().keys():
value = model.__getattribute__(prop)
# TODO(calebegg): Expand values if they are model keys.
simple_model[prop] = str(value)
return simple_model
class AddToBox(Json):
def post(self):
if self.users_only():
return
recipe_key = Recipe.get(self.request.get('id')).key()
if recipe_key in self.user.box.contents:
self.warning('This recipe is already in your box.')
else:
self.user.box.contents.append(recipe_key)
self.user.box.put()
self.info('Success')
class RemoveFromBox(Json):
def post(self):
if self.users_only():
return
recipe = Recipe.get(self.request.get('id'))
if not recipe.key() in self.user.box.contents:
self.warning('This recipe is not in your box.')
else:
self.user.box.contents.remove(recipe.key())
if recipe.key() in self.user.starred:
self.user.starred.remove(recipe.key())
recipe.stars -= 1
recipe.put()
self.user.put()
self.info('Success')
class AddStar(Json):
def post(self):
recipe = Recipe.get(self.request.get('id'))
if self.users_only():
return
if recipe.key() in self.user.starred:
self.warning('This recipe is already starred.')
else:
self.user.starred.append(recipe.key())
self.user.put()
recipe.stars += 1
recipe.put()
self.info('Success')
class RemoveStar(Json):
def post(self):
if self.users_only():
return
recipe = Recipe.get(self.request.get('id'))
if not recipe.key() in self.user.starred:
self.warning('This recipe has not been starred.')
else:
self.user.starred.remove(recipe.key())
self.user.put()
recipe.stars -= 1
recipe.put()
self.info('Success')
class UserSearch(Json):
def get(self):
if self.users_only():
return
query = self.request.get('query')
results = User.all().filter('who =', users.User(query)).fetch(10)
result_list = []
for result in results:
result_list.append({'name': '%s %s' % (result.first_name,
result.last_name),
'email': str(result.who),
'key': str(result.key()),
'is_current_user': result.who == self.account,
'is_already_friend': result.who in self.user.friends
})
self.json({'query': query, 'results': result_list})
class RequestFriend(Json):
def post(self):
if self.users_only():
return
receiver = db.get(self.request.get('id'))
notification = Notification()
notification.receiver = receiver.who
notification.sender = self.account
notification.type = 'friend_request'
notification.sender_name = '%s %s' % (self.user.first_name,
self.user.last_name)
notification.put()
self.info('Success')
class NotificationAction(Json):
def post(self):
if self.users_only():
return
notification = db.get(self.request.get('id'))
if self.request.get('action') == 'close':
notification.delete()
self.info('Success')
elif self.request.get('action') == 'accept_friend_request':
if notification.type != 'friend_request':
self.warning('This action is not allowed for this notification type.')
else:
if not notification.sender in self.user.friends:
self.user.friends.append(notification.sender)
self.user.put()
friend = User.all().filter('who =', notification.sender).get()
friend.friends.append(self.account)
friend.put()
response = Notification()
response.sender = self.account
response.receiver = notification.sender
response.sender_name = ('%s %s' %
(self.user.first_name, self.user.last_name))
response.type = 'friend_request_accept'
response.put()
notification.delete()
self.info('Success')
else:
self.warning('Unrecognized notification type.')
class Menus(Json):
def get(self):
if self.users_only():
return
start = datetime.date(* map(int, self.request.get('start').split('-')))
end = datetime.date(* map(int, self.request.get('end').split('-')))
results = Menu.all().filter("owner =", self.account).filter('when >=', start).filter('when <=', end).order('when').order('meal')
simple_results = []
for menu in results:
simple_menu = {
'when': str(menu.when),
'meal': menu.meal,
'what': [],
}
for key in menu.what:
recipe = Recipe.get(key)
simple_menu['what'].append({
'key': str(key),
'name': recipe.name,
})
simple_results.append(simple_menu)
self.json({'results': simple_results})
class AddToCalendar(Json):
def post(self):
if self.users_only():
return
menuDate = datetime.date(* map(int, self.request.get('when').split('-')))
recipeKey = Recipe.get(self.request.get('id')).key()
menus = Menu.all().filter('owner =', self.account).filter('when =', menuDate).filter('meal =', int(self.request.get('meal')))
if menus.count() == 0:
newMenu = Menu(when=menuDate)
newMenu.meal = int(self.request.get('meal'))
newMenu.what.append(recipeKey)
newMenu.put()
self.info("success")
else:
for menu in menus:
if recipeKey in menu.what:
self.warning("You've already added this recipe.");
else:
menu.what.append(recipeKey)
menu.put()
self.info("success")
class RemoveFromCalendar(Json):
def post(self):
if self.users_only():
return
menuDate = datetime.date(* map(int, self.request.get('when').split('-')))
recipeKey = Recipe.get(self.request.get('id')).key()
menus = Menu.all().filter('owner =', self.account).filter('when =', menuDate).filter('meal =', int(self.request.get('meal')))
if menus.count() == 0:
self.warning("There's no menu.")
else:
for menu in menus:
if recipeKey in menu.what:
logging.info("Test")
menu.what.remove(recipeKey)
menu.put()
if len(menu.what) == 0:
menu.delete()
self.info("success")
else:
self.warning("Recipe is not in this menu.")
class ParseIngredient(Json):
def get(self):
def is_numeric(token):
return re.match(r'^\d+$|^\d+[./]\d+$', token)
def parse_num(token):
ret = 0
try:
ret = float(token)
except ValueError:
num, denom = token.split('/')
ret = float(num) / float(denom)
return ret
query = self.request.get('query')
tokens = query.split(' ')
tokens = filter(lambda s: s != '', tokens)
tokens.reverse()
# Number
number = 0
token = tokens.pop()
if is_numeric(token):
number += parse_num(token)
token = tokens.pop()
if token == 'and':
token = tokens.pop()
if is_numeric(token):
number += parse_num(token)
# Unit
token = tokens.pop()
unit = token
if token in UNITS.keys():
pass
else:
pass
token = tokens.pop()
if token == 'of':
token = tokens.pop()
# Item
item = ''
while True:
if token[-1] == ',':
item += token[:-1] + ' '
break
item += token + ' '
if token == []:
break
token = tokens.pop()
item = item and item[:-1]
# Instructions
instructions = ' '.join(tokens)
self.json({'number': number, 'unit': unit, 'item': item, 'instructions':
instructions})
application = webapp.WSGIApplication([
('/add_to_box.json', AddToBox),
('/remove_from_box.json', RemoveFromBox),
('/add_star.json', AddStar),
('/remove_star.json', RemoveStar),
('/notification_action.json', NotificationAction),
('/request_friend.json', RequestFriend),
('/usersearch.json', UserSearch),
('/menus.json', Menus),
('/parse_ingredient.json', ParseIngredient),
('/add_to_calendar.json', AddToCalendar),
('/remove_from_calendar.json', RemoveFromCalendar),
], debug=True)
def main():
run_wsgi_app(application)
if __name__ == '__main__':
main()