Beispiel #1
0
def print_info():

    dir = config.get_download_dir()

    if dir is None:
        print("No load directory configured. To set,  use 'heroscript config --load_directory PATH'.")
        return

    if not path.exists(dir):
        exit_on_error("Not a valid directory: '{}'. "
                      "To change,  use 'heroscript config --load_directory PATH'.".format(dir))

    types = ('*.TCX', '*.tcx')
    files_grabbed = []

    for files in types:
        files_grabbed.extend(glob.glob(path.join(dir, files)))

    files_grabbed.sort()

    if len(files_grabbed) == 0:
        print("No track file found in {}".format(dir))
        return

    load = read_load()

    print(f"Found {len(files_grabbed)} track file(s) in '{dir}':")
    for file in files_grabbed:
        if load and file == load.file_name:
            status = "*"
        else:
            status = " "

        print(f"  {status} {path.basename(file)}")
Beispiel #2
0
    def __init__(self):
        self._load = read_load()

        self._points = self.get_track_points()
        utility.log("Map imported track points", len(self._points))
        self._title = utility.get_human_date(self._load.started_at, "%y-%m-%d %H:%M")

        self._max_lon = None
        self._min_lon = None
        self._max_lat = None
        self._min_lat = None
Beispiel #3
0
def process_set(args):
    log("process_set", "start")

    load = read_load()

    if args.activity_type:
        log("args.activity_type", args.training_type)
        load.set_activity_type(args.activity_type.strip().lower())

    if args.velohero_workout_id:
        log("args.velohero_workout_id", args.velohero_workout_id)
        if args.velohero_workout_id.strip() == '0':
            load.set_velohero_workout_id(None)
        else:
            load.set_velohero_workout_id(args.velohero_workout_id.strip())

    if args.training_type is not None:
        log("args.training_type", args.training_type)
        _set_training_type(load, find_training_type_by_name(args.training_type.strip().lower()))

    if args.route_name is not None:
        log("args.route_name", args.route_name)
        load.set_route_name(args.route_name.strip().lower())

    if args.equipment_names is not None:
        log("args.equipment_names", args.equipment_names)

        equipment_names = []
        if len(args.equipment_names.strip()) == 0:
            equipment_names = []

        elif args.equipment_names.find(",") > 0:
            for equipment in args.equipment_names.split(','):
                equipment_names.append(find_equipment_by_name(equipment.strip())['name'])
        else:
            equipment_names.append(find_equipment_by_name([args.equipment_names.strip().lower()][0])['name'])

        log("equipment_names", equipment_names)
        load.set_equipment_names(equipment_names)

    if args.title is not None:
        log("args.title", args.title)
        load.set_title(args.title.strip())

    if args.comment is not None:
        log("args.comment", args.comment)
        load.set_comment(args.comment.strip())

    save_load(load)

    log("process_set", "end")
Beispiel #4
0
def strava_do_update():
    """
    Precondition: In Load there is the STRAVA activity ID
    """
    print("Updating STRAVA...", end='', flush=True)

    messages = []

    try:

        client = _setup_client()
        load = read_load()
        type = masterdata.get_type(load.training_type)['name']

        if type == masterdata.get_competition_type()['name']:
            messages.append((
                "[WARN] Can't set the STRAVA workout type to 'competition', please do this manually "
                "(missing this feature in stravalib API)"))

        if load.strava_descriptions is None:
            description = None
        else:
            description = "\n".join(load.strava_descriptions)

        log("description", description)

        if len(load.equipment_names) == 9:

            messages.append(
                "[WARN] No equipment in stage, equipment on Strava will not be be updated"
            )

            client.update_activity(
                activity_id=load.strava_activity_id,
                name=load.strava_activity_name,
                commute=is_commute_training_type(type),
                trainer=is_indoor_training_type(type),
                description=description,
            )

        else:
            equipment = masterdata.find_first_strava_equipment(
                load.equipment_names)

            if equipment is None:
                messages.append(
                    "No equipment with Strava ID found! Are the master data up-to-date "
                    "(use 'masterdata --refresh' to update)? ")
                gear_id = False
            else:
                gear_id = equipment['strava_id']
                log("Take equipment ID",
                    f"{equipment['strava_id']} '{equipment['name']}'")

            # There can ve prints inside, so print afterwards
            client.update_activity(
                activity_id=load.strava_activity_id,
                name=load.strava_activity_name,
                commute=is_commute_training_type(type),
                trainer=is_indoor_training_type(type),
                gear_id=gear_id,
                description=description,
            )

        for message in messages:
            print(message)

        print(f" Done (Activity ID {load.strava_activity_id} updated)")

    except stravalib.exc.AccessUnauthorized as e:
        log("Exception occurred", e)
        exit_on_error(
            f"STRAVA access failed: Unauthorized. Maybe you have removed the app permission in your STRAVA profile!? "
            "Use 'heroscript config --strava_reset' to remove all login data.py. Then try the command again and you "
            "will be askt for app authorization.")
