Skip to content

Commit

Permalink
make garmin base domain configurable, bug fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
Tom Goetz committed Oct 4, 2023
1 parent 52fe56a commit 53e1e46
Show file tree
Hide file tree
Showing 6 changed files with 23 additions and 14 deletions.
3 changes: 3 additions & 0 deletions garmindb/GarminConnectConfig.json.example
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
{
"garmin": {
"domain": "garmin.com"
},
"credentials": {
"user" : "joe@shmoe.com",
"secure_password" : false,
Expand Down
16 changes: 9 additions & 7 deletions garmindb/download.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

from .garmin_connect_config_manager import GarminConnectConfigManager
from .config_manager import ConfigManager
from idbutils import RestException


logger = logging.getLogger(__file__)
Expand Down Expand Up @@ -51,12 +52,13 @@ class Download():
def __init__(self):
"""Create a new Download class instance."""
logger.debug("__init__")
self.gc_config = GarminConnectConfigManager()
self.garth = GarthClient()
self.garth.configure(domain=self.gc_config.get_garmin_base_domain())

def login(self):
"""Login to Garmin Connect."""
profile_dir = ConfigManager.get_or_create_fit_files_dir()
self.gc_config = GarminConnectConfigManager()
username = self.gc_config.get_user()
password = self.gc_config.get_password()
if not username or not password:
Expand Down Expand Up @@ -107,18 +109,18 @@ def save_json_to_file(cls, filename, json_data, overwite=False):
with open(full_filename, 'w') as file:
file.write(json.dumps(json_data, default=cls.__convert_to_json))

@classmethod
def save_binary_file(cls, filename, response, overwite=False):
def save_binary_file(self, filename, url, overwite=False):
"""Save binary data to a file."""
exists = os.path.isfile(filename)
if not exists or overwite:
logger.info("%s %s", 'Overwriting' if exists else 'Saving', filename)
try:
response = self.garth.get("connectapi", url, api=True)
with open(filename, 'wb') as file:
for chunk in response:
file.write(chunk)
except Exception as e:
raise Exception(e, response, error=f'failed to save as binary: {e} ({response.content})')
raise RestException(e, error=f'failed to save as binary: {e}')

def __get_stat(self, stat_function, directory, date, days, overwite):
for day in tqdm(range(0, days), unit='days'):
Expand Down Expand Up @@ -151,9 +153,9 @@ def get_daily_summaries(self, directory_func, date, days, overwite):
def __get_monitoring_day(self, date):
root_logger.info("get_monitoring_day: %s to %s", date, self.temp_dir)
zip_filename = f'{self.temp_dir}/{date}.zip'
url = f'/wellness/{date.strftime("%Y-%m-%d")}'
url = f'{self.garmin_connect_download_service_url}/wellness/{date.strftime("%Y-%m-%d")}'
try:
self.save_binary_file(zip_filename, self.garth.connectapi(url))
self.save_binary_file(zip_filename, url)
except GarthHTTPError as e:
root_logger.error("Exception getting daily summary: %s", e)

Expand Down Expand Up @@ -212,7 +214,7 @@ def __save_activity_file(self, activity_id_str):
zip_filename = f'{self.temp_dir}/activity_{activity_id_str}.zip'
url = f'{self.garmin_connect_download_service_url}/activity/{activity_id_str}'
try:
self.save_json_to_file(zip_filename, self.garth.connectapi(url))
self.save_binary_file(zip_filename, url)
except GarthHTTPError as e:
root_logger.error("Exception downloading activity file: %s", e)

Expand Down
4 changes: 4 additions & 0 deletions garmindb/garmin_connect_config_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,10 @@ def get_password(self):
return self.get_secure_password()
return self.__get_node_value('credentials', 'password')

def get_garmin_base_domain(self):
"""Return the Garmin base domain to use for api calls."""
return self.__get_node_value_default('garmin', 'domain', "garmin.com")

def latest_activity_count(self):
"""Return the number of activities to download when getting the latest."""
return self.__get_node_value('data', 'download_latest_activities')
Expand Down
8 changes: 4 additions & 4 deletions garmindb/import_monitoring.py
Original file line number Diff line number Diff line change
Expand Up @@ -282,9 +282,8 @@ def __init__(self, db_params, input_dir, debug):
self.conversions = {'calendarDate': self._parse_date}

def _process_json(self, json_data):
userData = json_data['userData']
measurement_system = fitfile.field_enums.DisplayMeasure.from_string(
userData['measurementSystem'])
measurement_system = fitfile.field_enums.DisplayMeasure.from_string(json_data['measurementSystem'])
logger.info("Processing profile data: measurement_system %r from %s", measurement_system, json_data['measurementSystem'])
Attributes.set_newer(self.garmin_db, 'measurement_system', str(measurement_system))
return 1

Expand All @@ -303,7 +302,7 @@ def __init__(self, db_params, input_dir, debug):
debug (Boolean): enable debug logging
"""
logger.info("Processing profile data")
logger.info("Processing social profile data")
super().__init__(r'^social_profile\.json', input_dir=input_dir, latest=False, debug=debug)
self.garmin_db = GarminDb(db_params)
self.conversions = {'calendarDate': self._parse_date}
Expand All @@ -314,6 +313,7 @@ def _process_json(self, json_data):
'userName': json_data['userName'],
'name': json_data['fullName']
}
logger.info("Processing social profile data: %r", attributes)
for attribute_name, attribute_value in attributes.items():
Attributes.set_newer(
self.garmin_db, attribute_name, attribute_value)
Expand Down
4 changes: 2 additions & 2 deletions scripts/garmindb_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@

from garmindb import Download, Copy, Analyze
from garmindb import FitFileProcessor, ActivityFitFileProcessor, MonitoringFitFileProcessor, SleepFitFileProcessor
from garmindb import GarminProfile, GarminSocialProfile, GarminWeightData, GarminSummaryData, GarminMonitoringFitData, GarminSleepFitData, GarminSleepData, GarminRhrData, GarminSettingsFitData, \
GarminHydrationData
from garmindb import GarminProfile, GarminSocialProfile, GarminWeightData, GarminSummaryData, GarminMonitoringFitData, GarminSleepFitData, GarminSleepData, GarminRhrData, \
GarminSettingsFitData, GarminHydrationData
from garmindb import GarminJsonSummaryData, GarminJsonDetailsData, GarminTcxData, GarminActivitiesFitData
from garmindb import ActivityExporter

Expand Down
2 changes: 1 addition & 1 deletion test/test_profile_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def test_parse_uprofile(self):
gdb = GarminDb(db_params)
measurement_system = Attributes.measurements_type(gdb)
self.assertEqual(measurement_system, fitfile.field_enums.DisplayMeasure.statute,
'DisplayMeasure expected %r found %r' % (fitfile.field_enums.DisplayMeasure.statute, measurement_system))
'DisplayMeasure expected %r found %r from %r' % (fitfile.field_enums.DisplayMeasure.statute, measurement_system, gp.file_names))


if __name__ == '__main__':
Expand Down

0 comments on commit 53e1e46

Please sign in to comment.