2014-11-11 13:45:11 +01:00
#! /usr/bin/env python
""" Performs (incremental) backups of activities for a given Garmin Connect
account .
The activities are stored in a local directory on the user ' s computer.
The backups are incremental , meaning that only activities that aren ' t already
stored in the backup directory will be downloaded .
"""
import argparse
2017-03-07 19:42:27 +01:00
from datetime import timedelta
2014-11-11 13:45:11 +01:00
import getpass
from garminexport . garminclient import GarminClient
2015-03-04 20:55:55 +01:00
import garminexport . backup
from garminexport . backup import export_formats
2017-03-07 19:42:27 +01:00
from garminexport . retryer import (
Retryer , ExponentialBackoffDelayStrategy , MaxRetriesStopStrategy )
2014-11-11 13:45:11 +01:00
import logging
import os
import re
import sys
import traceback
logging . basicConfig (
level = logging . INFO , format = " %(asctime)-15s [ %(levelname)s ] %(message)s " )
log = logging . getLogger ( __name__ )
LOG_LEVELS = {
" DEBUG " : logging . DEBUG ,
" INFO " : logging . INFO ,
" WARNING " : logging . WARNING ,
" ERROR " : logging . ERROR
}
""" Command-line (string-based) log-level mapping to logging module levels. """
2017-03-07 19:42:27 +01:00
DEFAULT_MAX_RETRIES = 7
""" The default maximum number of retries to make when fetching a single activity. """
2015-02-20 09:32:59 +01:00
2014-11-11 13:45:11 +01:00
if __name__ == " __main__ " :
parser = argparse . ArgumentParser (
description = (
" Performs incremental backups of activities for a "
" given Garmin Connect account. Only activities that "
" aren ' t already stored in the backup directory will "
" be downloaded. " ) )
# positional args
parser . add_argument (
" username " , metavar = " <username> " , type = str , help = " Account user name. " )
# optional args
parser . add_argument (
" --password " , type = str , help = " Account password. " )
parser . add_argument (
" --backup-dir " , metavar = " DIR " , type = str ,
help = ( " Destination directory for downloaded activities. Default: "
" ./activities/ " ) , default = os . path . join ( " . " , " activities " ) )
parser . add_argument (
" --log-level " , metavar = " LEVEL " , type = str ,
help = ( " Desired log output level (DEBUG, INFO, WARNING, ERROR). "
" Default: INFO. " ) , default = " INFO " )
2015-02-20 09:32:59 +01:00
parser . add_argument (
2015-03-04 20:55:55 +01:00
" -f " , " --format " , choices = export_formats ,
2015-02-20 09:32:59 +01:00
default = None , action = ' append ' ,
2015-03-04 20:55:55 +01:00
help = ( " Desired output formats ( " + ' , ' . join ( export_formats ) + " ). "
2015-02-20 09:32:59 +01:00
" Default: ALL. " ) )
parser . add_argument (
" -E " , " --ignore-errors " , action = ' store_true ' ,
help = " Ignore errors and keep going. Default: FALSE " )
2017-03-07 19:42:27 +01:00
parser . add_argument (
" --max-retries " , metavar = " NUM " , default = DEFAULT_MAX_RETRIES ,
type = int , help = " The maximum number of retries to make on failed attempts to fetch an activity. Exponential backoff will be used, meaning that the delay between successive attempts will double with every retry, starting at one second. DEFAULT: %d " % DEFAULT_MAX_RETRIES )
2017-05-14 08:54:23 +02:00
2014-11-11 13:45:11 +01:00
args = parser . parse_args ( )
if not args . log_level in LOG_LEVELS :
2015-03-04 20:55:55 +01:00
raise ValueError ( " Illegal log-level: {} " . format ( args . log_level ) )
# if no --format was specified, all formats are to be backed up
args . format = args . format if args . format else export_formats
log . info ( " backing up formats: %s " , " , " . join ( args . format ) )
2017-05-14 08:54:23 +02:00
2014-11-11 13:45:11 +01:00
logging . root . setLevel ( LOG_LEVELS [ args . log_level ] )
2015-03-04 20:55:55 +01:00
2014-11-11 13:45:11 +01:00
try :
if not os . path . isdir ( args . backup_dir ) :
os . makedirs ( args . backup_dir )
2017-05-14 08:54:23 +02:00
2014-11-11 13:45:11 +01:00
if not args . password :
args . password = getpass . getpass ( " Enter password: " )
2017-05-14 08:54:23 +02:00
2017-03-07 19:42:27 +01:00
# set up a retryer that will handle retries of failed activity
# downloads
retryer = Retryer (
delay_strategy = ExponentialBackoffDelayStrategy (
initial_delay = timedelta ( seconds = 1 ) ) ,
stop_strategy = MaxRetriesStopStrategy ( args . max_retries ) )
2014-11-11 13:45:11 +01:00
with GarminClient ( args . username , args . password ) as client :
2015-02-20 09:32:59 +01:00
# get all activity ids and timestamps from Garmin account
2017-05-14 08:54:23 +02:00
log . info ( " scanning activities for %s ... " , args . username )
2017-03-07 19:42:27 +01:00
activities = set ( retryer . call ( client . list_activities ) )
2017-05-14 08:54:23 +02:00
log . info ( " account has a total of %d activities " , len ( activities ) )
2015-03-04 20:55:55 +01:00
missing_activities = garminexport . backup . need_backup (
activities , args . backup_dir , args . format )
backed_up = activities - missing_activities
2017-05-14 08:54:23 +02:00
log . info ( " %s contains %d backed up activities " ,
args . backup_dir , len ( backed_up ) )
log . info ( " activities that aren ' t backed up: %d " ,
len ( missing_activities ) )
2015-02-20 09:32:59 +01:00
2015-03-04 20:55:55 +01:00
for index , activity in enumerate ( missing_activities ) :
id , start = activity
2017-03-07 19:42:27 +01:00
log . info ( " backing up activity %d from %s ( %d out of %d ) ... " % ( id , start , index + 1 , len ( missing_activities ) ) )
2015-02-20 09:32:59 +01:00
try :
2015-03-04 20:55:55 +01:00
garminexport . backup . download (
2017-03-07 19:42:27 +01:00
client , activity , retryer , args . backup_dir ,
args . format )
2015-02-20 09:32:59 +01:00
except Exception as e :
log . error ( u " failed with exception: %s " , e )
if not args . ignore_errors :
raise
2014-11-11 13:45:11 +01:00
except Exception as e :
exc_type , exc_value , exc_traceback = sys . exc_info ( )
2017-05-14 08:54:23 +02:00
log . error ( u " failed with exception: %s " , str ( e ) )