From d17df2fc6c1f7ac1dc63c2852e9cc3ecdf25be0b Mon Sep 17 00:00:00 2001 From: petergardfjall Date: Wed, 12 Nov 2014 16:12:33 +0100 Subject: [PATCH] refactoring --- garminexport.py | 2 +- garminexport/util.py | 74 +++++++++++++++++++++++++++---------------- get_activity.py | 17 +++++++--- incremental_backup.py | 2 +- 4 files changed, 60 insertions(+), 35 deletions(-) diff --git a/garminexport.py b/garminexport.py index 45d636f..e51fe60 100755 --- a/garminexport.py +++ b/garminexport.py @@ -61,7 +61,7 @@ if __name__ == "__main__": for index, id in enumerate(activity_ids): log.info("processing activity {} ({} out of {}) ...".format( id, index+1, len(activity_ids))) - garminexport.util.save_activity( + garminexport.util.export_activity( client, id, args.destination) except Exception as e: exc_type, exc_value, exc_traceback = sys.exc_info() diff --git a/garminexport/util.py b/garminexport/util.py index 4d8dadc..5b37441 100644 --- a/garminexport/util.py +++ b/garminexport/util.py @@ -6,9 +6,12 @@ import json from datetime import datetime import os -def save_activity(client, activity_id, destination): - """Downloads a certain Garmin Connect activity and saves it - to a given destination directory. +export_formats=["json_summary", "json_details", "gpx", "tcx", "fit"] + +def export_activity(client, activity_id, destination, + formats=None): + """Exports a Garmin Connect activity to a given set of formats + and saves the result file(es) to a given destination directory. :param client: A :class:`garminexport.garminclient.GarminClient` instance that is assumed to be connected. @@ -17,37 +20,52 @@ def save_activity(client, activity_id, destination): :type activity_id: int :param destination: Destination directory (assumed to exist already). :type destination: str - + + :keyword formats: Which format(s) to export to. Could be any + of: 'json_summary', 'json_details', 'gpx', 'tcx', 'fit'. + If set to :obj:`None` all formats will be exported. + :type formats: list of str """ + if formats is None: + formats = ['json_summary', 'json_details', 'gpx', 'tcx', 'fit'] activity_summary = client.get_activity_summary(activity_id) - activity_details = client.get_activity_details(activity_id) - activity_gpx = client.get_activity_gpx(activity_id) - activity_tcx = client.get_activity_tcx(activity_id) - activity_fit = client.get_activity_fit(activity_id) - - # save activitity summary, details and GPX, TCX and FIT file. + + # prefix saved activity files with timestamp and activity id creation_millis = activity_summary["activity"]["uploadDate"]["millis"] timestamp = datetime.fromtimestamp(int(creation_millis)/1000.0) filename_prefix = "{}_{}".format( timestamp.strftime("%Y%m%d-%H%M%S"), activity_id) path_prefix = os.path.join(destination, filename_prefix) - summary_file = path_prefix + "_summary.json" - details_file = path_prefix + "_details.json" - gpx_file = path_prefix + ".gpx" - tcx_file = path_prefix + ".tcx" - fit_file = path_prefix + ".fit" - with codecs.open(summary_file, encoding="utf-8", mode="w") as f: - f.write(json.dumps( - activity_summary, ensure_ascii=False, indent=4)) - with codecs.open(details_file, encoding="utf-8", mode="w") as f: - f.write(json.dumps( - activity_details, ensure_ascii=False, indent=4)) - with codecs.open(gpx_file, encoding="utf-8", mode="w") as f: - f.write(activity_gpx) - with codecs.open(tcx_file, encoding="utf-8", mode="w") as f: - f.write(activity_tcx) - if activity_fit: - with open(fit_file, mode="wb") as f: - f.write(activity_fit) + if 'json_summary' in formats: + summary_file = path_prefix + "_summary.json" + with codecs.open(summary_file, encoding="utf-8", mode="w") as f: + f.write(json.dumps( + activity_summary, ensure_ascii=False, indent=4)) + + if 'json_details' in formats: + activity_details = client.get_activity_details(activity_id) + details_file = path_prefix + "_details.json" + with codecs.open(details_file, encoding="utf-8", mode="w") as f: + f.write(json.dumps( + activity_details, ensure_ascii=False, indent=4)) + + if 'gpx' in formats: + activity_gpx = client.get_activity_gpx(activity_id) + gpx_file = path_prefix + ".gpx" + with codecs.open(gpx_file, encoding="utf-8", mode="w") as f: + f.write(activity_gpx) + + if 'tcx' in formats: + activity_tcx = client.get_activity_tcx(activity_id) + tcx_file = path_prefix + ".tcx" + with codecs.open(tcx_file, encoding="utf-8", mode="w") as f: + f.write(activity_tcx) + + if 'fit' in formats: + activity_fit = client.get_activity_fit(activity_id) + fit_file = path_prefix + ".fit" + if activity_fit: + with open(fit_file, mode="wb") as f: + f.write(activity_fit) diff --git a/get_activity.py b/get_activity.py index 0235af0..94f2f59 100755 --- a/get_activity.py +++ b/get_activity.py @@ -23,7 +23,6 @@ LOG_LEVELS = { } """Command-line (string-based) log-level mapping to logging module levels.""" - if __name__ == "__main__": parser = argparse.ArgumentParser( @@ -34,6 +33,10 @@ if __name__ == "__main__": "username", metavar="", type=str, help="Account user name.") parser.add_argument( "activity", metavar="", type=int, help="Activity ID.") + parser.add_argument( + "format", metavar="", type=str, + help="Export format (one of: {}).".format( + garminexport.util.export_formats)) # optional args parser.add_argument( @@ -49,7 +52,12 @@ if __name__ == "__main__": args = parser.parse_args() if not args.log_level in LOG_LEVELS: - raise ValueError("Illegal log-level argument: {}".format(args.log_level)) + raise ValueError("Illegal log-level argument: {}".format( + args.log_level)) + if not args.format in garminexport.util.export_formats: + raise ValueError( + "Uncrecognized export format: '{}'. Must be one of {}".format( + args.format, garminexport.util.export_formats)) logging.root.setLevel(LOG_LEVELS[args.log_level]) try: @@ -58,11 +66,10 @@ if __name__ == "__main__": if not args.password: args.password = getpass.getpass("Enter password: ") - with GarminClient(args.username, args.password) as client: log.info("fetching activity {} ...".format(args.activity)) - garminexport.util.save_activity( - client, args.activity, args.destination) + garminexport.util.export_activity( + client, args.activity, args.destination, formats=[args.format]) except Exception as e: exc_type, exc_value, exc_traceback = sys.exc_info() log.error(u"failed with exception: %s", e) diff --git a/incremental_backup.py b/incremental_backup.py index e65acae..7a53f4e 100755 --- a/incremental_backup.py +++ b/incremental_backup.py @@ -99,7 +99,7 @@ if __name__ == "__main__": for index, id in enumerate(missing_activities): log.info("backing up activity {} ({} out of {}) ...".format( id, index+1, len(missing_activities))) - garminexport.util.save_activity( + garminexport.util.export_activity( client, id, args.backup_dir) except Exception as e: exc_type, exc_value, exc_traceback = sys.exc_info()