Exemplo n.º 1
0
    def resolve_query(self, query_str):
        """Parse query and get corresponding stats."""
        params = self.parse_query(query_str)

        # Get activities.
        activities = Strava.get_activities(self.auth, params)

        if len(activities) == 0:
            logging.warning(
                "There are no activites that matched your query: %s\n",
                query_str)
            return

        print()
        aggregate = params.get('total')
        if aggregate:
            print('Total stats:')
            for agg in aggregate:
                print(f"{agg.capitalize()}: ", end='')
                if agg == 'count':
                    print(f"{len(activities)}")
                elif agg == 'distance':
                    print(
                        f"{Strava.format_distance(Strava.get_total_distance(activities))}"
                    )
                elif agg == 'time':
                    print(
                        f"{Strava.format_time(Strava.get_total_time(activities))}"
                    )
                else:  # Total elevation.
                    print(
                        f"{round(Strava.get_total_elevation(activities), 2)}m")

            if params.get('stats'):
                for dist in Stats.milestones[params['type']]:
                    params['distance'] = dist * 1000
                    activities = Strava.get_activities(self.auth, params)
                    if len(activities
                           ):  # Print the count only if there are activities.
                        print(f"{dist}k: {len(activities)}")
            print()
        else:
            # Print activity information.
            for act in activities:
                Strava.print_activity(act)
                print()
Exemplo n.º 2
0
    def get(self):
        strava = Strava()
        strava.access_token(self.get_current_token())

        athlete = strava.get_athlete()
        if athlete['profile'].startswith("avatar"):
            athlete['profile'] = "/static/images/commuter_avatar.png"

        year = datetime.date.today().year
        month = datetime.date.today().month

        mongo = MongoClient('mongo')
        user_settings = mongo.strava.settings.find_one({"_id": self.get_current_user()})
        
        context = dict()        
        context['year'] = year
        context['month'] = calendar.month_name[month]
        context['days_left'] = utils.days_left()
        context['currencies'] = sorted(list(pycountry.currencies), key=lambda currency: currency.name)

        self.render("index.html", context=context, athlete=athlete, settings=user_settings)
Exemplo n.º 3
0
 def get_Mayor_of_Mountain(self,effort_offset = 0) :
     s = Strava()
     s_util = SegmentMayor(self.segment_id)
     # need to call this with the save offset if available
     efforts_data = s.get_segment_efforts(self.segment_id,offset = effort_offset)
     #print efforts_data
     #  go through and iterrate over the segment efforts
     # Strava returns 50 ride efforts at a time
     while self.process_efforts_segment_frequency(efforts_data):
         # call get efforts repeatedly
         effort_offset += 50
         efforts_data = {} # clear it
         #print "offset is now %d" % effort_offset
         efforts_data = s.get_segment_efforts(self.segment_id,offset = effort_offset)
     # if this was the last bunch, make sure to add to the offset that last bunch of efforts
     if len(efforts_data['efforts']) < 50 :
         effort_offset += len(efforts_data['efforts'])
     # save the offset so it can be used in future if needed
     self.last_segment_effort_offset = effort_offset
 
     return s_util.get_segment_top_mayors()
Exemplo n.º 4
0
    def get_Mayor_of_Mountain(self, effort_offset=0):
        s = Strava()
        s_util = SegmentMayor(self.segment_id)
        # need to call this with the save offset if available
        efforts_data = s.get_segment_efforts(self.segment_id,
                                             offset=effort_offset)
        #print efforts_data
        #  go through and iterrate over the segment efforts
        # Strava returns 50 ride efforts at a time
        while self.process_efforts_segment_frequency(efforts_data):
            # call get efforts repeatedly
            effort_offset += 50
            efforts_data = {}  # clear it
            #print "offset is now %d" % effort_offset
            efforts_data = s.get_segment_efforts(self.segment_id,
                                                 offset=effort_offset)
        # if this was the last bunch, make sure to add to the offset that last bunch of efforts
        if len(efforts_data['efforts']) < 50:
            effort_offset += len(efforts_data['efforts'])
        # save the offset so it can be used in future if needed
        self.last_segment_effort_offset = effort_offset

        return s_util.get_segment_top_mayors()
