Ejemplo n.º 1
0
def find_distance_between_users(user_id_1, user_id_2):
    """ Find shortest path between 2 user objects."""

    user1 = crud.get_user_by_id(user_id_1)
    user2 = crud.get_user_by_id(user_id_2)

    u1_connects = crud.get_connect_by_user_id(user_id_1)
    u2_connects = crud.get_connect_by_user_id(user_id_2)

    explored = []
    queue = deque([[user1]])

    if user1 == user2:
        return 0

    while queue:
        path = queue.popleft()
        node = path[-1]

        if node not in explored:
            neighbors = u1_connects[node]

            for neighbor in neighbors:
                new_path = list(path)
                new_path.append(neighbor)
                queue.append(new_path)

                if neighbor == user2:
                    print("Shortest path:", *new_path)
                    return len(new_path)  # Degrees of separation
            explored.append(node)
    return -1
Ejemplo n.º 2
0
def save_workout_to_profile():
    """Verifies not empty workout before save"""
    #TODO- Future v3.0 - refactor and clean funtion and smarter queries

    workout_name = request.form.get('user_saved_workout_name')
    workout_id = session['workout_id']

    user_id = session['user_id']
    user = crud.get_user_by_id(user_id)
    workouts = crud.workouts_by_user_id(user_id)
    saved_exercises = crud.exercises_from_workout(workout_id)
    json_dict = crud.weight_entries_dict(user_id)

    if saved_exercises == []:
        crud.delete_empty_wkt(workout_id)
        # flash('Workout not saved, no exercises input','error')
        return redirect('/users/' + str(user_id))

    # flash('Workout Saved - Crushing it!')
    return render_template('user_profile.html',
                           user_id=user_id,
                           workout_name=workout_name,
                           workout_id=workout_id,
                           user=user,
                           workouts=workouts,
                           entries_dict=json_dict)
Ejemplo n.º 3
0
def post_main():
    """Create a group or project on the main page"""

    if "group_name" in request.form:
        if crud.does_group_name_exist(request.form.get("group_name")):
            flash(
                'A Group with that name already exists. Please choose another Group name.'
            )
            return view_main()
        else:
            group_name = request.form.get("group_name")
            group = crud.create_group(group_name)
            session["group_id"] = group.group_id
            user_id = session["user_id"]
            user = crud.get_user_by_id(user_id)
            crud.create_association(group, user)
            flash('Group Created! You can click on the Group name to edit it.')
            return view_main()

    if "project_name" in request.form:
        if crud.does_project_name_exist(request.form.get("project_name")):
            flash(
                'A Project with that name already exists. Please choose another Project name.'
            )
            return view_main()
        else:
            user_id = session["user_id"]
            project_name = request.form.get("project_name")
            genre = request.form.get("genre")
            project = crud.create_project(project_name, user_id, genre)
            flash(
                'Project Created. You can click on the Writing Project name to edit it.'
            )
            return view_main()
Ejemplo n.º 4
0
def like_button():
    """Like button."""

    #get reaction:
    like_button = request.args.get("likes_val")
    reaction = like_button  #test

    #subscriber/viewer id
    user_id = session[
        'user_id']  #will overwrite the previous session when a new user(info) is in session
    user = crud.get_user_by_id(user_id)

    #get image id:
    image_id = request.args.get("image_session")
    image = crud.get_image_by_id(int(image_id))
    print('*************', image_id, image, '********')

    print("REACTION BUTTON:", like_button, int(like_button))
    print('GET IMAGE ID FROM JS:', image, '********')

    video = None
    #add to crud
    reaction = crud.create_reaction(user, video, image, int(reaction))
    print("REACTION:", reaction)
    return jsonify({"likes": True})
Ejemplo n.º 5
0
def invite_to_follow(data):
    email = data['email']
    print(f"EMAIL {email}")
    doc_id = data['doc_id']
    print('DOC ID for invite to follow')
    print(doc_id)
    invite_msg = data['msg']
    inviter_id = session['user_id']
    doc = crud.get_doc_by_doc_id(doc_id)
    title = doc.title
    inviter = crud.get_user_by_id(inviter_id)

    user = crud.get_user_by_email(email)

    if user:
        follower = crud.create_doc_follower(user.user_id, doc_id, invite_msg)
        print(follower)
        msg = f"{inviter.fname} {inviter.lname} shared '{title}' with you"
        pkg = {
            'invitee': user.user_id,
            # 'inviter_fname': inviter.fname,
            # 'inviter_lname': inviter.lname,
            # 'title': title,
            'msg': msg,
            'follow_id': follower.doc_follower_id
        }
        io.emit("invite", pkg, include_self=False)
    else:
        msg = f"No user associated with {email}"
