def FetchGPSData(tokensFile,CPCdate,CPClen):
    client = Client()
    ###To get the saved access tokens below, I did the following:
    ##1. Run the following lines:
    #authorize_url = client.authorization_url(client_id=22380, redirect_uri='http://sustainability.leeds.ac.uk',approval_prompt='force')
    #print(authorize_url)
    ##2. Paste the above url into a browser, accept the request,
    ##   and copy the 'code' from the resulting url into the following line,
    ##   along with the client_secret which can be found under air pollution9 account on strava:
    #access_token = client.exchange_code_for_token(client_id=22380, client_secret='***',
    #  code='***')
    ##3. Extract token from the above variable:
    #print(access_token)
    ###Saved access tokens:
    f=open(tokensFile,'r')
    myTokens=f.read().splitlines()
    f.close()
    #Find activity which most closely matches CPC start date/time and sample length
    #All activities within 5 mins of the CPC start date are considered
    #The activity with the closest-matching elapsed time to the CPC sample length is then chosen
    validActs={}
    for i,token in enumerate(myTokens):
        client.access_token = token
        #athlete = client.get_athlete()
        #print(athlete.firstname,athlete.lastname+':')
        myActivities=client.get_activities()
        for activity in myActivities:
            startDate=activity.start_date_local
            #print('    '+activity.name+':',startDate,'Local time')
            if abs((CPCdate-startDate).total_seconds()) < 60:
                validActs.update({i:activity.id})
    assert len(validActs) > 0, "No GPS activities with a start time within 5 minutes of the CPC data file start time"
    DeltaT=1e10
    for key,value in validActs.items():
        client.access_token=myTokens[key]
        activity=client.get_activity(value)
        elap=activity.elapsed_time.seconds
        thisDT=abs(CPClen-elap)
        if thisDT < DeltaT:
            DeltaT=thisDT
            chosenAth=key
            chosenAct=value
    #Extract required data from chosen activity:
    client.access_token=myTokens[chosenAth]
    activity=client.get_activity(chosenAct)
    startDate=activity.start_date_local
    endDate=startDate+dt.timedelta(seconds=activity.elapsed_time.seconds)
    endDateCPC=CPCdate+dt.timedelta(seconds=CPClen)
    assert abs((endDateCPC-endDate).total_seconds()) < 60, "No valid GPS activities with an end time within 1 minute of the CPC data file end time"
    myTypes = ['time', 'latlng']
    myStream = client.get_activity_streams(chosenAct,types=myTypes)
    latlon=myStream['latlng'].data
    lat=[latlon[i][0] for i in range(len(latlon))]
    lon=[latlon[i][1] for i in range(len(latlon))]
    time=myStream['time'].data
    dateTime=[startDate+dt.timedelta(seconds=i) for i in time]
    GPSData=pd.DataFrame(data={'lon':lon,'lat':lat,'dateTime':dateTime})
    return GPSData
def get_strava_client(user_id=None):

    client = Client()
    if user_id is None:
        client.access_token = ConfigService.getConfigVar('strava.access_token')
    else:
        user = UserManager.get_user(user_id)
        if user:
            client.access_token = user.access_token
        else:
            print "[stravaM]: User {0} not found".format(user_id)
            return False

    return client
Beispiel #3
0
def api_profiles_activities_id(player_id, activity_id):
    if not request.stream:
        return '', 400
    activity_id = int(activity_id) & 0xffffffffffffffff
    activity = activity_pb2.Activity()
    activity.ParseFromString(request.stream.read())
    update_protobuf_in_db('activity', activity, activity_id)

    response = '{"id":%s}' % activity_id
    if request.args.get('upload-to-strava') != 'true':
        return response, 200
    try:
        from stravalib.client import Client
    except ImportError:
        logger.warn(
            "stravalib is not installed. Skipping Strava upload attempt.")
        return response, 200
    strava = Client()
    try:
        with open('%s/strava_token.txt' % STORAGE_DIR, 'r') as f:
            strava.access_token = f.read().rstrip('\r\n')
    except:
        logger.warn(
            "Failed to read %s/strava_token.txt. Skipping Strava upload attempt."
        )
        return response, 200
    try:
        # See if there's internet to upload to Strava
        strava.upload_activity(BytesIO(activity.fit),
                               data_type='fit',
                               name=activity.name)
        # XXX: assume the upload succeeds on strava's end. not checking on it.
    except:
        logger.warn("Strava upload failed. No internet?")
    return response, 200
    def handle(self, *args, **options):
        self.stdout.write("Updating the Acacia event miles")

        client = Client()
        rides_after = datetime(2018, 9, 1)
        rides_before = datetime(2018, 9, 3)

        participants = BigBulletRider.objects.exclude(
            access_token__isnull=True)
        for particpant in participants:
            self.stdout.write("Looking up activities for " +
                              str(particpant.name))

            client.access_token = particpant.access_token
            activities = client.get_activities(before=rides_before,
                                               after=rides_after)

            for activity in activities:
                km = unithelper.kilometers(activity.distance).num
                self.stdout.write("Got activity " + str(activity.id) +
                                  " distance = " + str(km) + " = " +
                                  str(activity))
                ride, created = BigBulletRide.objects.get_or_create(
                    activity_id=activity.id,
                    bullet=particpant,
                    distance=km,
                    start_date=activity.start_date)
                self.stdout.write("Created = " + str(created))