Exemplo n.º 5
0
    def get(self):
        strava = Strava()
        mongo = MongoClient('mongo')
        
        strava_client_secret = os.environ.get('STRAVA_CLIENT_SECRET')
        strava_client_id= os.environ.get('STRAVA_CLIENT_ID')
        
        code = self.get_argument("code")
        access_token, athlete = strava.exchange_token(client_id=strava_client_id, client_secret=strava_client_secret, code=code)
        
        user = mongo.strava.settings.find_one({"_id": athlete['email']})
        if user:
            mongo.strava.settings.update({"_id": athlete['email']}, {"$set": { "access_token": access_token} })
        else:
            mongo.strava.settings.save({
                "_id": athlete['email'],
                "access_token": access_token,
                "settings_ok": False,
                "cost_per_commute": 0,
                "currency": "USD"
            })

        self.set_secure_cookie("user", athlete['email'])
        self.redirect("/")
Exemplo n.º 6
0
    def test_Strava_get_efforts_whenCalledWithMockedAPI_returnsEffortsFromTestData(self):
        with mock.patch('webrequest.getjsonfromurl') as mock_geturl:
            self.setupTestData()
            mock_geturl.return_value = self.efforts

            starttime = datetime(year=2016, month=4, day=3, hour=1, minute=2, second=3)
            endtime = datetime(year=2016, month=4, day=10, hour=18, minute=0, second=0)

            efforts = Strava().get_efforts('123456', starttime, endtime)

            args = mock_geturl.call_args[0]
            params = args[1]

            self.assertEqual(params['start_date_local'], '2016-04-03T01:02:03')
            self.assertEqual(params['end_date_local'], '2016-04-10T18:00:00')
            self.assertIn('/123456/', args[0])
Exemplo n.º 7
0
    def get(self):
        if not self.get_current_user():
            raise tornado.web.HTTPError(401, "Access denied")
    
        year = datetime.date.today().year
        month = datetime.date.today().month
        after = datetime.datetime(year, month, 01, 0, 0).strftime("%s")
        
        mongo = MongoClient("mongo")
        user_settings = mongo.strava.settings.find_one({"_id": self.get_current_user()})

        strava = Strava()
        strava.access_token(self.get_current_token())

        athlete = strava.get_athlete()
        activities = strava.get_activities(per_page=200, after=after)

        results = dict()
        results["count"] = 0
        results["count_total"] = len(activities)
        results["kudos"] = 0
        results["achievement"] = 0
        for r in activities:
            if r['type'] == 'Ride' and r['commute']:
                results["count"] = results.get("count", 0) + 1
                results["distance"] = results.get("distance", 0) + r["distance"]
                results["kudos"] = results.get("kudos", 0) + r['kudos_count']
                results["achievement"] = results.get("achievement", 0) + r['achievement_count']
                results["moving_time"] = results.get("moving_time", 0) + r['moving_time']
                results["elevation"] = results.get("elevation", 0) + r['total_elevation_gain']
                
        results['money_saved'] = "%s %.2f" % (user_settings.get("currency", "USD"), (results.get("count", 0) * float(user_settings["cost_per_commute"])))
        results["distance"] = "%.2f" % round(utils.distance(athlete['measurement_preference'], results.get("distance", 0)) / 1000, 2)
        results["elevation"] = utils.elevation(athlete['measurement_preference'], results.get("elevation", 0))
        results["moving_time"] = utils.moving_time(results.get("moving_time", 0))
        results["commutes_percentage"] = utils.commutes_percentage(results["count"], results["count_total"])
        
        self.write(json.dumps(results))
Exemplo n.º 8
0
 def get(self):
     strava_client_id= os.environ.get('STRAVA_CLIENT_ID')
     strava = Strava()
     authorize_url = strava.authorization_url(client_id=strava_client_id, redirect_uri='https://www.cashmyrides.com/done')
     self.render("index.html", authorize_url=authorize_url)
