Ejemplo n.º 1
0
def get_news_feed(uid=None):

    try:
        friends = get_friend_uid_list(uid)
    except AttributeError:
        friends = []

    activities_dict = {}

    for friend in friends:

        their_uid = friend[0]
        snapshot = ref.child("users").child(their_uid) \
            .child("device").child("past") \
            .order_by_child("time").limit_to_last(5).get().val()

        their_name = ref.child("users").child(their_uid).child(
            "name").get().val()
        extension = ref.child("users").child(their_uid).child(
            "profile_pic_format").get().val()
        profile_pic_url = storageRef.child("users").child(their_uid).child(
            "profile." + extension).get_url(None)

        if snapshot is not None:
            activities_dict.update(
                parse_activity_snapshot(snapshot, their_uid, their_name,
                                        profile_pic_url))

    json_data = create_json_activities_list(activities_dict)

    return json_data, 200, {'Content-Type': 'text/javascript; charset=utf-8'}
Ejemplo n.º 2
0
def get_friend_requests_list(uid=None):
    try:
        # exists = ref.child("friend_requests").child(uid).get().val()
        # if exists is not None:
        test = "https://watshout-cloud.firebaseio.com/friend_requests/{0}.json?orderBy=%22request_type%22&equalTo=%22received%22".format(
            uid)
        friend_request_uid_list = list(requests.get(test).json())
        print(friend_request_uid_list)
        #friend_request_uid_list = list(
        #ref.child("friend_requests").child(uid).order_by_child("request_type").equal_to("received").get().val())

    except IndexError:
        friend_request_uid_list = []

    data = {"friend_requests": []}

    for uid in friend_request_uid_list:
        name = ref.child("users").child(uid).child("name").get().val()
        profile_pic_format = ref.child("users").child(uid).child(
            "profile_pic_format").get().val()
        profile_pic = storageRef.child("users").child(uid).child(
            "profile." + profile_pic_format).get_url(None)
        uid = uid

        data["friend_requests"].append({
            "name": name,
            "profile_pic": profile_pic,
            "uid": uid
        })

    return json.dumps(data), 200, {
        'Content-Type': 'text/javascript; charset=utf-8'
    }
Ejemplo n.º 3
0
def get_friends_list(uid=None):
    try:
        friend_uid_list = get_friend_uid_list(uid)
    except AttributeError:
        friend_uid_list = []

    data = {"friends": []}

    for uid, since in friend_uid_list:
        name = ref.child("users").child(uid).child("name").get().val()
        profile_pic_format = ref.child("users").child(uid).child(
            "profile_pic_format").get().val()
        profile_pic = storageRef.child("users").child(uid).child(
            "profile." + profile_pic_format).get_url(None)
        uid = uid

        data["friends"].append({
            "name": name,
            "profile_pic": profile_pic,
            "uid": uid,
            "since": since
        })

    return json.dumps(data), 200, {
        'Content-Type': 'text/javascript; charset=utf-8'
    }
Ejemplo n.º 4
0
def upload_activity(uid=None, file_name=None):
    try:
        strava_token = ref.child("users").child(uid).child(
            "strava_token").get().val()
        print(strava_token)

        c = StravaClient(access_token=strava_token)

        file_name += ".gpx"

        url = storageRef.child("users").child(uid).child("gpx").child(
            file_name).get_url(None)
        gcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1)  # Only for gangstars
        url_response = urllib.request.urlopen(url, context=gcontext)
        data = url_response.read()
        parsed_data = data.decode('utf-8')

        c.upload_activity(parsed_data, 'gpx')

        return json.dumps({'locationSuccess': True}), 200, {
            'Content-Type': 'text/javascript; charset=utf-8'
        }

    except KeyError:
        return json.dumps({'locationSuccess': False}), 403, {
            'Content-Type': 'text/javascript; charset=utf-8'
        }
Ejemplo n.º 5
0
def user_page(their_uid=None):

    my_uid, verified = get_cookies(request)
    redirect_link = check_user_exists(my_uid, verified)

    if redirect_link is not None:
        return redirect_link

    my_user_entry = get_user_entry(my_uid)

    my_email = my_user_entry["email"]
    my_friends = ref.child("friend_data").child(my_uid).get().val()

    if their_uid in my_friends:

        email = ref.child("users").child(their_uid).get().val()['email']
        name = ref.child("users").child(their_uid).get().val()['name']
        birthday = ref.child("users").child(their_uid).get().val()['birthday']

        profile_pic_format = ref.child("users").child(
            their_uid).get().val()['profile_pic_format']
        profile_pic = storageRef.child('users/' + their_uid + '/profile.' +
                                       profile_pic_format).get_url(None)

        # TODO: Use api endpoint to get list of user's activities

    return "Work in progress"