Beispiel #5
0
def rides(request):

    if (not request.user.is_authenticated):
        return JsonResponse({"user_auth": False})

    client = Client()
    user = AuthUser.objects.get(user_id=request.user.id)
    client.access_token = user.auth_code

    _before = datetime.now()
    _after = datetime(2018, 4, 1)

    batched_activities = client.get_activities(before=_before, after=_after)
    list_activities = list(batched_activities)
    rtn_activity_list = []

    for a in list_activities:
        detailed_activity = client.get_activity(a.id)
        _new_activity = JsonActivity(detailed_activity.id, detailed_activity.map.polyline, a.distance, a.start_date)
        rtn_activity_list.append(_new_activity.toJson())
    
    rtn = {
        "user_auth": True,
        "activities": rtn_activity_list
    }

    return JsonResponse(rtn)
Beispiel #6
0
    def create_client(self):
        self.s3_file_manager.download_file('strava_auth.json',
                                           '/tmp/strava_auth.json')
        with open('/tmp/strava_auth.json') as auth_json:
            data = json.load(auth_json)
            access_token = data['access_token']
            refresh_token = data['refresh_token']
            expires_at = data['expires_at']

        client = Client()
        client.access_token = access_token
        client.refresh_token = refresh_token
        client.token_expires_at = expires_at

        if time.time() > client.token_expires_at:
            print('Token has expired - refreshing...')
            refresh_response = client.refresh_access_token(
                client_id=int(os.getenv('STRAVA_CLIENT_ID', None)),
                client_secret=os.getenv('STRAVA_CLIENT_SECRET', None),
                refresh_token=client.refresh_token)

            with open('/tmp/strava_auth.json', 'w') as outfile:
                json.dump(refresh_response, outfile)

            self.s3_file_manager.upload_file('/tmp/strava_auth.json',
                                             'strava_auth.json')

        return client
Beispiel #7
0
def get_client_or_authorize_url():
    """Get strava client, or authorization URL if not authenticated"""
    client = Client()
    authorize_url = None

    if "strava_refresh_token" in session.keys():
        client.refresh_token = session["strava_refresh_token"]

        LOGGER.debug("{} / {} / {}".format(
            session["strava_access_token"],
            session["strava_refresh_token"],
            session["strava_expires_at"],
        ))

    if ("strava_access_token" in session.keys()
            and int(session["strava_expires_at"]) >
            datetime.datetime.now().timestamp()):
        client.access_token = session["strava_access_token"]
        client.refresh_token = session["strava_refresh_token"]
        client.token_expires_at = session["strava_expires_at"]
    else:
        authorize_url = get_authorization_url()

    LOGGER.debug("Authorize URL: {}".format(authorize_url))
    return client, authorize_url
Beispiel #8
0
def strava_upload(tcxfiles, login=None):
    logging.basicConfig(level=logging.DEBUG)

    client = Client()

    creds = read_strava_auth_file()
    if login == None:
      if len(creds) > 0:
        print("found strava credentials for: " )
        n = 0
        for email in creds.keys():
          print(str(n) + " " + email)
          n += 1
   
        index_input = raw_input("enter the number corresponding to your email address.  Or just press enter to use your default browser to login\n")
        if re.match("\A\d+\Z", index_input):
          index = int(index_input)
          if index < len(creds):
            login = creds.keys()[index]
    
    if login and creds.has_key(login):
      client.access_token = creds[login]
    else:
      strava_authorize(client)

    for tcxfile in tcxfiles:
      r = post_file_to_strava(client, tcxfile)
      if(r.status_code == 401):
        print("invalid auth token, rerequesting authorization")
        strava_authorize(client)
        r = post_file_to_strava(client, tcxfile)

      if(r.status_code not in [200,201]):
        print("error uploading file.  HTTP response code: " + str(r.status_code))
        print(str(r.text))
