Ejemplo n.º 1
0
def addIngredient():
    user_id = current_user.get_id()
    form = getIngredientForm()

    if form.validate_on_submit():
        ingredientObj = Ingredient.query.filter_by(name=form.name.data).first()
        currentUserObj = User.query.filter_by(id=current_user.get_id()).first()
        addIngredientToUserFunction(currentUserObj, ingredientObj)
        return '<h1>The name of the ingredient is {}.'.format(form.name.data)

    return render_template('addIngredient.html', form=form)
Ejemplo n.º 2
0
def get_projects():
    """Get the projects belonging to the current user.

    Returns
    -------
    projects : list
        The projects belonging to the current user.

    """
    if current_user.get_id() is None:
        return
    with database.engine.begin() as connection:
        result = connection.execute(
            select([
                models.projects.c.project_id, models.projects.c.name,
                models.projects.c.path, models.projects.c.creation_date,
                models.projects.c.user_id,
                func.count(models.objects.c.object_id).label('object_count')
            ]).select_from(models.projects.outerjoin(models.objects)).where(
                and_(models.projects.c.active == True,
                     models.projects.c.user_id == current_user.id)).group_by(
                         models.projects.c.project_id).order_by(
                             models.projects.c.project_id))
        projects = [dict(row) for row in result]
        for project in projects:
            user = models.User.query.filter_by(id=project['user_id']).first()
            if user:
                project['email'] = user.email
        return projects
Ejemplo n.º 3
0
def listenedto():
    version_id = request.json['version_id']
    listened_to = request.json['listened_to']
    if current_user.is_authenticated:
        return mark_listenedto(current_user.get_id(), version_id, listened_to)
    else:
        abort(403)
Ejemplo n.º 4
0
    def post(self):
        # Add new dataset
        posted_json = request.get_json()

        dataset = Dataset(
            name=posted_json['name'],
            description=posted_json['description'],
            user_id=current_user.get_id(),
            project_id=current_user.get_id(),
            file_id=posted_json['file_id']
        )

        db.session.add(dataset)
        db.session.commit()

        return {'you sent': dataset.id}, 201
Ejemplo n.º 5
0
def upload_thermal_image():
    form = create_upload_thermal_image_form(db.session)
    if request.method=='POST':
        if form.validate_on_submit():
            image = request.files.get('image_file')
            filename = random_string(10)+'_'+secure_filename(image.filename)
            s3.upload_fileobj_thermal_image(image, filename)
            thermal_image = ThermalImage()
            thermal_image.filename = unicode(filename)
            for f in ['description',
                      'year_of_construction',
                      'keywords', ]:
                if request.form.get(f):
                    setattr(thermal_image, f, request.form.get(f))
            if request.form.get('building_type'):
                building_type_id = int(request.form.get('building_type'))
                building_type = BuildingTypes.query.filter(BuildingTypes.id==building_type_id).first()
                setattr(thermal_image, 'building_type', building_type)
            setattr(thermal_image, 'user', User.query.get(current_user.get_id()))
            db.session.add(thermal_image)
            db.session.commit()
            # Send watchers email.
            subject = '[CHEESE] New themrmal image'
            message = 'From '+str(thermal_image.user) \
                      + ' at '+str(datetime.datetime.today())+': ' \
                      + current_app.config['URL_BASE']+str(url_for('thermalimage.details_view', id=thermal_image.id))
            mail.send(Message(subject=subject,
                              body=message,
                              recipients=current_app.config['WATCHERS']))
            # Flash success message.
            flash('The thermal image has been submitted successfully.')
            return redirect(url_for('cheese.upload_thermal_image'))
        else:
            flash('There were problems with your form.', 'error')
    return render_template('upload-thermal-image.html', form=form)
Ejemplo n.º 6
0
def home():
    """Renders the home page."""
    if current_user.get_id() is None:
        print("*************")
    return render_template('index.jade',
                           title='Home Page',
                           year=datetime.now().year,
                           sterms=searchterms,
                           searches=tsearches)
Ejemplo n.º 7
0
def pantry():
    user_id = current_user.get_id()

    userobj = User.query.filter(User.id == user_id).first()
    x = userobj.savedIngredients

    ingredients = ""
    for i in x:
        ingredients += i.name + ' ' + str(i.id) + ' ' + i.imageUrl
    return ingredients