Ejemplo n.º 6
0
def add_post_from_page():
    """Create a post on a given cellist's profile."""

    # TODO: handle time zones on the front end - JS library?

    user_id = session['user_id']
    cellist_id = request.form.get('cellist_id_from_profile')
    post_content = request.form.get('post_content')
    post_date = datetime.now(timezone.utc)

    new_post = crud.create_post(user_id, cellist_id, post_content, post_date)
    new_username = crud.get_user_by_id(new_post.user_id).username
    new_date = new_post.post_date.strftime('%b. %d, %Y, %H:%M')
    new_content = new_post.content
    new_post_id = new_post.post_id
    new_post_upvotes = new_post.upvotes

    return jsonify({
        'status': 'ok',
        'new_username': new_username,
        'new_date': new_date,
        'new_content': new_content,
        'new_post_id': new_post_id,
        'new_post_upvotes': new_post_upvotes
    })
Ejemplo n.º 7
0
def get_all_events():
    """Returns all events that are not private"""
    if request.method == "GET":
        events = crud.get_all_events()

        today = date.today()

        all_events = {"past": [], "upcoming": []}

        for event in events:
            event = event.to_dict()
            host = crud.get_user_by_id(event["host_id"]).to_dict()
            attendee_users = crud.get_all_attendees(event["id"])
            attendees = [
                attendee.to_dict() for attendee in attendee_users
                if attendee.id != host["id"]
            ]

            event["attending"] = attendees
            event["host"] = host
            if today <= event["event_date"]:
                all_events["upcoming"].append(event)
            else:
                all_events["past"].append(event)

        return jsonify(all_events)

    if request.method == "DELETE":
        event_id = request.json.get("event_id")
        crud.delete_event(event_id)

        return jsonify(
            {"success": f"Your event has been successfully deleted."})
Ejemplo n.º 8
0
def create_note_reply(data):
    print('received note reply')
    print(data['room'])
    body = data['body']
    room = data['room']  # same as doc id
    user_id = session['user_id']  #check this
    parent_id = data['parent_id']

    user = crud.get_user_by_id(user_id)
    fname = user.fname
    lname = user.lname

    created_at = datetime.datetime.utcnow()
    date_as_int = int(time.mktime(created_at.timetuple())) * 1000

    note_reply = crud.create_note_reply(user_id, room, created_at, body,
                                        parent_id, fname, lname)

    color = note_reply['color']
    note = note_reply['note']

    reply_json = {
        'note_id': note.note_id,
        'user_id': user_id,
        'parent_id': parent_id,
        'doc_id': room,
        'created_at': date_as_int,
        'body': body,
        'fname': fname,
        'lname': lname,
        'color': color
    }

    io.emit("note_reply_created", reply_json, room=room)
Ejemplo n.º 9
0
def update_meetup(meetup_id):
    """Update meetup details."""
    name = request.json.get('name')
    date = request.json.get('date')
    capacity = request.json.get('capacity')
    description = request.json.get('description')

    host = crud.get_user_by_id(session['user_id'])

    meetup = crud.update_meetup_by_id(meetup_id, name, date, capacity,
                                      description)

    notification_data = {
        'message':
        f'Your meetup at {meetup.restaurant.name} has been changed.',
        'link': 'Go to meetup.',
        'url': f'/meetup/{meetup_id}'
    }

    notifications = crud.create_many_notifications(
        'meetup_changed', meetup_id, json.dumps(notification_data), host)

    return jsonify({
        'status': 'success',
        'message': 'Successfully updated meetup.'
    })