Beispiel #5
0
def load_strava_activity():
    """
    Precondition: Load is staged.
    """
    # log("load_strava_activity", "start")

    try:

        client = _setup_client()
        load = read_load()

        log("Searching for an activity at", load.started_at)

        # client.get_activity(1).tr

        for a in client.get_activities(after=load.started_at_datetime +
                                       datetime.timedelta(seconds=-1),
                                       before=load.started_at_datetime +
                                       datetime.timedelta(seconds=1)):
            log(
                f"Found STRAVA activity: started at={a.start_date}, "
                f"name='{a.name}' ID",
                f"'{a.id}', commute={a.commute}, trainer={a.trainer}, "
                f"workout type={a.workout_type}")

            if len(a.name.split(": ", 1)) == 2:
                title = a.name.split(": ", 1)[1]
            else:
                title = a.name

            if a.commute:
                type = masterdata.get_commute_type()

            elif a.trainer:
                type = masterdata.get_indoor_type()

            # Type decorates the name as prefix
            elif re.compile(".*: .*").match(a.name):
                type = masterdata.find_type_by_name(a.name.split(": ", 1)[0])

            # Run or bike competition
            elif a.workout_type == strava_workout_run_competition_type or \
                    a.workout_type == strava_workout_bicycle_competition_type:
                type = masterdata.get_competition_type()

            # Strava doesn't have a type
            else:
                type = masterdata.get_default_type()

            log("Detected STRAVA activity type", type['name'])

            equipment_name = None
            if a.gear_id:
                log("gear_id", a.gear_id)
                equipment = masterdata.find_equipment_by_strava_id(a.gear_id)
                if equipment is None:
                    print(
                        f"[WARN] STRAVA equipment with ID {a.gear_id} not found ! To update master data use "
                        f"'masterdata --refresh'")
                else:
                    equipment_name = equipment['name']
                    if equipment['training_type'] is not None:
                        type = masterdata.find_type_by_name(
                            equipment['training_type'])
            else:
                print("[WARN] STRAVA activity hasn't got an equipment")

            myconfig = config.get_strava_description_items()

            descriptions = []

            log("a.distance", f"{a.distance.num} {a.distance.unit}")
            log("a.total_elevation_gain",
                f"{a.total_elevation_gain.num} {a.total_elevation_gain.unit}")
            elevation = a.total_elevation_gain.num / (a.distance.num / 1000)
            descriptions.append(
                "\u25B2 {elevation:.1f} {unit1}/k{unit2}".format(
                    elevation=elevation,
                    unit1=a.total_elevation_gain.unit,
                    unit2=a.distance.unit))

            for item in myconfig:
                log("description rule", item)
                if item['condition_field'] == 'strava_name':
                    if item['condition_value'].lower().strip() == title.lower(
                    ).strip():
                        descriptions.append(item['text'])

                if item['condition_field'] == 'training_type':
                    if item['condition_value'].lower().strip(
                    ) == type['name'].lower():
                        descriptions.append(item['text'])

            descriptions.append(
                "Powered by https://github.com/chs8691/heroscript")

            log("descriptions", descriptions)

            load.add_strava(
                a.id, a.name, type['name'], title, equipment_name,
                descriptions,
                masterdata.find_activity_type_by_equipment(equipment_name))

            save_load(load)
            print(f"Found activity on Strava")
            return

        print("[WARN] Strava activity not found !")

    except stravalib.exc.AccessUnauthorized as e:
        log("Exception occurred", e)
        exit_on_error(
            f"STRAVA access failed: Unauthorized. Maybe you have removed the app permission in your STRAVA profile!? "
            "Use 'heroscript config --strava_reset' to remove all login data.py. Then try the command again and you "
            "will be askt for app authorization.")