Ejemplo n.º 8
0
def single_version(version_id):
    version = db.session.query(Version.date,Version.url,ListenedTo.lt_id.label('lt_id'),Version.mu,Version.version_id,Song.name.label('song_name'),Song.song_id,Show.show_id,Venue.name.label('venue_name'),Venue.location) \
        .outerjoin(ListenedTo, and_(ListenedTo.user_id == current_user.get_id(), ListenedTo.version_id == version_id)) \
        .join(Song, Song.phishin_id == Version.song_id) \
        .join(Show, Show.phishin_id == Version.show_id) \
        .join(Venue, Show.venue_id == Venue.phishin_id) \
        .filter(Version.version_id==version_id).one()
    comments = db.session.query(VersionComment.body,User.username.label('author')).outerjoin(User, User.id == VersionComment.author_id) \
        .filter(VersionComment.version_id==version_id).order_by(VersionComment.comment_date.desc()).all()
    return render_template('single_version.html',
                           version=version,
                           comments=comments)
Ejemplo n.º 9
0
def set_flag():
    g.user = User.query.filter_by(id = current_user.get_id()).scalar()
    if not g.user:
        return
    g.user.flagstring = flag.flag
    pokeballs = json.loads(g.user.pokeballs)
    split_len = len(flag.flag)/(db.session.query(Product).count() - 1)
    print pokeballs, split_len
    for k,v in pokeballs.iteritems():
        i = Product.query.filter_by(name = k).scalar().id - 1
        if not (v > 0):
            portion=flag.flag[(split_len * i):(split_len * (i + 1))]
            g.user.flagstring = g.user.flagstring.replace(portion, '~' * split_len)
    db.session.commit()
Ejemplo n.º 10
0
def testdata():
    text = """
    From Reqest: {0}
    Name: {1} 
    Email: {2}
    Authenticated {3}
    Active {4}
    Anonymous {5}
    ID  {6}
    REMOMOTE_ADDDR  {7}
    HTTP_HOST  {8}
    """.format(request, current_user.member, current_user.email,
               current_user.is_authenticated,
               current_user.is_active, current_user.is_anonymous,
               current_user.get_id(), request.environ['REMOTE_ADDR'],
               request.environ['HTTP_HOST'])
    return text, 200, {'Content-type': 'text/plain'}
Ejemplo n.º 11
0
def saveRecipeProcess():
    #get the recipe ID
    recipe_id = request.args.get('recipe', 0, type=str)

    recipeObj = Recipe.query.filter(Recipe.id == recipe_id).first()
    userObj = User.query.filter(User.id == current_user.get_id()).first()

    if recipeObj in userObj.savedRecipes:
        print('Unsaving this recipe!')
        userObj.savedRecipes.remove(recipeObj)
        recipeObj.detail.saveCount -= 1
        db.session.commit()
        return jsonify(isSaved=False)
    else:
        print('saving this recipe!')
        saveRecipeFunction(userObj, recipeObj)
        recipeObj.detail.saveCount += 1
        db.session.commit()
        return jsonify(isSaved=True)
Ejemplo n.º 12
0
def race_shop_page():
    product_list = Product.query.all()
    success = False
    message = ''
    if request.method == 'POST':
        quantity = int(request.form['quantity']) if request.form['quantity'] else ''
        item_id = int(request.form['item_id']) if request.form['item_id'] else ''
        if (item_id == ''):
            flash("no product selected. stop tampering with that, you dont need to")
            return render_template('shop.html', message=message, form=forms.shop_obj_form(), user=g.user, success=success)

        product = Product.query.filter_by(id = item_id).scalar()
        if (product == None):
            flash("invalid product. stop tampering with that. you dont need to")
            return render_template('shop.html', message=message, form=forms.shop_obj_form(), user=g.user, success=success)

        g.user = User.query.filter_by(id = current_user.get_id()).scalar()
        if (product.currency == 'poke'):
            if (g.user.pokedollars < product.price * quantity):
                flash("Not enough pokedollars to complete purchase")
            else:
                g.user.pokedollars -= product.price * quantity
                #save user pokeballs here.
                pokeballs = json.loads(g.user.pokeballs)
                pokeballs[product.name] += quantity
                g.user.pokeballs = json.dumps(pokeballs)
                db.session.commit()
                set_flag()
                flash("Purchased {} {}".decode('utf-8').format(quantity, product.name))
        elif (product.currency == 'real'):
            if (g.user.realdollars < product.price * quantity):
                flash("Not enough realdollars to complete purchase")
            else:
                g.user.realdollars -= product.price * quantity
                #save g.user realballs here.
                db.session.commit()
                set_flag()
                flash("Purchased {} {}".decode('utf-8').format(quantity, product.name))

    return render_template('shop2.html', message=message, form=forms.shop_obj_form(), user=g.user, success=success, products_list = product_list)