Ejemplo n.º 10
0
def update_user(user_id):
    """Update user information."""

    old_password = request.form.get('old_password')
    new_password = request.form.get('new_password')

    user = crud.get_user_by_id(user_id)
    if old_password and not user.check_password(old_password):
        return jsonify({
            'status': 'error',
            'message': 'Previous password is incorrect.'
        })

    password = new_password

    fname = request.form.get('fname')
    lname = request.form.get('lname')
    email = request.form.get('email')
    image = request.files.get('image')
    about = request.form.get('about')
    image_url = ''

    if image:
        cloudinary_upload = cloudinary.uploader.upload(image)
        image_url = cloudinary_upload['url'].partition("upload")[2]

    user = crud.update_user(user, fname, lname, email, password, image_url,
                            about)
    return jsonify({
        'status': 'success',
        'message': 'Information updated successfully.',
        'user': user.to_dict('include_email')
    })
Ejemplo n.º 11
0
def update_user_restaurant_relationship(user_id, restaurant_id):
    """Make restaurant a favorite of the user."""
    #TODO: Make user able to un-favorite a restaurant

    restaurant = crud.get_restaurant_by_id(restaurant_id)
    user = crud.get_user_by_id(user_id)

    # Check if restaurant is in database
    if not restaurant:
        id = request.json['id']
        name = request.json['name']
        cuisine = request.json['categories'][0]['title']
        address = "\n".join(request.json['location']['display_address'])
        longitude = request.json['coordinates']['longitude']
        latitude = request.json['coordinates']['latitude']
        image_url = request.json['image_url']

        restaurant = crud.create_restaurant(id, name, cuisine, address,
                                            longitude, latitude, image_url)

    crud.create_user_restaurant_relationship(user, restaurant)

    return jsonify({
        'status': 'success',
        'message': "Restaurant added to user's favorites."
    })
Ejemplo n.º 12
0
def get_user_emission_info():
    """get the users current month emission info from the db, 
        store it as json for current month charts"""

    current_user = session.get('current_user')
    user_obj = crud.get_user_by_id(current_user)
    month = datetime.now().month
    year = datetime.now().year
    #date = datetime.now()
    #last_month = month - 1
    #TODO:
    #updated values if they arte zero
    monthly_elect = crud.compare_monthly_elect(user_obj.user_id, month, year)
    vehicle_emit = crud.compare_monthly_vehicle_emissions(
        user_obj.user_id, month, year)
    nat_gas_emit = crud.compare_monthly_nat_gas(user_obj.user_id, month, year)
    public_trans_emit = crud.compare_monthly_public_trans(
        user_obj.user_id, month, year)

    print("SEE PUBLIC TRANSIT ****************", public_trans_emit)
    print("MONTHLY ELECTRICITY HERE #######################", monthly_elect)

    emission_info = {
        "labels": [
            "Electricity Emissions", "Vehicle Emissions",
            "Natural Gas Emissions", "Public Transit Emissions"
        ],
        "data": [
            monthly_elect, vehicle_emit, nat_gas_emit,
            "{:.2f}".format(public_trans_emit)
        ]
    }
    print("EMISSION INFO*******", emission_info)
    return jsonify(emission_info)
Ejemplo n.º 13
0
def previous_month_user_emission_info():
    """Get the users previous month emission info from the db, 
        store it as json for previous month charts."""

    current_user = session.get('current_user')
    user_obj = crud.get_user_by_id(current_user)
    month = datetime.now().month
    year = datetime.now().year
    last_month = month - 1

    previous_elect_emission = crud.compare_monthly_elect(
        user_obj.user_id, last_month, year)
    #print("SEEE PREVIOS ELECT EMISSSS ------------", previous_elect_emission)
    previous_month_gas_emit = crud.compare_monthly_nat_gas(
        user_obj.user_id, last_month, year)
    previous_month_vehicle_emit = crud.compare_monthly_vehicle_emissions(
        user_obj.user_id, last_month, year)
    previous_month_public_trans_emit = crud.compare_monthly_public_trans(
        user_obj.user_id, last_month, year)

    previous_month_emit_info = {
        "labels": [
            "Electricity Emissions", "Vehicle Emissions",
            "Natural Gas Emissions", "Transit Emissions"
        ],
        "data": [
            previous_elect_emission, previous_month_vehicle_emit,
            previous_month_gas_emit, previous_month_public_trans_emit
        ]
    }

    return jsonify(previous_month_emit_info)