Beispiel #9
0
def send_run_to_strava():
    '''Ask whether to send a run to strava if it hasn't already.  Option to
    add a description.  Update on_strava field in database if successfully
    sent or prompted to do so if not sent.'''
    cfg.read(os.path.join(os.getenv('HOME'), '.config/strava.cfg'))
    access_token = cfg.get('Strava', 'access_token')
    client = Client()
    client.access_token = access_token
    runs = get_list_of_runs_not_on_strava()
    for run in runs:
        print run
        send = raw_input("Send this run to Strava? (Y|N): ")
        if (send[0] in ['Y', 'y']):
            start_time = raw_input(
                "What time did the activity start HH:MM:SS: ")
            date_of_activity = "%sT%sZ", (run.run_date, start_time)
            description = raw_input("Add an optional description: ")
            client.create_activity(run.name,
                                   ACTIVITY_TYPE,
                                   date_of_activity,
                                   run.time,
                                   description,
                                   unithelper.miles(run.distance))
            mark_run_as_on_strava(run.run_date, run.route_id, run.athlete_id)
            logging.info("Sent this activity to Strava: %s", run)
        else:
            update = raw_input("Update this run as on Strava (Y|N): ")
            if (update[0] in ['Y', 'y']):
                mark_run_as_on_strava(
                    run.run_date, run.route_id, run.athlete_id)
    def collect_ride_data(self, challenge):
        """
        Pull the latest ride data from Strava via the API
        """
        client = Client()
        client.access_token = self.strava_config['access-token']
        #activities = client.get_club_activities(165009)
        activities = client.get_club_activities(challenge.get_group_id())

        act_list = []
        for activity in activities:
            if not activity.type == 'Ride' and not activity.type == 'VirtualRide':
                print 'Non-ride activity: %s, type: %s' % (activity.name, activity.type)
                continue
            act = Activity(activity.id)
            act.set_athlete(activity.athlete.id)
            act.set_name(activity.name)
            act.set_gmt_date(activity.start_date) # GMT Start date
            act.set_elapsed_time(activity.elapsed_time)
            act.set_distance(round(unithelper.kilometers(activity.distance).num, 2))
            act.set_elevation(unithelper.meters(activity.total_elevation_gain).num)
            act.set_ride_type(activity.type)
            act.set_trainer_ride(activity.trainer)
            act_list.append(act)
        db_store = GTDataStore(challenge.get_db_path(), self.verbose)
        db_store.store_if_new(act_list)
    def handle(self, *args, **options):
        settings_obj = Site.objects.get_current().settings

        self.stdout.write("Updating the Strava cache...")
        if settings.STRAVA_ACCESS_TOKEN == None:
            self.stdout.write("You must set STRAVA_ACCESS_TOKEN")
            return

        client = Client()
        client.access_token = settings.STRAVA_ACCESS_TOKEN

        if settings.STRAVA_CYCLING_CLUB != 0:
            cycling_club = client.get_club(settings.STRAVA_CYCLING_CLUB)
            self.stdout.write("Got this many cyclists = " +
                              str(cycling_club.member_count))
            settings_obj.cyclists = cycling_club.member_count

    #        self.stdout.write("Getting cycling activities")
    #        cycling_activities = client.get_club_activities(settings.STRAVA_CYCLING_CLUB)	# Just get all of them, database can dedupe
    #        self.insert_into_db(cycling_activities, ActivityCache.RIDE)

        if settings.STRAVA_RUNNING_CLUB != 0:
            running_club = client.get_club(settings.STRAVA_RUNNING_CLUB)
            self.stdout.write("Got this many runners = " +
                              str(running_club.member_count))
            settings_obj.runners = running_club.member_count

    #        self.stdout.write("Getting running activities")
    #        running_activities = client.get_club_activities(settings.STRAVA_RUNNING_CLUB)
    #        self.insert_into_db(running_activities, ActivityCache.RUN)

        settings_obj.save()
Beispiel #12
0
def main(ctx):
    client = Client()
    client.access_token = get_access_token()

    ctx.obj['client'] = client
    ctx.obj['athlete'] = client.get_athlete()

    ctx.obj['bikes'] = get_bikes(ctx.obj['athlete'])
Beispiel #13
0
def make_client(client_id, client_secret, refresh_token):
    client = Client()

    refresh_response = client.refresh_access_token(
        client_id=client_id, client_secret=client_secret, refresh_token=refresh_token
    )
    client.access_token = refresh_response["access_token"]
    return client
Beispiel #14
0
def __get_strava_client(request):
    client = Client()
    if request.user:
        if request.user.social_auth:
            provider = request.user.social_auth.get(provider='strava')
            if provider:
                if 'access_token' in provider.extra_data.keys():
                    client.access_token = provider.extra_data['access_token']
    return client
Beispiel #15
0
def strava_client(client_id=None,
                  client_secret=None,
                  refresh_token=None,
                  access_token=None):
    client = Client()
    if access_token is None:
        authorize_url = client.authorization_url(
            client_id=client_id,
            redirect_uri='http://localhost:8282/authorized',
            scope='view_private,write')
        logging.info("Go to %s" % (authorize_url))
        code = raw_input("Code: ")
        client.access_token = client.exchange_code_for_token(
            client_id=client_id, client_secret=client_secret, code=code)
        logging.info("Access Token = %s" % (client.access_token))
    else:
        client.access_token = access_token

    return client
Beispiel #16
0
def get_images(segment_id):
    access_token = request.cookies.get('access_token')
    if not access_token:
        return redirect("/")
    client = Client(rate_limiter=limiter.DefaultRateLimiter())
    client.access_token = access_token

    # look into this: https://github.com/saimn/sigal/
    images = get_images_from_segment(segment_id, client)
    return render_template('test.html', images=images)
Beispiel #17
0
def pull_activities(access_token,
                    firstname,
                    lastname,
                    from_time="2018-01-01T00:00:00Z"):
    # An authorized callback is coming. Process it and add
    client = Client()
    client.access_token = access_token
    for activity in client.get_activities(after=from_time, limit=500):
        process_activity(activity, firstname, lastname)

    return True
