def deck(slug=None): """ Returns information about a deck as a JSON object. """ try: deck = Deck.objects.get(slug=slug) except DoesNotExist: return simplejson.dumps({}) cards = [] for card in deck.cards: front_img = False if card['front_img'].grid_id is not None: front_img = 'img/front_img/{cid}/{grid_id}'.format( cid=card.id, grid_id=card['front_img'].grid_id) card_state = CardStates.review if current_user.is_authenticated(): user_card_data, created = UserCardData.objects.get_or_create( user=current_user.to_dbref(), card=card) if user_card_data: card_state = user_card_data.card_state # TODO: Need to calculate whether the card is due cards.append( dict( front_img=front_img, front_text=card['front_text'], id=str(card.id), card_state=card_state, due=True, )) can_write = False deck_state = DeckStates.review if current_user.is_authenticated(): admin_role = user_datastore.find_role("admin") if admin_role in current_user.roles: # admins can write to all decks can_write = True user_deck_data, created = UserDeckData.objects.get_or_create( user=current_user.to_dbref(), deck=deck) if user_deck_data: deck_state = user_deck_data.deck_state data = dict( id=str(deck.id), mnemonic=deck.mnemonic, mnemonic_positions=deck.mnemonic_positions, can_write=can_write, turn_time=deck.turn_time, title=deck.title, cards=cards, deck_state=deck_state, ) return simplejson.dumps(data)
def add_patient(): """ Allows a physician to enter in patient information and for an invitational email to be sent to the patient. The PatientInvite is then stored so as to not spam the patient and for logging purposes. """ form = AddPatientForm(request.form) if request.method == "POST": try: # First, ensure this physician is not already monitoring this patient if current_user.patients.objects(email=form.email.data).count() > 0: flash("Error: You are already monitoring this patient. Please specify a new patient.", "warning") return render_template("add-patient.html", form=form) except AttributeError: pass # Patients table is empty, so no need to check if form.validate(): # Don't allow physician to send duplicate invite requests to a new patient if PatientInvite.objects(email=form.email.data, inviting_physician=current_user.to_dbref()).count() > 0: flash("Warning: You have already invited this patient to join.", "warning") return redirect("/dashboard") full_name = "{} {}".format(form.first_name.data, form.last_name.data) # Generate a PatientInvite object and send an invite email to given patient invite = PatientInvite( inviting_physician=current_user.to_dbref(), accepted=False, email=form.email.data, first_name=form.first_name.data, last_name=form.last_name.data, ) invite.save() email_sent = email_patient_invite( email=form.email.data, name=full_name, invite_id=str(invite.id), physician_name=current_user.full_name ) if email_sent: success_msg = ( "{name} has been emailed an invitation, and will appear" " on your Dashboard after granting access.".format(name=full_name) ) flash(success_msg, "success") else: flash( "We were unable to send the patient invitation. Please ensure the address provided is correct.", "warning", ) return redirect("/dashboard") else: flash("Invalid input: please see the suggestions below.", "warning") return render_template("add-patient.html", form=form)
def createPin(title, img, dscrp): """Creates pin - title : the pin title - img : the image path - dscrp : the image description """ if allowed_file(img): orig = True try: pinQuery = Pin.objects.get(img_path=img_path) if pinQuery is not None: orig = False except Pin.DoesNotExist: pass pin = Pin( title=title, img=img, pinner=current_user.to_dbref(), dscrp=dscrp, orig=orig, date=datetime.now(), repins=0, like_count=0, ) pin.save() if pin.repins == None: fix_repins()
def teach_class(id): if current_user.is_anonymous(): flash( Markup('<span class="glyphicon glyphicon-info-sign"></span> You have to login before becoming a teacher.'), "info", ) return redirect("/login?next=/proposals/" + id) p = Proposal.objects.get_or_404(id=id) for teacher in p.teachers: if teacher.id == current_user.id: flash( Markup( '<span class="glyphicon glyphicon-info-sign"></span> You have already volunteered to become a teacher for this proposal.' ), "info", ) return detail(id) p.teachers.append(current_user.to_dbref()) p.save() flash( Markup( '<span class="glyphicon glyphicon-ok"></span> Thank you for volunteering to become a teacher for this proposal. We will contact you if there is enough interest generated for this proposal.' ), "success", ) return detail(id)
def featured_decks(): """ Returns list of featured decks """ try: decks = Deck.objects.filter(featured=True) except DoesNotExist: return simplejson.dumps({}) featured_decks = [] for deck in decks: deck_state = DeckStates.review if current_user.is_authenticated(): user_deck_data, created = UserDeckData.objects.get_or_create( user=current_user.to_dbref(), deck=deck) if user_deck_data: deck_state = user_deck_data.deck_state featured_decks.append( dict( id=str(deck.id), title=deck['title'], slug=deck['slug'], deck_state=deck_state, )) return simplejson.dumps(featured_decks)
def is_liked(self): lpins = Pin.objects(likes__contains=current_user.to_dbref()) for lpin in lpins: if lpin == self: return True else: return False
def upload(): form = UploadForm() if form.validate(): if form.title.data == "": flash("Must include title") return redirect(request.referrer + "#add_form") filename = secure_filename(form.photo.data.filename) pos = filename.rfind('.') if pos < 0 or (pos >= 0 and (not filename[pos + 1 : ] in ALLOWED_EXTENSIONS)): flash("Error: Invalid extension, pleases use jpg or png") return redirect(request.referrer + '#add_form') while os.path.isfile(os.path.join(current_app.config['UPLOAD_FOLDER'], filename)): filename = '_' + filename form.photo.file.save(os.path.join(current_app.config['UPLOAD_FOLDER'], filename)) pin = Pin(title=form.title.data, img=filename, dscrp=form.dscrp.data, orig=True, date=datetime.now(), pinner=current_user.to_dbref(), repins=0, like_count=0) pin.save() flash("Image has been uploaded.") else: flash("Image upload error.") return redirect('viewprofile/%s/pins' % str(current_user.uname) + "#add_form")
def teach_class(id): if current_user.is_anonymous(): flash( Markup( "<span class=\"glyphicon glyphicon-info-sign\"></span> You have to login before becoming a teacher." ), "info") return redirect('/login?next=/proposals/' + id) p = Proposal.objects.get_or_404(id=id) for teacher in p.teachers: if teacher.id == current_user.id: flash( Markup( "<span class=\"glyphicon glyphicon-info-sign\"></span> You have already volunteered to become a teacher for this proposal." ), "info") return detail(id) p.teachers.append(current_user.to_dbref()) p.save() flash( Markup( "<span class=\"glyphicon glyphicon-ok\"></span> Thank you for volunteering to become a teacher for this proposal. We will contact you if there is enough interest generated for this proposal." ), "success") return detail(id)
def add_comment(): if request.form.get("val") != "": pin = Pin.objects.get(id=request.form.get("id")) comment = Comment(commenter=current_user.to_dbref(), message=request.form.get("val"), date=datetime.now()) pin.cmts = pin.cmts + [comment] pin.save() flash("Comment added") return redirect(request.referrer)
def like(): id = request.form.get('id') pin = Pin.objects.get(id=id) if pin.is_liked() == True: pin.update(pull__likes=current_user.to_dbref()) pin.like_count = pin.like_count - 1 pin.save() flash("pin unliked") return redirect(request.referrer) else: if pin.like_count == None: fix_likes() pin = Pin.objects.get(id=id) pin.likes.append(current_user.to_dbref()) pin.like_count = pin.like_count + 1 pin.save() flash("pin liked") return redirect("/viewprofile/%s/likes" % str(current_user.uname))
def _new_project(): form = NewProjectForm() if form.validate_on_submit(): name = form.name.data description = form.description.data print "project count", Project.objects(name=name).count() if Project.objects(name=name).count() == 0: project = Project(name=name, description=description) project.save() project.add_user(current_user.to_dbref()) current_user.add_project(project) return redirect(url_for("project._project", project_id=project.id)) else: flash("Project name already exists") return render_template('new_project.html', form=form)
def _new_project(): form = NewProjectForm() if form.validate_on_submit(): name = form.name.data description = form.description.data print "project count", Project.objects(name = name).count() if Project.objects(name = name).count() ==0: project = Project(name=name, description=description) project.save() project.add_user(current_user.to_dbref()) current_user.add_project(project) return redirect(url_for("project._project", project_id = project.id)) else: flash("Project name already exists") return render_template('new_project.html', form=form)
def user_notifications(): """ User-level notifications page """ from backend.backend.models.notification import Notification user = current_user.to_dbref() notifications = { 'new': Notification.objects(user_for=user, read=False, complete=False).order_by('-created'), 'read': Notification.objects(user_for=user, read=True, complete=False).order_by('-created'), 'completed': Notification.objects(user_for=user, complete=True).order_by('-created') } return render_template('notifications.html', notifications=notifications)
def decorated_view(*args, **kwargs): date = datetime.now() msg = "%s: " % (current_user.uname) # Function does not have a _ if fn.__name__.find('_') == -1: msg += "%sed a picture" % fn.__name__ elif 'edit_pin' == fn.__name__ or 'delete_pin' == fn.__name__ or fn.__name__ == 'add_comment': msg += "%sed a %s" % (fn.__name__.split('_')[0], fn.__name__.split('_')[1]) else: msg += "updated their %s %s" % (fn.__name__.split('_')[0], fn.__name__.split('_')[1]) notification = Notification(notifier=current_user.uname, msg=msg, date=date) usrs = User.objects.filter(follower_array__contains=current_user.to_dbref()) for usr in usrs: usr.notification_array.append(notification) usr.save() return fn(*args, **kwargs)
def repin(): id = request.form.get('id') pin = Pin.objects.get(id=id) newpin = Pin(title=pin.title, img=pin.img, dscrp=pin.dscrp, orig=False, date=datetime.now(), pinner=current_user.to_dbref(), repins=0, like_count=0) newpin.save() if pin.repins == None: fix_repins() pin = Pin.objects.get(id=id) pin.repins = pin.repins + 1 pin.save() flash("Pin repinned") return redirect('/viewprofile')
def updateUserCommenterPermissions(form): ''' Updates commenter permissions on users pins ''' perm = form.data['pin_commenters'] current_user.update(set__pin_commenters=perm) current_user.save() pins = Pin.objects.filter(pinner=current_user.to_dbref()) if type(pins) == type(''): pins = [ pins ] # Everyone has permission if perm == PERM_EVERYONE: for pin in pins: pin.invalid_commenters = [] pin.save() # Your followers have permission elif perm == PERM_FOLLOWERS: invalid = getFollowerPermissions() for pin in pins: pin.invalid_commenters = invalid pin.save() # People you follow have permission elif perm == PERM_FOLLOWING: invalid = getFollowingPermissions() for pin in pins: pin.invalid_commenters = invalid pin.save() # Followers and following get permission elif perm == PERM_BOTH: invalid = getBothPermissions() for pin in pins: pin.invalid_commenters = invalid pin.save() # Nobody has permission elif perm == PERM_NOBODY: invalid = [ usr.to_dbref() for usr in User.objects.all() if usr.uname != current_user.uname ] for pin in pins: pin.invalid_commenters = invalid pin.save()
def favorite(): id = request.form.get('id') pin = Pin.objects.get(id=id) pin.favs.append(current_user.to_dbref()) pin.save() return redirect("/viewprofile/%s/favorites" % str(current_user.uname))
def make(): pin = Pin(title="Settings 1", img="img1.jpg", dscrp="Description 1", orig=True, date=datetime.now(), pinner=current_user.to_dbref()) pin.save() pin = Pin(title="Settings 2", img="img2.jpg", dscrp="Description 2", orig=True, date=datetime.now(), pinner=current_user.to_dbref()) pin.save() pin = Pin(title="Settings 3", img="img3.jpg", dscrp="Description 3", orig=True, date=datetime.now(), pinner=current_user.to_dbref()) pin.save() pin = Pin(title="Settings 4", img="img4.jpg", dscrp="Description 4", orig=True, date=datetime.now(), pinner=current_user.to_dbref()) pin.save() flash("Pins Created!") return redirect(url_for('index'))
def favorites(): pins = Pin.objects(favs__contains=current_user.to_dbref()) return render_template("profilepins.html", pins=pins, upform=UploadForm())
def profilepins(): pins = Pin.objects(pinner=current_user.to_dbref()).order_by("-date") return render_template("profilepins.html", pins=pins, upform=UploadForm())