Ejemplo n.º 13
0
def email_action(id, action):
    """ Perform action 'action' on UserEmail object 'id'
    """
    user_manager =  current_app.user_manager
    db_adapter = user_manager.db_adapter

    # Retrieve UserEmail by id
    user_email = db_adapter.find_first_object(db_adapter.UserEmailClass, id=id)

    # Users may only change their own UserEmails
    if not user_email or user_email.user_id != int(current_user.get_id()):
        return unauthorized()

    if action=='delete':
        # Primary UserEmail can not be deleted
        if user_email.is_primary:
            return unauthorized()
        # Delete UserEmail
        db_adapter.delete_object(user_email)
        db_adapter.commit()

    elif action=='make-primary':
        # Disable previously primary emails
        user_emails = db_adapter.find_all_objects(db_adapter.UserEmailClass, user_id=int(current_user.get_id()))
        for ue in user_emails:
            if ue.is_primary:
                ue.is_primary = False
        # Enable current primary email
        user_email.is_primary = True
        # Commit
        db_adapter.commit()

    elif action=='confirm':
        _send_confirm_email(user_email.user, user_email)

    else:
        return unauthorized()

    return redirect(url_for('user.manage_emails'))
Ejemplo n.º 14
0
def race_swap_page():
    cur_poke = db.session.query(User.pokedollars).filter_by(id = current_user.get_id()).scalar()
    #time.sleep(2)
    cur_real = db.session.query(User.realdollars).filter_by(id = current_user.get_id()).scalar()
    success = False

    message = 'Exchange your MokéDollars for `real` money here!'.decode('utf-8')
    if request.method == 'POST':
        quantity = int(request.form['quantity']) if request.form['quantity'] else ''
        if ('poke' in request.form):
            # real -> poke conversion -> 1 real = 10 poke
            if (cur_real >= quantity):
                g.user.pokedollars += quantity * 10
                db.session.commit()

                # we intentionally want to get new values to mess with
                g.user = User.query.filter_by(id = current_user.get_id()).scalar()
                cur_real -= quantity
                g.user.realdollars = cur_real
                db.session.commit()
            else:
                flash("insufficient real dollars")
        elif ('real' in request.form):
            # poke -> real conversion -> 10 poke = 1 real

            if (quantity % 10 != 0):
                flash("can only convert multiples of 10")
                g.user = User.query.filter_by(id = current_user.get_id()).scalar() # very database heavy
                return render_template('swap.html', message=message, form=forms.swap_form(), user=g.user, success=success)

            if (cur_poke >= quantity):
                g.user.realdollars += quantity / 10
                db.session.commit()

                # we intentionally want to get new values to mess with
                g.user = User.query.filter_by(id = current_user.get_id()).scalar()
                cur_poke -= quantity
                g.user.pokedollars = cur_poke
                db.session.commit()
            else:
                flash("insufficient poke dollars")


    g.user = User.query.filter_by(id = current_user.get_id()).scalar() # very database heavy
    return render_template('swap.html', message=message, form=forms.swap_form(), user=g.user, success=success)
Ejemplo n.º 15
0
def single_song(song_id):
    song = db.session.query(Song).filter(Song.song_id == song_id).one()

    versions = db.session.query(Version.date,Version.version_id,Version.mu,func.count(Vote.vote_id).label('count'), \
        func.count(ListenedTo.lt_id).label('lt_id')) \
        .outerjoin(ListenedTo, and_(ListenedTo.version_id == Version.version_id, ListenedTo.user_id == current_user.get_id())) \
        .outerjoin(Vote, or_(Vote.lhs == Version.version_id, Vote.rhs == Version.version_id)) \
        .filter(Version.song_id==song.phishin_id) \
        .group_by(Version.version_id).subquery('versions')

    versions_with_comments = db.session.query(versions, func.count(VersionComment.versioncomment_id).label('vc_count')) \
        .outerjoin(VersionComment, VersionComment.version_id == versions.c.version_id) \
        .group_by(versions.c.version_id) \
        .order_by(versions.c.mu.desc(),versions.c.count.desc(),func.count(VersionComment.versioncomment_id).desc())

    versions = versions_with_comments.all()

    return render_template('single_song.html', song=song, versions=versions)
Ejemplo n.º 16
0
def savedRecipes():
    recipes = User.query.filter(User.id == current_user.get_id()).first().savedRecipes
    return render_template('savedRecipes.html', recipes=recipes)