Ejemplo n.º 6
0
def my_settings():
    my_uid, verified = get_cookies(request)
    redirect_link = check_user_exists(my_uid, verified)

    if redirect_link is not None:
        return redirect_link

    my_user_entry = get_user_entry(my_uid)

    send_user_data = {
        'email': my_user_entry['email'],
        'birthday_month': my_user_entry['birthday'][0:2],
        'birthday_day': my_user_entry['birthday'][3:5],
        'birthday_year': my_user_entry['birthday'][6:10]
    }

    try:
        height_feet = my_user_entry['height-feet']
    except KeyError:
        height_feet = None

    try:
        height_inches = my_user_entry['height-inches']
    except KeyError:
        height_inches = None

    try:
        weight = my_user_entry['weight']
    except KeyError:
        weight = None

    try:
        gender = my_user_entry['gender']
        print(gender)
    except KeyError:
        gender = None

    profile_pic_format = my_user_entry['profile_pic_format']
    profile_pic = storageRef.child('users/' + my_uid + '/profile.' +
                                   profile_pic_format).get_url(None)

    send_user_data['profile_pic'] = profile_pic

    return render_template('new_settings.html',
                           uid=my_uid,
                           user_data=send_user_data,
                           height_feet=height_feet,
                           height_inches=height_inches,
                           weight=weight,
                           gender=gender)
Ejemplo n.º 7
0
def get_calendar_json(uid=None):
    activities_dict = ref.child("users").child(uid).child("device").child(
        "past").get().val()

    extension = ref.child("users").child(uid).child(
        "profile_pic_format").get().val()
    profile_pic_url = storageRef.child("users").child(uid).child(
        "profile." + extension).get_url(None)

    data = {"activities": []}

    if activities_dict is not None:
        for key, value in activities_dict.items():

            current_data = {"time": value['time']}

            attributes_list = [
                "map_link", "event_name", "distance", "time_elapsed", "pace",
                "temp_celsius", "weather_type", "weather_id"
            ]

            for attrib in attributes_list:
                try:
                    current_data[attrib] = value[attrib]
                except KeyError:
                    current_data[attrib] = None

            try:
                current_data["activity_id"] = key
            except KeyError:
                current_data["activity_id"] = None

            try:
                current_data["profile_pic_url"] = profile_pic_url
            except KeyError:
                current_data["profile_pic_url"] = None

            data["activities"].append(current_data)

    return json.dumps(data), 200, {
        'Content-Type': 'text/javascript; charset=utf-8'
    }