Exemplo n.º 9
0
    def compile_efforts(self, year=None, week_number=None):
        log.info('Method=compile_efforts Year=%s WeekNumber=%s' %
                 (year, week_number))
        leagues = {}

        starttime = datetime.combine(
            date.today() - timedelta(date.today().weekday()),
            datetime.min.time())
        key_name = self.get_sotw_key_name()

        if year != None and week_number != None:
            key_name = 'sotw_%s_%s' % (year, week_number)
            d = "%s-W%s" % (year, week_number)
            r = datetime.strptime(d + '-0', "%Y-W%W-%w")
            starttime = datetime.combine(r - timedelta(r.weekday()),
                                         datetime.min.time())

        endtime = starttime + timedelta(days=6, hours=20)
        log.info('Method=compile_efforts ResultKey=%s' % key_name)

        log.info(
            'Method=compile_efforts Message="Getting segment data from redis"')

        segment = redisclient.get('%s_segment' % key_name)
        log.info('Method=compile_efforts Segment=%s' % segment)

        neutral_zones = redisclient.smembers('%s_neutral_zones' % key_name)
        log.info('Method=compile_efforts NeutralZones=%s' % neutral_zones)

        log.info(
            'Method=compile_efforts Message="Getting segment data from Strava" Segment=%s StartTime=%s EndTime=%s'
            % (segment, starttime, endtime))
        try:
            segment_efforts = Strava().get_efforts(segment, starttime, endtime)
            log.info(
                'Method=compile_efforts Message="Data from Strava" ResultCount=%s'
                % (len(segment_efforts)))
        except Exception as e:
            log.exception(
                'Method=compile_efforts Message="Strava call failed"')
            raise (e)

        for segment_effort in segment_efforts:
            segment_effort['neutralised'] = {}

        for neutral_zone in neutral_zones:
            log.info(
                'Method=compile_efforts Message="Getting segment data from Strava" Segment=%s StartTime=%s EndTime=%s'
                % (neutral_zone, starttime, endtime))
            try:
                neutral_zone_efforts = Strava().get_efforts(
                    neutral_zone, starttime, endtime)
                log.info(
                    'Method=compile_efforts Message="Data from Strava" ResultCount=%s'
                    % (len(neutral_zone_efforts)))
            except Exception as e:
                log.exception(
                    'Method=compile_efforts Message="Strava call failed"')
                raise (e)

            # neutral_zone_efforts = Strava().get_efforts(neutral_zone, starttime, endtime)

            for neutral_zone_effort in neutral_zone_efforts:
                for segment_effort in segment_efforts:
                    if neutral_zone_effort['activity']['id'] == segment_effort[
                            'activity']['id']:
                        segment_effort['neutralised'][
                            neutral_zone] = neutral_zone_effort['elapsed_time']

        divisions = redisclient.smembers('divisions')

        for divisionId in divisions:
            division = divisionId
            # division_name = redisclient.hgetasstring(division, 'name')
            leagues[division] = self.compile_league(division, segment_efforts)

        return leagues
Exemplo n.º 10
0
env = os.environ

# The Strava API secrets must be provided by setting the following envorinment
# variables:
# - CLIENT_ID
# - CLIENT_SECRET
# - REFRESH_TOKEN
CLIENT_ID = env['CLIENT_ID']
CLIENT_SECRET = env['CLIENT_SECRET']
REFRESH_TOKEN = env['REFRESH_TOKEN']

# The ID of the Strava Club we want to provide the badge for is provided by
# setting the following environment variable:
# - STRAVA_CLUB_ID
STRAVA_CLUB_ID = env['STRAVA_CLUB_ID']

app = Flask(__name__)
api = Api(app)

# Create the Strava instance which will handle fetching the club data from Strava
strava = Strava(CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN, STRAVA_CLUB_ID)

# Connect the /strava REST endpoint to the Strava instance
api.add_resource(StravaShield,
                 "/strava",
                 resource_class_kwargs={'strava': strava})

if __name__ == "__main__":
    app.run()
Exemplo n.º 11
0
 def test_Strava_get_access_token_whenCalled_returnsTestDataToken(self):
     self.setupTestData()
     token = Strava().get_access_token()
     self.assertEqual(token, self.test_data['api_token'])
Exemplo n.º 12
0
 def get_from_strava(self):
     self.segment_object = Strava().get_segment(self.segment_id)
Exemplo n.º 13
0
 def get_from_strava(self):
     self.athlete_object = Strava().get_athlete(self.athlete_id)
Exemplo n.º 14
0
jognote_id = options.jognote_id
jognote_password = options.jognote_password
start_date = options.start_date
end_date = options.end_date
strava_email = options.strava_email
strava_password = options.strava_password
log_level = options.log_level

# set log settings
init_log(log_level)

# get jognote data
jog = Jognote(jognote_id, jognote_password, start_date, end_date, log_level)
history = jog.export()
logging.debug('%d data export from JogNote' % len(history))

# make strava object
strava = Strava(strava_email, strava_password, log_level)

for workout in history:
    name = get_type_name(workout.name)
    start_date = workout.date.strftime('%m/%d/%Y')
    title = '%s%s' % (TITLE_PREFIX, start_date)
    elapsed_time = ':'.join(list(workout.time))
    distance = workout.distance

    # post data
    strava.add_activity(name, title, COUNTRY, LOCATION,
                        start_date, START_TIME, elapsed_time,
                        distance)