Beispiel #18
0
def get_strava_client():
    token_dict = current_token_dict()
    if token_dict:
        client = Client()
        client.access_token = token_dict['access_token']
        client.refresh_token = token_dict['refresh_token']
        # If token is old, refresh it
        if time.time() > token_dict['expires_at']:
            app.server.logger.debug('Strava tokens expired, refreshing...')
            refresh_response = client.refresh_access_token(client_id=client_id, client_secret=client_secret,
                                                           refresh_token=client.refresh_token)
            # Save to db
            save_strava_token(refresh_response)
            # Update client
            client.access_token = refresh_response['access_token']
            client.refresh_token = refresh_response['refresh_token']
    else:
        client = Client()

    return client
Beispiel #19
0
 def check_oauth_token(cls, access_token):
     if not access_token:
         return False
     c = Client()
     c.access_token = access_token
     try:
         c.get_athlete()
     except HTTPError:
         return False
     else:
         return True
Beispiel #20
0
    def get_user(self):
        client = Client()
        token = self.accessToken()

        if token is None:
            return None

        client.access_token = token
        athlete = client.get_athlete()
        return dict(first_name=athlete.firstname,
                    last_name=athlete.lastname,
                    email=athlete.email)
Beispiel #21
0
    def get_user(self):
        client = Client()
        token = self.accessToken()

        if token is None:
            return None

        client.access_token = token
        athlete = client.get_athlete()
        return dict(first_name=athlete.firstname,
                    last_name=athlete.lastname,
                    email=athlete.email)
Beispiel #22
0
def add_athlete(access_token):
    # An authorized callback is coming. Process it and add
    client = Client()

    # Now store that access token along with athlete details
    client.access_token = access_token
    athlete = client.get_athlete()
    ath = extract_athlete(athlete)
    ath['access_token'] = access_token
    dao = MainDAO()
    dao.add_athlete(ath)
    pull_activities(access_token, ath['firstname'], ath['lastname'])
    return True
Beispiel #23
0
def get_client():
    client = Client()
    authorize_url = client.authorization_url(
        client_id=26273,
        redirect_uri='https://localhost:8080',
        scope=['read', 'read_all', 'activity:read_all'])
    code = '299ad7943b6eb478247684620d87e341cfdcb6a2'
    access_token = client.exchange_code_for_token(
        client_id=26273,
        client_secret='80f4236b6e958701dbeebb8c09c99e9d2fb71d1a',
        code=code)
    client.access_token = access_token['access_token']
    return client
Beispiel #24
0
def main(action, filename):
    if action == "DOWNLOAD":
        client = Client()
        client.access_token = access_token
        athlete = client.get_athlete()
        print("For {id}, I now have an access token {token}".format(
            id=athlete.id, token=access_token))
        fileToUpload = open(filename, 'rb')
        activityUploader = client.upload_activity(fileToUpload, 'fit',
                                                  'TestActivity', '', 'ride',
                                                  False, '1')
        activityUploader.wait(60, 1)
        print('Finished uploading to strava')
        return 0
Beispiel #25
0
    def get_strava_activities(self, strava_social, from_date=None):
        new_activities = []
        provider_name = 'strava'
        if self.relate_activities:
            existing_ids = self.activities.filter(
                provider=provider_name).values_list('original_id', flat=True)
        else:
            existing_ids = Activity.objects.filter(
                provider=provider_name).values_list('original_id', flat=True)

        # get access token
        token = strava_social.get_access_token(load_strategy())

        # get activity details
        client = Client()
        client.access_token = token

        query = client.get_activities(after=from_date)

        try:
            for strava_activity in query:
                strava_id = strava_activity.id
                if not strava_id in existing_ids:

                    new_activity = Activity()
                    new_activity.original_id = strava_id
                    new_activity.provider = provider_name

                else:
                    new_activity = self.activities.get(original_id=strava_id)

                new_activity.date = strava_activity.start_date_local
                new_activity.distance = strava_activity.distance
                new_activity.duration = strava_activity.elapsed_time
                new_activity.name = strava_activity.name
                new_activity.type = strava_activity.type

                if self.relate_activities:
                    new_activity.member = self
                else:
                    new_activity.member = None

                new_activity.save()

                new_activities.append(new_activity)
        except:
            print('User f{self} ha no permissions on strava')
            strava_social.delete()

        return new_activities
Beispiel #26
0
def authorized():
	# get access token to make requests
	client = Client()
	code = request.args.get('code')
	client.access_token = client.exchange_code_for_token(client_id=creds.client_id, client_secret=creds.client_secret, code=code) # add id and secret

	# get data
	today = datetime.datetime.strptime(str(datetime.date.today()), "%Y-%m-%d")
	one_month_ago = today - dateutil.relativedelta.relativedelta(months=1)
	athlete = client.get_athlete()
	activities = client.get_activities(after=one_month_ago)
	rides = toolkit.get_activity_types(activities, 'ride')
	runs = toolkit.get_activity_types(activities, 'run')
	ride_set = ActivitySet("Rides", rides)
	run_set = ActivitySet("Runs", runs)
	return render_template('main.html', athlete=athlete, activity_sets=[ride_set, run_set])
