Exemple #1
0
    def load_strava_tracks(self, strava_config: str) -> typing.List[Track]:
        tracks = []
        tracks_names = []
        if self.cache_dir:
            self.strava_cache_file = os.path.join(self.cache_dir, strava_config)
            if os.path.isfile(self.strava_cache_file):
                with open(self.strava_cache_file) as f:
                    strava_cache_data = json.load(f)
                    tracks = [self._strava_cache_to_track(i) for i in strava_cache_data]
                    tracks_names = [track.file_names[0] for track in tracks]

        with open(strava_config) as f:
            strava_data = json.load(f)
        filter_type = strava_data.pop("activity_type", None)
        client = Client()
        response = client.refresh_access_token(**strava_data)
        client.access_token = response["access_token"]
        filter_dict = {"before": datetime.datetime.utcnow()}
        if tracks:
            max_time = max(track.start_time() for track in tracks)
            filter_dict = {"after": max_time - datetime.timedelta(days=2)}
        for activity in client.get_activities(**filter_dict):
            # tricky to pass the timezone
            if str(activity.id) in tracks_names:
                continue
            if filter_type and activity.type not in (
                [filter_type] if isinstance(filter_type, str) else filter_type
            ):  # pylint: disable=superfluous-parens
                continue
            t = Track()
            t.load_strava(activity)
            tracks.append(t)
        self._store_strava_tracks_to_cache(tracks)
        return self._filter_and_merge_tracks(tracks)
Exemple #2
0
def load_gpx_file(file_name: str,
                  timezone_adjuster: TimezoneAdjuster) -> Track:
    """Load an individual GPX file as a track by using Track.load_gpx()"""
    log.info("Loading track %s...", os.path.basename(file_name))
    t = Track()
    t.load_gpx(file_name, timezone_adjuster)
    return t
Exemple #3
0
    def load_strava_tracks(self, strava_config: str) -> typing.List[Track]:
        tracks = []
        tracks_names = []
        if self.cache_dir:
            self.strava_cache_file = os.path.join(self.cache_dir,
                                                  strava_config)
            if os.path.isfile(self.strava_cache_file):
                with open(self.strava_cache_file) as f:
                    strava_cache_data = json.load(f)
                    tracks = [
                        self._strava_cache_to_track(i)
                        for i in strava_cache_data
                    ]
                    tracks_names = [track.file_names[0] for track in tracks]

        with open(strava_config) as f:
            strava_data = json.load(f)
        client = Client()
        response = client.refresh_access_token(**strava_data)
        client.access_token = response["access_token"]
        fliter_dict = {"before": datetime.datetime.utcnow()}
        if tracks:
            max_time = max(track.start_time for track in tracks)
            if max_time:
                fliter_dict = {"after": max_time - datetime.timedelta(days=2)}
        for activate in client.get_activities(**fliter_dict):
            # tricky to pass the timezone
            if str(activate.id) in tracks_names:
                continue
            t = Track()
            t.load_strava(activate)
            tracks.append(t)
        self._store_strava_tracks_to_cache(tracks)
        return self._filter_and_merge_tracks(tracks)
def load_cached_track_file(cache_file_name: str, file_name: str) -> Track:
    """Load an individual track from cache files"""
    try:
        t = Track()
        t.load_cache(cache_file_name)
        t.file_names = [os.path.basename(file_name)]
        log.info(f"Loaded track {file_name} from cache file {cache_file_name}")
        return t
    except Exception as e:
        raise TrackLoadError("Failed to load track from cache.") from e
Exemple #5
0
 def _make_strava_cache_dict(track: Track) -> typing.Dict[str, Any]:
     lines_data = []
     for line in track.polylines:
         lines_data.append([{"lat": latlng.lat().degrees, "lng": latlng.lng().degrees} for latlng in line])
     return {
         "name": track.file_names[0],  # strava id
         "start": track.start_time().strftime("%Y-%m-%d %H:%M:%S"),
         "end": track.end_time().strftime("%Y-%m-%d %H:%M:%S"),
         "length": track.length_meters,
         "segments": lines_data,
     }
 def _draw_track(self, dr: svgwrite.Drawing, tr: Track, size: XY,
                 offset: XY) -> None:
     color = self.color(self.poster.length_range, tr.length(), tr.special)
     for line in utils.project(tr.bbox(), size, offset, tr.polylines):
         dr.add(
             dr.polyline(
                 points=line,
                 stroke=color,
                 fill="none",
                 stroke_width=0.5,
                 stroke_linejoin="round",
                 stroke_linecap="round",
             ))
Exemple #7
0
 def _strava_cache_to_track(data: typing.Dict[str, Any]) -> "Track":
     t = Track()
     t.file_names = [data["name"]]
     t.set_start_time(datetime.datetime.strptime(data["start"], "%Y-%m-%d %H:%M:%S"))
     t.set_end_time(datetime.datetime.strptime(data["end"], "%Y-%m-%d %H:%M:%S"))
     t.length_meters = float(data["length"])
     t.polylines = []
     for data_line in data["segments"]:
         t.polylines.append([s2sphere.LatLng.from_degrees(float(d["lat"]), float(d["lng"])) for d in data_line])
     return t
    def _draw_track(self, dr: svgwrite.Drawing, g: svgwrite.container.Group, tr: Track, size: XY, offset: XY) -> None:
        color = self.color(self.poster.length_range, tr.length(), tr.special)
        str_length = utils.format_float(self.poster.m2u(tr.length()))

        date_title = str(tr.start_time.date()) if tr.start_time else "Unknown Date"
        for line in utils.project(tr.bbox(), size, offset, tr.polylines):
            polyline = dr.polyline(
                points=line,
                stroke=color,
                fill="none",
                stroke_width=0.5,
                stroke_linejoin="round",
                stroke_linecap="round",
            )
            polyline.set_desc(title=f"{date_title} {str_length} {self.poster.u()}")
            g.add(polyline)
def load_gpx_file(file_name: str) -> Track:
    """Load an individual GPX file as a track by using Track.load_gpx()"""
    log.info(f"Loading track {os.path.basename(file_name)}...")
    t = Track()
    t.load_gpx(file_name)
    return t