Ejemplo n.º 8
0
def add_activity():
    uid = request.form['uid']
    upload_time = float(request.form['time'])
    time_stamp = request.form['time_stamp']
    time_elapsed = float(request.form['time_elapsed'])
    pace = request.form['pace']
    map_url = request.form['map_url']
    distance = float(request.form['distance'])

    gpx = gpxpy.gpx.GPX()

    # Create first track in our GPX:
    gpx_track = gpxpy.gpx.GPXTrack()
    gpx.tracks.append(gpx_track)

    # Create first segment in our GPX track:
    gpx_segment = gpxpy.gpx.GPXTrackSegment()
    gpx_track.segments.append(gpx_segment)

    data = ref.child("users").child(uid).child("device").child(
        "current").get().val()

    # Build GPX
    for key, value in data.items():
        formatted_time = time.strftime('%Y-%m-%d %H:%M:%S',
                                       time.localtime(value["time"] / 1000))
        datetime_object = datetime.strptime(formatted_time,
                                            '%Y-%m-%d %H:%M:%S')
        gpx_segment.points.append(
            gpxpy.gpx.GPXTrackPoint(latitude=value["lat"],
                                    longitude=value["lon"],
                                    elevation=value["altitude"],
                                    time=datetime_object))

    # Move database entry to 'past'
    ref.child("users").child(uid).child("device").child("past").child(
        time_stamp).set({
            "distance": distance,
            "map_link": map_url,
            "time": upload_time,
            "time_elapsed": time_elapsed,
            "type": "run",
            "pace": pace
        })

    ref.child("users").child(uid).child("device").child("current").remove()

    with NamedTemporaryFile() as temp:
        temp.write(gpx.to_xml().encode())
        temp.fileinfo = {'type': 'text/xml', 'Content-Type': 'text/xml'}
        temp.seek(0)

        storageRef.child("users").child(uid).child("gpx").child(
            time_stamp + ".gpx").put(temp)
        gpx_url = storageRef.child("users").child(uid).child("gpx").child(
            time_stamp + ".gpx").get_url(None)

    # Note: Map URL creation has been offloaded to the Android app
    try:
        map_data = create_map_url(gpx_url)
        first_lat = map_data["first_lat"]
        first_lon = map_data["first_lon"]

        city_name = get_location_from_latlng(first_lat, first_lon)
        event_name = city_name + " run"

        weather_id, weather_type, temp_celsius = get_weather(
            first_lat, first_lon)

        ref.child("users").child(uid).child("device").child("past").child(
            time_stamp).child("weather_type").set(weather_type)
        ref.child("users").child(uid).child("device").child("past").child(
            time_stamp).child("weather_id").set(weather_id)
        ref.child("users").child(uid).child("device").child("past").child(
            time_stamp).child("temp_celsius").set(temp_celsius)
        ref.child("users").child(uid).child("device").child("past").child(
            time_stamp).child("event_name").set(event_name)

        return json.dumps({'success': True}), 200, {
            'Content-Type': 'text/javascript; charset=utf-8'
        }

    except Exception as e:
        print(e)
        ref.child("users").child(uid).child("device").child("past").child(
            time_stamp).child("weather_type").set(None)
        ref.child("users").child(uid).child("device").child("past").child(
            time_stamp).child("weather_id").set(None)
        ref.child("users").child(uid).child("device").child("past").child(
            time_stamp).child("temp_celsius").set(None)
        ref.child("users").child(uid).child("device").child("past").child(
            time_stamp).child("event_name").set("Run")
        return json.dumps({'success': True}), 200, {
            'Content-Type': 'text/javascript; charset=utf-8'
        }
Ejemplo n.º 9
0
def my_page():
    my_uid, verified = get_cookies(request)
    redirect_link = check_user_exists(my_uid, verified)

    if redirect_link is not None:
        return redirect_link

    my_user_entry = get_user_entry(my_uid)

    email = my_user_entry['email']
    name = my_user_entry['name']
    birthday = my_user_entry['birthday']

    profile_pic_format = my_user_entry['profile_pic_format']
    profile_pic = storageRef.child('users/' + my_uid + '/profile.' +
                                   profile_pic_format).get_url(None)

    user_info = {"email": email, "name": name, "profile_pic_url": profile_pic}

    # Get friend count
    friends = ref.child("friend_data").child(my_uid).get().val()

    if friends is None:
        user_info["friend_count"] = 0
    else:
        user_info["friend_count"] = len(friends)

    # Get activity count
    activities = ref.child("users").child(my_uid).child("device").child(
        "past").get().val()
    if activities is None:
        user_info["activity_count"] = 0
    else:
        user_info["activity_count"] = len(activities)

    # Get total distance
    distance = 0
    if activities is not None:
        for i in activities:
            distance += float(activities[i]["distance"])

    user_info["total_distance"] = distance

    # Get latest activity image
    latest_activity = ref.child("users").child(my_uid).child("device").child(
        "past").order_by_child("time").limit_to_last(1).get().val()

    if latest_activity is not None:
        for i in latest_activity:
            map_link = latest_activity[i]["map_link"]
            # 47 is the index in which attributes start being defined
            url_front = map_link[:47]
            url_back = map_link[47:]

            new_url = url_front + "&size=2000x300" + url_back
    else:
        new_url = ""

    user_info["latest_activity"] = new_url

    # Try to build a list of user's activities
    try:
        device = ref.child("users").child(my_uid).get().val()['device']['past']

        activity_ids = []

        # Gets the activity 'ID' and adds it to a list
        # (that is parsed as a string)
        for key, value in device.items():
            activity_ids.append(key)

    # User has no activities/devices
    except KeyError:
        activity_ids = ""
        print("User '" + email + "' has no activities")

    # Get the user's Strava auth token
    try:
        strava_token = ref.child("users").child(
            my_uid).get().val()['strava_token']

    # User hasn't authenticated with Strava, throw an error
    except KeyError:
        strava_token = "no"
        print("User '" + email + "' is not connected with Strava")

    return render_template('profile-page.html',
                           uid=my_uid,
                           user_info=user_info,
                           strava_token=strava_token)