Beispiel #27
0
def index(request):

    user = None 

    if (request.user.is_authenticated):
        user = AuthUser.objects.get(user_id=request.user.id)

    client = Client()
    authorize_url = client.authorization_url(client_id=24429, redirect_uri="http://localhost:8000/main")

    #get code from get
    #Get Code from webapp response
    code = request.GET.get('code') if (request.GET.get('code') != None) else ''

    start_pos, end_pos, a_polyline = '', '', ''
    if (code != '' and request.user.is_authenticated):

        access_token = client.exchange_code_for_token(client_id=24429, client_secret=config_vars.STRAVA_CLIENT_SECRET, code=code)

        user_model = AuthUser.objects.get(user_id=request.user.id)
        
        # Store User Access Token in DB
        if (user_model is not None):
            user_model.auth_code = access_token
            user_model.save()

    # Set Access Token On Client
    if (request.user.is_authenticated and user.auth_code != ''):
        
        pprint("User Logged in and has an auth code")
        client.access_token = user.auth_code
        athlete = client.get_athlete()

        full_activity = client.get_activity(1486441471, True)
        
        a_polyline = full_activity.map.polyline
        start_pos = full_activity.start_latlng
        end_pos = full_activity.end_latlng


    return render(request, "index.html", {
        "auth_url": authorize_url, 
        "start_pos": start_pos,
        "end_pos": end_pos,
        "polyline": a_polyline,
        "user_is_authenticated": request.user.is_authenticated 
    })
Beispiel #28
0
def strava_last_activity(request):
    currentUser = User.objects.get(pk=request.user.id)

    client = Client()
    client.access_token = currentUser.profile.stravaAccessCode

    activities = client.get_activities(before=datetime.datetime.now(), limit=1)
    activityName = ''
    for activity in activities:
        activityName = activity.name
        downloadedActivity = client.get_activity(activity.id)
        activityStream = client.get_activity_streams(activity.id,
                                                     types=["time", "watts"])
        averageCadence = downloadedActivity.average_cadence

    return render(request, 'strava_last_activity.html',
                  {'activity_name': averageCadence})
Beispiel #29
0
def strava_redirect(request):
    auth_code = request.GET.get("code")
    client = Client()
    access_token = client.exchange_code_for_token(CLIENT_ID, CLIENT_SECRET,
                                                  auth_code)
    client.access_token = access_token

    global accesToken
    accesToken = access_token

    athlete = client.get_athlete()

    currentUser = User.objects.get(pk=request.user.id)
    currentUser.profile.stravaAccessToken = access_token
    currentUser.profile.save()

    return render(request, 'strava_redirect.html',
                  {'athlete_name': athlete.username})
def get_activities(access_token, output_file):
    
    """Retrieving all user activities and output them in CSV format"""

    client = Client()
    client.access_token = access_token

    filewriter = csv.writer(output_file, delimiter=",", quotechar="|", quoting=csv.QUOTE_MINIMAL)
    filewriter.writerow(["ID", "Name", "Distance", "Type", "Workout type", "Start date", "Was manually added", "Is private", "Gear ID", "Description"])

    activities_count = 0
    for activity in client.get_activities():

        filewriter.writerow([activity.id, activity.name, activity.distance, activity.type, activity.workout_type, activity.start_date, activity.manual, activity.private, activity.gear_id, activity.description])

        activities_count += 1

    print("[+] Number of saved activities: {}".format(activities_count))
Beispiel #31
0
def strava_upload(player_id, activity):
    try:
        from stravalib.client import Client
    except ImportError:
        logger.warn(
            "stravalib is not installed. Skipping Strava upload attempt.")
        return
    profile_dir = '%s/%s' % (STORAGE_DIR, player_id)
    strava = Client()
    try:
        with open('%s/strava_token.txt' % profile_dir, 'r') as f:
            client_id = f.readline().rstrip('\r\n')
            client_secret = f.readline().rstrip('\r\n')
            strava.access_token = f.readline().rstrip('\r\n')
            refresh_token = f.readline().rstrip('\r\n')
            expires_at = f.readline().rstrip('\r\n')
    except:
        logger.warn(
            "Failed to read %s/strava_token.txt. Skipping Strava upload attempt."
            % profile_dir)
        return
    try:
        if time.time() > int(expires_at):
            refresh_response = strava.refresh_access_token(
                client_id=client_id,
                client_secret=client_secret,
                refresh_token=refresh_token)
            with open('%s/strava_token.txt' % profile_dir, 'w') as f:
                f.write(client_id + '\n')
                f.write(client_secret + '\n')
                f.write(refresh_response['access_token'] + '\n')
                f.write(refresh_response['refresh_token'] + '\n')
                f.write(str(refresh_response['expires_at']) + '\n')
    except:
        logger.warn("Failed to refresh token. Skipping Strava upload attempt.")
        return
    try:
        # See if there's internet to upload to Strava
        strava.upload_activity(BytesIO(activity.fit),
                               data_type='fit',
                               name=activity.name)
        # XXX: assume the upload succeeds on strava's end. not checking on it.
    except:
        logger.warn("Strava upload failed. No internet?")
