[be40b02] | 1 | import os |
---|
| 2 | |
---|
| 3 | from fitparse.utils import FitHeaderError |
---|
| 4 | |
---|
| 5 | from ow.utilities import create_blob |
---|
| 6 | from ow.models.workout import Workout |
---|
| 7 | |
---|
| 8 | |
---|
| 9 | def get_files(path, extension): |
---|
| 10 | """ |
---|
| 11 | Given a path and a file extension, return a list of full-path strings |
---|
| 12 | pointing to files found with such extension |
---|
| 13 | """ |
---|
| 14 | files = [] |
---|
| 15 | for f in os.listdir(path): |
---|
| 16 | if f.endswith(extension): |
---|
| 17 | files.append(os.path.join(path, f)) |
---|
| 18 | return files |
---|
| 19 | |
---|
| 20 | |
---|
| 21 | def load_workouts(user, paths, extension='fit'): |
---|
| 22 | """ |
---|
| 23 | Load workouts from the given path, looking for files with the given |
---|
| 24 | extension (only fit and gpx files supported so far) |
---|
| 25 | """ |
---|
| 26 | for path in paths: |
---|
| 27 | print('Loading from path:', path) |
---|
| 28 | files = get_files(path, extension) |
---|
| 29 | for file_path in files: |
---|
| 30 | if extension == 'fit': |
---|
| 31 | print(' Loading file:', file_path) |
---|
| 32 | with open(file_path, 'rb') as f_obj: |
---|
| 33 | fit_blob = create_blob( |
---|
| 34 | f_obj.read(), file_extension=extension, binary=True) |
---|
| 35 | elif extension == 'gpx': |
---|
| 36 | print(' Loading file:', file_path) |
---|
| 37 | with open(file_path, 'r') as f_obj: |
---|
| 38 | fit_blob = create_blob( |
---|
| 39 | f_obj.read(), file_extension=extension) |
---|
| 40 | workout = Workout() |
---|
| 41 | workout.tracking_file = fit_blob |
---|
| 42 | workout.tracking_filetype = extension |
---|
| 43 | try: |
---|
| 44 | workout.load_from_file() |
---|
| 45 | except FitHeaderError: |
---|
| 46 | print(' ERROR LOADING WORKOUT ') |
---|
| 47 | else: |
---|
| 48 | # add the workout only if no errors happened |
---|
| 49 | user.add_workout(workout) |
---|