Ejemplo n.º 14
0
def create_or_get_user():
    """Create a new user or get info about existing user."""

    if request.method == "GET":
        if session.get("user_id"):
            user_id = session["user_id"]
            user = crud.get_user_by_id(user_id)
            user = user.to_dict()
            return jsonify(user)

    if request.method == "POST":
        first_name = request.json.get("first_name")
        last_name = request.json.get("last_name")
        email = request.json.get("email")
        password = request.json.get("password")
        city = request.json.get("city")
        state = request.json.get("state")

        if crud.get_user_by_email(email):
            return jsonify({
                "error":
                f"An account with the email, {email}, already exists."
            })

        user = crud.create_user(first_name, last_name, email, password, city,
                                state)
        first_category = crud.create_category(user.id, "My Favorite Books")
        return jsonify({"user": user.to_dict()})
Ejemplo n.º 15
0
def show_update_form():
    """Show page to update existing users tavel, electric, and gas usage"""

    current_user = session.get('current_user')
    user_obj = crud.get_user_by_id(current_user)

    return render_template("update_info.html")
Ejemplo n.º 16
0
def build_expiration_report(current_user):
    user = crud.get_user_by_id(current_user)
    inventory = crud.get_first_inventory_for_user(user)

    expiring_items = crud.get_items_expiring(inventory, 30)
    expiring_items.sort(key=lambda item: item.expiration_date)

    html_list = []

    row_number = 0

    for item in expiring_items:
        if row_number % 2 == 0:
            html_list.append(f'''<tr style="background-color: #dddddd;">
                                <td>{item.name}</td>
                                <td>{item.quantity}</td>
                                <td>{item.expiration_date.strftime('%d %b %Y')}</td>
                                <td>{item.date_added.strftime('%d %b %Y')}</td>
                            </tr>''')
            row_number += 1

        else:
            html_list.append(f'''<tr>
                                <td>{item.name}</td>
                                <td>{item.quantity}</td>
                                <td>{item.expiration_date.strftime('%d %b %Y')}</td>
                                <td>{item.date_added.strftime('%d %b %Y')}</td>
                            </tr>''')
            row_number += 1
    
    separator = ''
    html_string = separator.join(html_list)
    return html_string
Ejemplo n.º 17
0
def like_entry(entry_id):

    user_id = session['current_user']
    user = crud.get_user_by_id(user_id)

    # selected_rating_id = request.form.get("rating_id")

    # rating = crud.get_rating_by_rating_id(selected_rating_id)

    entry = crud.get_entry_by_id(entry_id)

    # selected_rating_id= request.form.get("rating_id")

    # num_likes= request.form.get("likes-counter")

    rating = crud.create_rating(user, entry)

    ratings = crud.get_entry_ratings(entry_id)

    total_ratings = 0

    for rating in ratings:
        total_ratings += 1

    return str(total_ratings)
Ejemplo n.º 18
0
def get_restaurants_seach():
    location = request.args.get('location')
    longitude = request.args.get('longitude')
    latitude = request.args.get('latitude')
    categories = request.args.get('categories')
    price = request.args.get('price')
    sort_by = request.args.get('sort_by')

    yelp_res = YelpAPI(API_KEY).search_query(location=location,
                                             longitude=longitude,
                                             latitude=latitude,
                                             categories=categories,
                                             price=price,
                                             sort_by=sort_by,
                                             limit=5)

    yelp_list = yelp_res["businesses"]
    biz_list = []

    user_id = session['user_id']
    user = crud.get_user_by_id(user_id)

    for idx in range(len(yelp_list)):
        yelp_id = yelp_list[idx]["id"]
        res = crud.get_restaurant_by_id(yelp_id)
        group_name = None
        if 'group_name' in request.cookies:
            group_name = request.cookies["group_name"]
        like = crud.get_like(user, res, group_name)
        biz = YelpAPI(API_KEY).business_query(id=yelp_id)
        biz_res = restaurant_from_yelp(biz, like, like_count=0)

        biz_list.append(biz_res)

    return jsonify({"businesses": biz_list})
Ejemplo n.º 19
0
def profile_edit():

    user = crud.get_user_by_id(session['id'])

    if request.method == 'GET':
        return render_template('profile_edit.html',
                               user=user,
                               name=session['name'])

    if request.method == 'POST':

        last_name = request.form['last_name']
        email = request.form['email']
        password = request.form['password']
        zipcode = request.form['zipcode']

        if last_name:
            user.last_name = last_name
        if email:
            user.email = email
        if password:
            user.password = password
        if zipcode:
            user.zipcode = zipcode

        db.session.commit()

        flash("Profile updated successfully!")
        return redirect(url_for('profile'))

    else:
        return render_template('index.html', user=user, name=session['name'])