Beispiel #32
0
	def handle(self, *args, **options):
		client = Client()
		client.access_token = '20bf9e2864c1411d17d9cab8c11aa8dbe626aedd'
		cityEntries = City.objects.all()
		resetPlaceChanges = False
		if not cityEntries:
			cityEntries = createDefaultCitySegments()
			resetPlaceChanges = True

		for city in cityEntries:
			updater = CityLeaderboardUpdater(city, client)
			updater.update()

		# Delete placement changes if data has just been reset
		if resetPlaceChanges:
			placementChanges = PlacementChange.objects.all()
			for pc in placementChanges.iterator():
				pc.delete()
		print("Updated at " + str(timezone.now()))
    def authorize(self):
        client = Client()
        authorize_url = client.authorization_url(
            client_id=9531, redirect_uri='http://127.0.0.1:5000/authorization')
        # Have the user click the authorization URL, a 'code' param will be added to the redirect_uri
        # .....

        # Extract the code from your webapp response
        # code = request.args.get('code') # or whatever your framework does
        # access_token = client.exchange_code_for_token(client_id=9531, client_secret='111b5017534c4bd4049f8ff941790b0762b63701', code=code)

        access_token = "990aa3bd5897c731ee759794edeecd7c058939de"
        # Now store that access token somewhere (a database?)
        client.access_token = access_token
        athlete = client.get_athlete()
        print("For {id}, I now have an access token {token}".format(
            id=athlete.id, token=access_token))
        athlete = client.get_athlete(227615)
        print("Hello, {}".format(athlete.firstname))
def main():
    global leader_list

    client = Client()
    authorize_url = client.authorization_url(
        client_id=16694, redirect_uri='http://localhost:8282/authorized')

    access_token = '1a424f23c2b57360dab45e720a9a45bd0868f299'

    client.access_token = access_token
    rex = client.get_athlete(168768)
    abdul = client.get_athlete(9954274)
    addison = client.get_athlete(3070847)
    jd = client.get_athlete(2903427)

    leaders = client.get_segment_leaderboard(7769406)
    for leader in leaders:
        name = (str(leader.athlete_name))
        leader_list.append(name)
    print(leader_list)
Beispiel #35
0
def fetch_stats():
    client = Client()

    refresh_response = client.refresh_access_token(client_id=client_id,
                                                   client_secret=client_secret,
                                                   refresh_token=refresh_token)
    client.access_token = refresh_response['access_token']
    stats = client.get_athlete_stats()

    return textwrap.dedent(f"""\
    #### Recent rides

{get_stat_values(stats.recent_ride_totals)}

    #### YTD ride totals

{get_stat_values(stats.ytd_ride_totals)}

    #### All ride totals

{get_stat_values(stats.all_ride_totals)}
    """)
Beispiel #36
0
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
    """Authenticate to the Strava API."""
    from stravalib.client import Client

    hass.http.register_view(StravaAuthCallbackView())

    client_id = config.get(CONF_CLIENT_ID)
    client_secret = config.get(CONF_CLIENT_SECRET)

    client = Client()

    config_path = hass.config.path(STRAVA_CONFIG_PATH)

    @asyncio.coroutine
    def _read_config():
        if not os.path.isfile(config_path):
            return None
        with open(config_path, 'r') as auth_file:
            config = json.load(auth_file)
            if config['client_id'] == client_id:
                return config['access_token']

    @asyncio.coroutine
    def _write_config():
        with open(config_path, 'w') as auth_file:
            json.dump(
                {
                    'client_id': client_id,
                    'access_token': client.access_token,
                }, auth_file)

    @asyncio.coroutine
    def _add_device():
        strava = StravaSensor(hass, client)
        yield from strava.async_update()
        return async_add_devices([strava])

    access_token = yield from _read_config()
    if access_token is not None:
        client.access_token = access_token
        yield from _add_device()
    else:
        callback_url = '{}{}'.format(hass.config.api.base_url,
                                     StravaAuthCallbackView.url)
        authorize_url = client.authorization_url(client_id=client_id,
                                                 redirect_uri=callback_url)

        configurator = hass.components.configurator
        request_id = configurator.async_request_config(
            'Strava',
            description='Authorization required for Strava account.',
            link_name='Authorize Home Assistant',
            link_url=authorize_url,
            entity_picture='/local/images/logo_strava.png')

    @asyncio.coroutine
    def initialize_callback(code):
        """Handle OAuth callback from Strava authorization flow."""
        client.access_token = client.exchange_code_for_token(
            client_id=client_id, client_secret=client_secret, code=code)
        yield from _write_config()
        yield from _add_device()
        configurator.async_request_done(request_id)

    hass.data[DATA_CALLBACK] = initialize_callback
    return True
        client_id = cfg.get("StravaClient", "ClientId")
        client_secret = cfg.get("StravaClient", "ClientSecret")
        port = int(cfg.get("Application", "Port"))
        
        # setup webserver for authentication redirect
        httpd = http.server.HTTPServer(('127.0.0.1', port), AuthHandler)

        # The url to authorize from
        authorize_url = client.authorization_url(client_id=client_id, redirect_uri='http://localhost:{port}/authorized'.format(port=port), scope='view_private,write')
        # Open the url in your browser
        webbrowser.open(authorize_url, new=0, autoraise=True)

        # wait until you click the authorize link in the browser
        httpd.handle_request()
        code = httpd.code

        # Get the token
        token = client.exchange_code_for_token(client_id=client_id, client_secret=client_secret, code=code)

        # Now store that access token in the config
        cfg.set("UserAcct", "Token", token)
        with open("stravamng.cfg", "w") as cfg_file:
            cfg.write(cfg_file)

    client.access_token = token

    # do stuff
    athlete = client.get_athlete()
    print("For {id}, I now have an access token {token}".format(id=athlete.id, token=token))

