def request_to_borrow(lenderID, itemCopyID): emailText = [] emailText.append("You have received the following message from " + current_user().name + ", a Sharing Commons user.\n----\n\n") emailText.append(request.data) emailText.append("\n\n----\nReply to this message to send an email to " + current_user().name + " and set up the exchange. Once you've lent the item, visit beta.sharingcommons.com to confirm lending the item. " + current_user().name + " will receive an email when the item is due") emailBody = ''.join(emailText) # Request item try: borrower = current_user() lender = UserAccount.getuser(int(lenderID)) itemCopy = ItemCopy.get_by_id(int(itemCopyID)) rtb1 = RequestToBorrow() rtb1.useraccount = lender.key rtb1.connection = borrower.key rtb1.item = itemCopy.key rtb1.put() wtb1 = WaitingToBorrow() wtb1.useraccount = borrower.key wtb1.connection = lender.key wtb1.item = itemCopy.key wtb1.put() except: return jsonify({"result":"error"}) # Send email mail.send_mail(sender="Sharing Commons <*****@*****.**>", to=lender.name + " <" + lender.email + ">", reply_to=borrower.name + " <" + borrower.email + ">", subject='Sharing Commons: Request to Borrow "' + Item.query(Item.key == itemCopy.item).get().title + '"', body=emailBody) return jsonify({"result":"success"})
def searchbooks(): booklist = {} searchterm = request.args.get('value') attr = request.args.get('refineSearch') if attr == "all": attr = None if searchterm is None: searchterm = "" else: searchterm = searchterm.lstrip() if searchterm is None or searchterm == "": pass else: cur_user = current_user() logging.info(cur_user) if not cur_user.is_authenticated(): #Assume no books in library or network, return results only booklist = Book.search_books_by_attribute(searchterm,attr) for book in booklist: booklist[book] = booklist[book].to_dict() #Assume not in booklist or networkbooklist booklist[book]["inLibrary"] = "False" booklist[book]["inNetwork"] = "False" else: user = current_user() #Create a dictionary of the user's books mybooklist = {} for copy in user.get_library(): mybooklist[copy.OLKey] = copy #Create a dictionary of the books in my network networkbooklist = {} string = "" for connection in user.get_connections(): u = UserAccount.getuser(connection.id()) for copy in u.get_library(): networkbooklist[copy.OLKey] = copy booklist = Book.search_books_by_attribute(searchterm,attr) for book in booklist: booklist[book] = booklist[book].to_dict() booklist[book]["escapedtitle"] = re.escape(booklist[book]["title"]) if booklist[book]['OLKey'] in mybooklist: booklist[book]["inLibrary"] = "True" else: booklist[book]["inLibrary"] = "False" if booklist[book]['OLKey'] in networkbooklist: booklist[book]["inNetwork"] = "True" else: booklist[book]["inNetwork"] = "False" return render_response('searchbooks.html', books=booklist, search=searchterm, attribute=attr)
def movie_info(RTKey): itemMovie = Item.get_by_key("movie",RTKey) movie = itemMovie.to_dict() # Check if user owns book and pass itemCopy object if current_user().is_authenticated(): itemCopy = ItemCopy.query(ItemCopy.item==itemMovie.key,ItemCopy.owner==current_user().key).fetch() if itemCopy: movieCopy = itemCopy[0] else: movieCopy = None else: movieCopy = None return render_response('itemdetail.html', item=movie, itemCopy=movieCopy)
def settings(): cur_user = current_user() # Get message template msgTemplate = MessageTemplate.query(MessageTemplate.restaurant_key==cur_user.key,MessageTemplate.message_type==1,MessageTemplate.is_active==True).get() if not msgTemplate: # No template exists, create one msgTemplate = MessageTemplate(restaurant_key=cur_user.key,message_type=1,is_active=True,message_text="{firstName}, your table is almost ready. Need more time? Reply ""bump"" and the # of minutes you'd like.") msgTemplate.put() if cur_user.is_demo: # Don't let demo into settings return redirect(url_for("index")) else: if request.method == 'POST' and "defaultMessage" in request.form and "promoDefault" in request.form: defaultMessage = request.form["defaultMessage"] if request.form["promoDefault"].lower() == "true": promoDefault = True elif request.form["promoDefault"].lower() == "false": promoDefault = False if request.form["gvPW"]: gv_email = request.form["gvEmail"] gv_password = request.form["gvPW"] else: gv_email = None gv_password = None reply_to_email = request.form["replyEmail"] # Udpate Message Template if msgTemplate.update(defaultMessage) and cur_user.update(promoDefault, gv_email, gv_password, reply_to_email): return "Success" else: return False return render_response('settings.html',default_message=msgTemplate.message_text)
def new_promo(): cur_user = current_user() templateName = request.form["templateName"] templateText = request.form["templateText"] msgTemplate = MessageTemplate(restaurant_key=cur_user.key,message_type=2,is_active=True,message_name=templateName,message_text=templateText) msgTemplate.put() return "Success"
def optin(user_ID=None): signup_method = request.args.get('signup_method') include_email = request.args.get('include_email') iframe = request.args.get('iframe') if not include_email: include_email = False elif include_email.lower() == "true": include_email = True else: include_email = False if not iframe: iframe = False elif iframe.lower() == "true": iframe = True else: iframe = False if not signup_method: signup_method = 3 # Default to website cur_user = current_user() if user_ID: # Regardless of who is logged in, send to page for provided user ID restaurant = UserAccount.get_by_id(int(user_ID)) else: # No one is logged in, send to provided user or if none redirect to home if cur_user.is_authenticated(): restaurant = cur_user else: return redirect(url_for("index")) return render_response("optin.html",restaurant=restaurant,signup_method=signup_method,include_email=include_email,iframe=iframe)
def manage(): tour = request.args.get('tour') cur_user = current_user() guestlist = [] if cur_user: # Get message template msgTemplate = MessageTemplate.query(MessageTemplate.restaurant_key==cur_user.key,MessageTemplate.message_type==1,MessageTemplate.is_active==True).get() if not msgTemplate: # No template exists, create one msgTemplate = MessageTemplate(restaurant_key=cur_user.key,message_type=1,is_active=True,message_text="{firstName}, your table is almost ready. Need more time? Reply ""bump"" and the # of minutes you'd like.") msgTemplate.put() # Create a list of guests (as dicts) within the user's library for checkin in cur_user.get_checkedin_guests(): guest = Guest.get_by_id(checkin.guest_key.id()) checkedinGuest = {} checkedinGuest["guest_ID"] = checkin.guest_key.id() checkedinGuest["checkin_ID"] = checkin.key.id() checkedinGuest["firstName"] = guest.first_name checkedinGuest["lastName"] = guest.last_name if guest.sms_number: checkedinGuest["sms"] = functions.stylizePhoneNumber(guest.sms_number) checkedinGuest["email"] = guest.email checkedinGuest["partySize"] = checkin.party_size arrival_time = checkin.signin_time - timedelta(hours=6) checkedinGuest["arrival_time"] = arrival_time checkedinGuest["wait_estimate"] = checkin.wait_estimate checkedinGuest["target_time"] = arrival_time + timedelta(minutes=checkin.wait_estimate) guestlist.append(checkedinGuest) # Sort guestlist by arrival time (oldest on top) guestlist.sort(key=lambda guest: guest["arrival_time"]) return render_response("manage.html", guestlist=guestlist, cur_user=cur_user, tour=tour, default_message=msgTemplate.message_text)
def guest_signin(): cur_user = current_user() tour = request.args.get('tour') if cur_user: if request.method == 'POST': firstName = request.form["firstName"] try: lastName = request.form["lastName"] except: lastName = None preferredContact = request.form["preferredContact"] if preferredContact == 'sms': smsNumber = functions.digitizePhoneNumber(request.form["smsNumber"]) email = None elif preferredContact == 'email': email = request.form["email"] smsNumber = None try: if request.form["optIn"] == 'on': optIn = True else: optIn = False except: optIn = False # Add guest to database guest = Guest.add_guest(firstName=firstName,lastName=lastName,preferredContact=preferredContact,smsNumber=smsNumber,email=email,optIn=optIn,signup_method=1,user=cur_user) if not guest: return "Error" checkin = CheckIn.check_in_guest(guest) if not checkin: return "Error" if tour == "continue": return redirect(url_for("manage") + '?tour=continue') return "Success" return render_response("guest-signin.html", tour=tour)
def index(): # Each user has an invitation link (in /network) which they send to other users to # invite them to connect on BookOut. Currently, this is the only method of connecting # users. The link adds an argument to the index link (?connect=) with the inviter's # user ID. A modal appears in the view if otherUserID is not 0. # Grab User ID from connection invitation otherUserID = request.args.get('connect') # If no connect argument is present (just a regular visit to the dashboard), set to 0 (ignored in view) if otherUserID is None: connectionType = 0 #No connection request is being made otherUserID = 0 otherUserName = 0 else: # Get User Name from User ID otherUserObj = UserAccount.get_by_id(int(otherUserID)) # Set invalid objects to invalid if otherUserObj is None: otherUserID = 0 otherUserName = 0 connectionType = 1 #Invalid User ID else: otherUserName = otherUserObj.name connectionType = 2 #Valid User # Don't let a user connect with him/herself, set to 0 so they get nothing if int(otherUserID) == current_user().get_id(): connectionType = 3 #Own self # Don't let a user connect with an existing connection # if int(otherUserID) matches something in current_user().connected_accounts # connectionType = 4 #Existing Connection return render_response('home.html',connectUserID=otherUserID,connectUserName=otherUserName,connectType=connectionType)
def simple_add_connection(otherUserID): cur_user = current_user() otherUser = UserAccount.getuser(int(otherUserID)) if cur_user.add_connection(otherUser): return jsonify({"Message":"Connection successfully created"}) else: return jsonify({"Message":"Connection already existed"})
def manual_checkout(itemCopyID): if request.method == 'POST': itemCopy = ItemCopy.get_by_id(int(itemCopyID)) # Manually checkout itemCopy.borrower = current_user().key itemCopy.lender = current_user().key itemCopy.manual_borrower_name = request.form["borrowerName"] if "borrowerEmail" in request.form: itemCopy.manual_borrower_email = request.form["borrowerEmail"] itemCopy.due_date = datetime.strptime(request.form["dueDate"], "%m/%d/%Y") itemCopy.put() return jsonify({"result":"success"}) else: return jsonify({"result":"error"})
def refresh_manage(): cur_user = current_user() waitlist = [] if cur_user: # Create a list of guests (as dicts) within the user's library for checkin in cur_user.get_checkedin_guests(): guest = Guest.get_by_id(checkin.guest_key.id()) checkedinGuest = {} checkedinGuest["guest_ID"] = checkin.guest_key.id() checkedinGuest["checkin_ID"] = checkin.key.id() checkedinGuest["firstName"] = guest.first_name checkedinGuest["lastName"] = guest.last_name if guest.sms_number: checkedinGuest["sms"] = functions.stylizePhoneNumber(guest.sms_number) checkedinGuest["email"] = guest.email checkedinGuest["partySize"] = checkin.party_size arrival_time = checkin.signin_time - timedelta(hours=6) checkedinGuest["arrival_time"] = arrival_time.strftime('%I:%M %p') checkedinGuest["wait_estimate"] = checkin.wait_estimate target_time = arrival_time + timedelta(minutes=checkin.wait_estimate) checkedinGuest["target_time"] = target_time.strftime('%I:%M %p') waitlist.append(checkedinGuest) # Sort guestlist by arrival time (oldest on top) waitlist.sort(key=lambda guest: guest["arrival_time"]) jsondump = json.dumps(waitlist) return jsondump return "User Not Logged In"
def delete_user(): cur_user = current_user() if not cur_user: logging.info("there is not a user logged in") #return "<a href='%s' >Login</a>" %users.create_login_url(dest_url=url_for('library_requests',ISBN=ISBN)) if delete_account(cur_user): return "Success" return ""
def update_current_wait(): cur_user = current_user() if not cur_user: logging.info("there is not a user logged in") return "Error" else: cur_user.default_wait = int(request.form["current-wait"]) cur_user.put() return "Success"
def send_invitation_request(): if current_user().is_authenticated(): if request.method == 'POST': import json jsonString = request.data jsonData = json.loads(jsonString) # Check email address if not mail.is_email_valid(jsonData["emailTo"]): return jsonify({"result":"invalidemail"}) # Send email mail.send_mail(sender="Sharing Commons <*****@*****.**>", to=jsonData["emailTo"], reply_to=current_user().name + " <" + current_user().email + ">", subject=jsonData["emailSubject"], body=jsonData["emailBody"] + "\n\nJoin Sharing Commons and Connect with " + current_user().name + ": " + request.host_url + "?connect=" + str(current_user().get_id()), html=jsonData["emailBody"] + "<br><br>Join Sharing Commons and Connect with " + current_user().name + ":<br><br><a href='" + request.host_url + "?connect=" + str(current_user().get_id()) + "' style='display: block; background: #4E9CAF; padding: 5px; width: 180px; text-align: center; border-radius: 5px; color: white; font-weight: bold;'>Join Sharing Commons</button>") return jsonify({"result":"success"})
def book_info(OLKey): # Pass book object to template itemBook = Item.get_by_key("book",OLKey) book = itemBook.to_dict() # Determine if the user owns this book # Find all connections who own this book and get the status for each # Find out any pending actions regarding this book # Find any current loans or borrow of this book # Check if user owns book and pass itemCopy object if current_user().is_authenticated(): itemCopy = ItemCopy.query(ItemCopy.item==itemBook.key,ItemCopy.owner==current_user().key).fetch() if itemCopy: bookCopy = itemCopy[0] else: bookCopy = None else: bookCopy = None return render_response('itemdetail.html',item=book,itemCopy=bookCopy)
def discover(): # Start by creating a list of items (as dicts) within the user's library # This is necessary prep to be able to show that the item is in the user's library librarylist = {} useraccount = current_user() for copy in useraccount.get_library(): item = Item.query(Item.key == copy.item).get().to_dict() item["item_subtype"] = copy.item_subtype item["escapedtitle"] = re.escape(item["title"]) librarylist[(item["item_key"],item["item_subtype"])] = item # Create a list of all items (as dicts) in the user's network user = current_user() itemlist = [] for connection in user.get_connections(): u = UserAccount.getuser(connection.id()) for copy in u.get_library(): item = Item.query(Item.key == copy.item).get().to_dict() item["item_subtype"] = copy.item_subtype item["escapedtitle"] = re.escape(item["title"]) if copy.borrower is None: item["available"] = True else: item["available"] = False # Check to see if book is in the user's library item["inLibrary"] = [] for item_subtype in ['book', 'ebook', 'audiobook']: if (item["item_key"],item_subtype) in librarylist: item["inLibrary"].append(item_subtype) itemlist.append(item) # Sort itemlist alphabetically, with title as the primary sort key, # author as secondary, and item_subtype as tertiary itemlist.sort(key=lambda item: item["item_subtype"]) itemlist.sort(key=lambda item: item["title"].lower()) #Remove duplicate books (dictionaries) from itemlist (list) dedupeditemlist = [] for item in itemlist: if item not in dedupeditemlist: dedupeditemlist.append(item) return render_response('discover.html',itemlist=dedupeditemlist)
def update_party_size(checkin_ID): cur_user = current_user() if not cur_user: logging.info("there is not a user logged in") return "Error" else: checkin = CheckIn.get_by_id(int(checkin_ID)) checkin.party_size = int(request.form["party-size"]) checkin.put() return "Success"
def undo_checkin_guest(checkin_ID): cur_user = current_user() if not cur_user: logging.info("there is not a user logged in") return "Error" else: # Place CheckIn back in queue checkin = CheckIn.get_by_id(int(checkin_ID)) checkin.in_queue = True checkin.put() return "Success"
def update_wait_estimate(checkin_ID): cur_user = current_user() if not cur_user: logging.info("there is not a user logged in") return "Error" else: checkin = CheckIn.get_by_id(int(checkin_ID)) checkin.wait_estimate = int(request.form["wait-estimate"]) target_seating_time = checkin.signin_time - timedelta(hours=6) + timedelta(minutes=checkin.wait_estimate) checkin.put() return jsonify({"target": target_seating_time.strftime('%I:%M %p')})
def settings(): if request.method == 'POST' and "displayName" in request.form and "lendingLength" in request.form and "notifications" in request.form and "additionalInfo" in request.form: user = current_user() name = request.form["displayName"] length = request.form["lendingLength"] notify = request.form["notifications"] info = request.form["additionalInfo"] if user.update(name, length, notify, info): return "Success" else: return False return render_response('settings.html')
def get_my_book_list(): cur_user = current_user() if not cur_user: logging.info("there is not a user logged in") return "<a href='%s' >Login</a>" %users.create_login_url(dest_url=url_for('manage_library')) books = {} counter = 0 for copy in cur_user.get_library(): book = Book.query(Book.key == copy.book).get() books[counter] = book.to_dict() counter += 1 return jsonify(JsonIterable.dict_of_dict(books))
def get_notifications(): cur_user = current_user() notifications = [] for notification in cur_user.pending_actions: info = dict() info["ID"] = notification.key.id() info["text"] = notification.text info["confirm_text"] = notification.accept_text info["confirm_activated"] = notification.can_accept info["reject_text"] = notification.reject_text info["reject_activated"] = notification.can_reject notifications.append(info) return jsonify({"notifications": notifications})
def get_my_item_list(): cur_user = current_user() if not cur_user: logging.info("there is not a user logged in") return "<a href='%s' >Login</a>" %users.create_login_url(dest_url=url_for('manage_library')) items = {} counter = 0 for copy in cur_user.get_library(): item = Item.query(Item.key == copy.item).get() items[counter] = item.to_dict() counter += 1 return jsonify(JsonIterable.dict_of_dict(items))
def advertise(): demo = request.args.get('demo') if not demo: demo = False elif demo.lower() == "true": demo = True else: demo = False cur_user = current_user() # Create a list of guests (as dicts) within the user's library optInList = [] for guest in cur_user.get_optins(): if guest.sms_number or guest.email: optin = {} optin["guest_ID"] = guest.key.id() if guest.first_name and guest.last_name: optin["name"] = guest.first_name + ' ' + guest.last_name elif guest.first_name: optin["name"] = guest.first_name if guest.preferred_contact == 'sms': optin["smsNumber"] = functions.stylizePhoneNumber(guest.sms_number) elif guest.preferred_contact == 'email': optin["email"] = guest.email if guest.subscribe_date: optin["subscribe_date"] = guest.subscribe_date.strftime('%m/%d/%y') else: optin["subscribe_date"] = "Unknown" if guest.signup_method: if guest.signup_method == 1: optin["signup_method"] = 'Waitlist' elif guest.signup_method == 2: optin["signup_method"] = 'SMS' elif guest.signup_method == 3: optin["signup_method"] = "Website" else: optin["signup_method"] = 'Waitlist' optin["promos_sent"] = Message.query(Message.restaurant_key==cur_user.key,Message.recipient_key==guest.key).count() # TODO: Don't count table notifications (it's going to be nasty to fix that!) optInList.append(optin) optInList.sort(key=lambda optin: optin["subscribe_date"]) # Create list of MessageTemplates msgTemplates = [] for msgTemplate in MessageTemplate.query(MessageTemplate.restaurant_key==cur_user.key,MessageTemplate.message_type==2,MessageTemplate.is_active==True).fetch(): if msgTemplate.message_name: # If it doesn't have a name, we can't show it msg = {} msg["msgID"] = msgTemplate.key.id() msg["msgName"] = msgTemplate.message_name msg["msgText"] = msgTemplate.message_text msgTemplates.append(msg) msgTemplates.sort(key=lambda msg: msg["msgName"]) return render_response("advertise.html", optInList=optInList, msgTemplates=msgTemplates, demo=demo)
def discover(): user = current_user() booklist = [] string = "" for connection in user.get_connections(): u = UserAccount.getuser(connection.id()) for copy in u.get_library(): book = Book.query(Book.key == copy.book).get() booklist.append(book) #Sort booklist alphabetically, with title as the primary sort key and author as secondary booklist.sort(key=lambda book: book.author.lower()) booklist.sort(key=lambda book: book.title.lower()) return render_response('discover.html',books=booklist)
def whitelist(): cur_user = current_user() if cur_user: if cur_user.is_admin: if request.method == 'POST': domain = request.form["domain"].lower() whitelistDomain = Whitelist.query(Whitelist.domain==domain).get() if not whitelistDomain: whitelistDomain = Whitelist(domain=domain) whitelistDomain.put() return render_response("whitelist.html") else: logging.info("User is not admin, cannot access whitelist") return redirect(url_for("index"))
def get_borrowed_books(): cur_user = current_user() borrowedBooks = [] for bookcopy in cur_user.get_borrowed_books(): book = Book.get_by_id(bookcopy.book.id()) owner = UserAccount.get_by_id(bookcopy.owner.id()) bookInfo = dict() bookInfo["title"] = book.title bookInfo["author"] = book.author bookInfo["copyID"] = bookcopy.key.id() bookInfo["ownerId"] = bookcopy.owner.id() bookInfo["owner"] = owner.name bookInfo["due_date"] = str(bookcopy.due_date) borrowedBooks.append(bookInfo) return jsonify({"borrowedBooks":borrowedBooks})
def manage_connections(otherUserID = None): cur_user = current_user() if request.method == 'GET': connections = cur_user.get_all_connections() users = [] result = "you have " + str(len(connections)) + " connections" for connection in connections: result += "<br>" + connection.name user = dict() user["name"] = connection.name user["email"] = connection.email #user["username"] = connection.username user["id"] = connection.get_id() users.append(user) return jsonify({"connectedUsers":users}) elif request.method == 'POST': cur_user = current_user() otherUser = UserAccount.getuser(int(otherUserID)) result = cur_user.send_invite(otherUser) if(result == 0): return jsonify({"Message":"Invitation successfully sent"}) elif(result == 1): return jsonify({"Message":"Connection already existed"}) elif(result == 2): return jsonify({"Message":"Cannot create a connection with yourself"}) elif request.method == 'DELETE': cur_user = current_user() otherUser = UserAccount.getuser(int(otherUserID)) if cur_user.remove_connection(otherUser): return jsonify({"Message":"Connection successfully deleted"}) else: return jsonify({"Message":"Connection didn't existed"}) else: #this should never be reached return jsonify({"Message":"Error: http request was invalid"})
def checkin_guest(checkin_ID): cur_user = current_user() if not cur_user: logging.info("there is not a user logged in") return "Error" else: checkin = CheckIn.get_by_id(int(checkin_ID)) # Find checkin object and check in checkin.in_queue = False checkin.seat_time = datetime.datetime.now() wait_time_timedelta = checkin.seat_time - checkin.signin_time calculated_wait_time = float(wait_time_timedelta.seconds) / float(60) checkin.wait_time = calculated_wait_time checkin.put() return "Success"