Ejemplo n.º 20
0
def view_only_entry(entry_id):

    entry = crud.get_entry_by_id(entry_id)

    user = crud.get_user_by_id(entry.user_id)

    city_id = entry.city_id

    city = crud.get_city_by_id(city_id)

    ratings = crud.get_entry_ratings(entry_id)

    total_ratings = 0

    for rating in ratings:
        total_ratings += 1

    photo = crud.get_photo_by_entry(entry_id)

    created_at_raw = entry.created_at

    created_at = str(created_at_raw)[0:10]

    return render_template('see_entry_only.html',
                           user=user,
                           entry=entry,
                           city=city,
                           photo=photo,
                           total_ratings=total_ratings,
                           created_at=created_at)
Ejemplo n.º 21
0
def post_comment(meetup_id):
    """Post a comment to a meetup."""
    text = request.json['text']

    writer = crud.get_user_by_id(session['user_id'])
    meetup = crud.get_meetup_by_id(meetup_id)
    comment = crud.create_comment(writer, meetup, text)
    return jsonify({'status': 'success', 'comment': comment.to_dict()})
Ejemplo n.º 22
0
def create_route():
    """Create new route"""

    trip_description = request.form.get('trip_description')
    user = crud.get_user_by_id(session['user'])
    route = crud.create_route(user, trip_description)

    return redirect(f'/api/view_stops/{route.route_id}')
Ejemplo n.º 23
0
def handle_leave_room(room):
    """Remove user from session when they leave a room"""
    user_id = session['user_id']
    user = crud.get_user_by_id(user_id)
    msg = f"{user.fname} has left"
    print(msg)
    del session[request.sid]
    io.emit('leave_msg', msg, room=room, include_self=False)
Ejemplo n.º 24
0
def log_out_user():
    """Log a user out and show them they were successful or not."""
  
    user_id = session.pop("user")
    # user = session.pop("user")
    user = crud.get_user_by_id(user_id)

    return jsonify ({"success": f"{user.first_name}, you have been successfully logged out! Come back soon, and happy reading!"})
Ejemplo n.º 25
0
def get_one_user(user_id: int, db: Session = Depends(get_db)):

    user = get_user_by_id(db, user_id)
    if user:
        return JSONResponse(status_code=status.HTTP_200_OK, content=user)

    raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
                        detail="User not found")
Ejemplo n.º 26
0
def my_gallery():
    """Lets users view and interact with their OWN gallery"""
    if 'user_id' not in session:
        return redirect("/")
    user = crud.get_user_by_id(session['user_id'])
    images = crud.get_image_by_user(user.user_id)

    return render_template('gallery.html', user=user, images=images)
Ejemplo n.º 27
0
def view_wishlist():
    """Show items in wishlist."""

    user_id = session["user_id"]

    user = crud.get_user_by_id(user_id)

    return render_template("view_wishlist.html", user=user)
Ejemplo n.º 28
0
def profile():
    # print('LOGGED IN USER ID:', session['logged_in_user_id'])
    current_logged_in_user = crud.get_user_by_id(session["logged_in_user_id"])
    #print( "************** ___ first name =", current_logged_in_user )
    # user_trail=crud.get_trail_by_user_id(session['logged_in_user_id'])

    # print("***************", user_trail)
    return render_template('user_profile.html',
                           current_logged_in_user=current_logged_in_user)
Ejemplo n.º 29
0
def show_user(user_id):
    """Show users info based on the specified user_id"""

    print('user_id Type: ', type(user_id))
    print('user_id: ', user_id)
    user = crud.get_user_by_id(int(user_id))

    print("USER TYPE: ", user)
    return render_template('user_profile.html', user=user)
Ejemplo n.º 30
0
def delete_restaurant_for_user(user_id, restaurant_id):
    user = crud.get_user_by_id(user_id)
    restaurant = crud.get_restaurant_by_id(restaurant_id)
    crud.delete_user_restaurant_relationship(user, restaurant)

    return jsonify({
        'status': 'success',
        'message': 'Restaurant successfully removed from favorites.'
    })