Beispiel #38
0
## import libraries
from stravalib.client import Client
from cartodb import CartoDBAPIKey, CartoDBException
import numpy as np
import datetime
import time
from polyline.codec import PolylineCodec
from geojson import Feature, LineString

## Strava connection
client = Client()
client.access_token = 'd47099a29b2f3539e1c21af6d820e33a109a079e'

## CartoDB connection
API_KEY ='cad54ea0c580a0c554b9e9562157e7c9bd9f37b0'
cartodb_domain = 'geodarcy'
cl = CartoDBAPIKey(API_KEY, cartodb_domain)

## remove duplicate rows
cl.sql('DELETE FROM wbstrava WHERE cartodb_id IN (SELECT cartodb_id FROM (SELECT cartodb_id, ROW_NUMBER() OVER (partition BY segment_id ORDER BY cartodb_id) AS rnum FROM wbstrava) t WHERE t.rnum > 1);')

## find segments with no geometry
queryResult = cl.sql('select segment_id from wbstrava where the_geom is null')
currentSegments = [x['segment_id'] for x in queryResult['rows']]
for id in currentSegments:
  try:
    segmentGeojson = PolylineCodec().decode(client.get_segment(id).map.polyline)
    flippedGeojson = [[x[1], x[0]] for x in segmentGeojson]
    inputGeojson = '{"coordinates": ' + str(flippedGeojson) + ', "type": "LineString", "crs":{"type":"name","properties":{"name":"EPSG:4326"}}}'
    cl.sql('UPDATE wbstrava SET the_geom = ST_GeomFromGeoJSON(\'' + inputGeojson + '\') WHERE segment_id=' + str(id))
  except Exception as e:
Beispiel #39
0
from stravalib.client import Client
from stravalib import unithelper
import pandas as pd
import cPickle as pickle
from os.path import join, exists
from os import makedirs, getcwd
from datetime import datetime

client = Client()
client.access_token = "8ad469fc76e136a0d5a40f0ad10ea0e8282ef6e5"

me = client.get_athlete()

print me.email

def to_miles(dist):
    return float(unithelper.miles(dist))

def to_mph(mps):
    return float(unithelper.mph(act.average_speed))

def echo(v):
    return v

#TODO Convert moving time properly, want in a timedelta really

#TODO To do proper clustering, need columns as lat then long, and rows as runs
# but how to deal with runs of different lengths?
# I think all streams have the same number of points?  
# Which isn't going to be great, but givem that different routes, even if stretched out/shrunk, have different shapes
# then distinct ones should stay that way, so might be ok
Beispiel #40
0
#!/bin/python
import ConfigParser
import json
import io
from stravalib.client import Client

config = ConfigParser.ConfigParser()
client = Client()

config.read('config.ini')
client.access_token = config.get("access","access_token")
app_friends = config.get("app","friends")
redis_host = config.get("access", "redis_host")

# get my profile
#curr_athlete = client.get_athlete()
# inspect the athlete object
#print(type(curr_athlete))
#print(dir(curr_athlete))

# get another athlete profile
#curr_athlete = client.get_athlete(4658463)
#print(curr_athlete)

# get a segment
#curr_segment = client.get_segment(11493495)
#print(type(curr_segment))
#print(dir(curr_segment))
#print(curr_segment)
# get a segment leaderboard
#curr_segmentldr = client.get_segment_leaderboard(11493495)
Beispiel #41
0
from stravalib.client import Client
from stravalib.attributes import LatLon
import units

LOGIN = file("access_token").read().strip()
BIKES = {
	"Madone": "b1258359",
	"Secteur": "b1708741",
	"Random": "b1209450",
}
# Strava rounds to two decimals which isn't terribly precise but at least easy
# for comparisons.
WORK = LatLon(lat=51.49, lon=-0.15)

client = Client()
client.access_token = LOGIN

def build_updates(act):
	ret = {}

	if act.type != act.RIDE:
		if (act.start_latlng == WORK and
		    act.start_date_local.weekday() <= 4):
			ret["name"] = "Walking commute"
			ret["commute"] = True
			ret["activity_type"] = act.WALK

		# I don't record walks that often anyway.
		return
	
	segments = [se.segment.id for se in act.segment_efforts]