Beispiel #6
0
def process_show(args):
    utility.log("process_show", "start")

    load = read_load()

    if load is None:
        utility.exit_on_error("No activity loaded yet.")

    if args.map:
        show_map()
        # print("Opening map in default Browser...", end='', flush=True)
        # tracksfer_gps.map("track.gps")
        # print("Done.")
        return

    if not path.exists(load.file_name):
        file_message = "<--------- MISSING !!!"
    else:
        file_message = ""

    print('File Name              : {} {}'.format(load.file_name, file_message))

    print('--- ATTRIBUTES ---')

    if load.new_activity_type is None:
        print(f"Activity Type          : ({load.original_activity_type})  "
              f"<=== Use set --activity_type {utility.activity_type_list}")
    else:
        print('Activity Type          : %s (original: %s)' %
              (load.new_activity_type, load.original_activity_type))

    print('Training Type          : %s' % load.training_type)

    print('Route Name             : %s' % load.route_name)

    print('Equipment Names        : %s' % load.equipment_names)

    print(f"Name                   : '{load.title}'")

    print("Comment                : '%s'" % load.comment)
    print("")

    print("Started at (GMT)       : {}".format(utility.get_human_date(load.started_at, "%a %y-%m-%d %H:%M")))

    print("Distance               : {0:.1f} k{1}".format(load.distance/1000, load.distance_unit_abbreviation()))

    print("Duration               : {} h".format(time.strftime('%H:%M:%S', time.gmtime(load.duration))))

    print("Velocity - Pace (total): {0:.1f} k{1}/h - {2}/k{3}".format(
        load.velocity_average, load.distance_unit_abbreviation(), load.pace, load.distance_unit_abbreviation()))

    print("Altitude               : \u25B2 {0:.0f} \u25bc {1:.0f}  [{2:.0f}..{3:.0f}] {4}".format(
        load.ascent, load.descent, load.altitude_min, load.altitude_max, load.distance_units))

    print('--- STRAVA ---')
    print(f'Activity ID            : {load.strava_activity_id}')
    print(f'Activity Name          : {load.strava_activity_name}')

    if(load.strava_descriptions is None):
        print('Description (generated): None')
    else:
        print(f'Description (generated):')
        for description in load.strava_descriptions:
            print(f'    {description}')

    print('--- STATUS ---')
    print('Velohero Workout ID    : %s' % load.velohero_workout_id)

    print("Archived to            : {}".format(load.archived_to))

    utility.log("process_show", "end")
Beispiel #7
0
def process_transfer(args):
    # utility.log("process_transfer", "start")

    if not args.velohero and not args.archive and not args.strava and not args.dir and not args.purge:
        utility.exit_on_error(
            "Missing transfer destination(s). Use --help to see possible arguments"
        )

    load = read_load()

    if load is None:
        utility.exit_on_error(
            "No file loaded! Use 'load' to stage the next activity.")

    if args.purge:
        if args.purge != path.basename(load.file_name):
            utility.exit_on_error(
                f"Wrong filename. You can only purge the loaded file {path.basename(load.file_name)}"
            )
        else:
            remove(load.file_name)
            delete_load()
            print("File and Load purged")
            return

    if args.strava and load.strava_activity_id is None:
        utility.exit_on_error(
            "STRAVA activity not loaded, so STRAVA can't be updated. If you want to update your STRAVA activity, "
            "first 'load --strava' to get the activity ID from STRAVA.")

    if not path.exists(load.file_name):
        utility.exit_on_error("File not found: '{}'".format(load.file_name))

    if load.new_activity_type is None:
        utility.exit_on_error(
            f"Activity type not set! Use heroscript set --activity_type '{utility.activity_type_list}'"
        )

    archive_preparation = None

    if args.dir or args.archive:
        if args.dir:
            archive_preparation = _prepare_archive(args.dir, load)

        if args.archive:
            archive_preparation = _prepare_archive(
                get_config(config.key_archive_dir), load)

        if archive_preparation['overwrite']:
            print(f"[WARN] Archive file already exists, will be overwritten.")

    if args.velohero:

        # Velohero step 2: Upload, if not already done
        if load.velohero_workout_id is None:
            print("Upload to velohero.", end='', flush=True)

            velohero_check_sso_login()
            print(".", end='', flush=True)

            velohero_workout_id = velohero_do_upload(load.file_name)

            load.set_velohero_workout_id(velohero_workout_id)
            print(".", end='', flush=True)

            save_load(load)

            velohero_do_update(velohero_workout_id, None, load)

            print("Done (new Workout ID %s created)" % velohero_workout_id)

        # Velohero step update
        else:
            print("Update velohero.", end='', flush=True)

            velohero_check_sso_login()
            print(".", end='', flush=True)

            velohero_workout_id = load.velohero_workout_id

            # Velohero step update
            velohero_do_update(velohero_workout_id, None, load)

            print("Done (Workout ID %s updated)" % velohero_workout_id)

    if args.strava:
        strava_do_update()

    if args.dir or args.archive:

        _execute_archive(archive_preparation, load)