Beispiel #42
0
def scrape_strava():
    # Scraper config:

    # Enter your Strava API info here.
    # You can find this at https://www.strava.com/settings/api
    CLIENT_ID = 31337
    CLIENT_SECRET = 'BA5ED60D'
    # Strava auth callbacks will hit this host and port. Change the port if you
    # need to avoid port conflicts with other servers.
    CALLBACK_PORT = 36724
    # Where to store your Strava activity info and the Strava auth token.
    ACTIVITIES_TABLE = 'strava_activities'
    TOKEN_TABLE = 'strava_token'

    # Scraper body begins here.

    import config

    import webbrowser
    import logging
    from cgi import parse_qs
    from wsgiref.simple_server import make_server

    import dataset
    from stravalib.client import Client
    from stravalib import unithelper
    from units import unit

    # And here's the rest of the scraper.

    def get_new_token():
        authorize_url = client.authorization_url(
            client_id=CLIENT_ID,
            redirect_uri=('%s:%s' % (config.SERVER_HOST, CALLBACK_PORT))
        )
        webbrowser.open(authorize_url)
        print('Click here to authorize me to access your Strava activities: %s'
              % authorize_url)
        make_server('localhost', CALLBACK_PORT, auth_listener).handle_request()

    def auth_listener(environ, start_response):
        start_response("200 OK", [('Content-Type', 'text/plain')])
        parameters = parse_qs(environ.get('QUERY_STRING', ''))
        code_received(parameters['code'][0])
        return ['Got your authorization from Strava! '
                'You can close this window now.'
                .encode('utf-8')]

    def code_received(code):
        token = client.exchange_code_for_token(client_id=CLIENT_ID,
                                               client_secret=CLIENT_SECRET,
                                               code=code)
        tokens.insert({'token': token})
        print('Got your authorization from Strava. Thanks!')
        query_strava()

    def avg_speed_to_mins(avg_speed):
        sec_per_meter = unit('s') / unit('m')
        min_per_mile = unit('min') / unit('mi')
        pace = min_per_mile(sec_per_meter(avg_speed.get_num() ** -1))
        return pace.get_num()

    def query_strava():
        print('Querying Strava...')

        table = db[ACTIVITIES_TABLE]
        activity_summaries = [a for a in client.get_activities()]
        num_added = 0

        for a_summary in activity_summaries:
            if table.find_one(strava_id=a_summary.id):
                break
            a = client.get_activity(a_summary.id)
            activity_data = {
                'strava_id': a.id,
                'name': a.name,
                'type': a.type,
                'start_date': a.start_date.isoformat(),
                'distance_mi': float(unithelper.miles(a.distance)),
                'elapsed_sec': a.elapsed_time.total_seconds(),
                'pace_mins_per_mi': avg_speed_to_mins(a.average_speed),
                'polyline': a.map.summary_polyline
            }
            print('Added %s: %s' % (a.type, a.name))
            num_added += 1
            table.insert(activity_data)

        print('Done! %s activities added.' % num_added)

    # Stravalib throws lots of warnings for schema issues on Strava's end.
    # These warnings don't impact us so let's ignore them.
    logger_names = [k for k in logging.Logger.manager.loggerDict.keys() if
                    k.startswith('stravalib')]
    for logger_name in logger_names:
        logging.getLogger(logger_name).setLevel(logging.ERROR)

    client = Client()

    db = dataset.connect(config.DB_URI)
    tokens = db[TOKEN_TABLE]
    token_obj = tokens.find_one()

    if token_obj:
        client.access_token = token_obj['token']
        query_strava()
    else:
        get_new_token()
Beispiel #43
0
# id and port info
client_id = open('client.id')
client_secret = os.environ['STRAVA_CLIENT_SECRET']
access_token = os.environ['STRAVA_ACCESS_TOKEN']
port = 5000
url = 'http://localhost:%d/authorized' % port

if __name__ == '__main__':
    # initialize stravalib client
    client = Client()
    authorize_url = client.authorization_url(client_id=client_id,
                                             redirect_uri=url)

    # get athlete
    client.access_token = access_token
    athlete = get_athlete(client)

    # get activities for athlete
    activities = get_activities(client, limit=10)

    # initiate mongo database, connect, make collection
    db_client = MongoClient(
        'localhost', 27017)  # Establish connection to persistent storage
    db = db_client.Strava  # Access/Initiate Database
    coll_name = '{}_{}_user'.format(athlete.firstname, athlete.lastname)
    collection = db[coll_name]

    # write activities to mongodb
    types = ['name', 'time', 'latlng', 'altitude', 'distance']
    write_activities_to_mongo(activities, types, collection)
Beispiel #44
0
"""
Created on Sat Aug  1 11:08:17 2015

@author: fraidylevilev
"""

# My access token: c2f218e5c3a9af9a3e0389d3e539e197f19f650e
# My athlete id: 9753705

from stravalib.client import Client
# import the strava library

client = Client()

# Input your access token below!
client.access_token = 'c2f218e5c3a9af9a3e0389d3e539e197f19f650e'
#this is me
athlete = client.get_athlete(9753705)
print("For {id}, I now have an access token {token}".format(id = athlete, token = client.access_token))

import requests
import pandas as pd
import numpy as np
import time
import sys

#calling strava api
base_url = 'https://www.strava.com/api'
#using api to get efforts on a segment
segment_url = base_url + '/v3/segments/{0}/all_efforts'
extra_headers = {'Authorization' : 'Bearer {0}'.format(access_token)}