├── logo.png ├── logo256w.png ├── sessioncache.py ├── .gitignore ├── README.md ├── nokia.py ├── smashrun.py ├── fit.py ├── garmin.py ├── nokia-weight-sync.py └── LICENSE /logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/magnific0/nokia-weight-sync/HEAD/logo.png -------------------------------------------------------------------------------- /logo256w.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/magnific0/nokia-weight-sync/HEAD/logo256w.png -------------------------------------------------------------------------------- /sessioncache.py: -------------------------------------------------------------------------------- 1 | # From https://github.com/cpfair/tapiriik 2 | 3 | from datetime import datetime 4 | 5 | class SessionCache: 6 | def __init__(self, lifetime, freshen_on_get=False): 7 | self._lifetime = lifetime 8 | self._autorefresh = freshen_on_get 9 | self._cache = {} 10 | 11 | def Get(self, pk, freshen=False): 12 | if pk not in self._cache: 13 | return 14 | record = self._cache[pk] 15 | if record.Expired(): 16 | del self._cache[pk] 17 | return None 18 | if self._autorefresh or freshen: 19 | record.Refresh() 20 | return record.Get() 21 | 22 | def Set(self, pk, value): 23 | self._cache[pk] = SessionCacheRecord(value, self._lifetime) 24 | 25 | class SessionCacheRecord: 26 | def __init__(self, data, lifetime): 27 | self._value = data 28 | self._lifetime = lifetime 29 | self.Refresh() 30 | 31 | def Expired(self): 32 | return self._timestamp < datetime.utcnow() - self._lifetime 33 | 34 | def Refresh(self): 35 | self._timestamp = datetime.utcnow() 36 | 37 | def Get(self): 38 | return self._value 39 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # nokia-to-garmin-weight 2 | *.ini 3 | 4 | # Byte-compiled / optimized / DLL files 5 | __pycache__/ 6 | *.py[cod] 7 | *$py.class 8 | 9 | # C extensions 10 | *.so 11 | 12 | # Distribution / packaging 13 | .Python 14 | build/ 15 | develop-eggs/ 16 | dist/ 17 | downloads/ 18 | eggs/ 19 | .eggs/ 20 | lib/ 21 | lib64/ 22 | parts/ 23 | sdist/ 24 | var/ 25 | wheels/ 26 | *.egg-info/ 27 | .installed.cfg 28 | *.egg 29 | MANIFEST 30 | 31 | # PyInstaller 32 | # Usually these files are written by a python script from a template 33 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 34 | *.manifest 35 | *.spec 36 | 37 | # Installer logs 38 | pip-log.txt 39 | pip-delete-this-directory.txt 40 | 41 | # Unit test / coverage reports 42 | htmlcov/ 43 | .tox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | 53 | # Translations 54 | *.mo 55 | *.pot 56 | 57 | # Django stuff: 58 | *.log 59 | .static_storage/ 60 | .media/ 61 | local_settings.py 62 | 63 | # Flask stuff: 64 | instance/ 65 | .webassets-cache 66 | 67 | # Scrapy stuff: 68 | .scrapy 69 | 70 | # Sphinx documentation 71 | docs/_build/ 72 | 73 | # PyBuilder 74 | target/ 75 | 76 | # Jupyter Notebook 77 | .ipynb_checkpoints 78 | 79 | # pyenv 80 | .python-version 81 | 82 | # celery beat schedule file 83 | celerybeat-schedule 84 | 85 | # SageMath parsed files 86 | *.sage.py 87 | 88 | # Environments 89 | .env 90 | .venv 91 | env/ 92 | venv/ 93 | ENV/ 94 | env.bak/ 95 | venv.bak/ 96 | 97 | # Spyder project settings 98 | .spyderproject 99 | .spyproject 100 | 101 | # Rope project settings 102 | .ropeproject 103 | 104 | # mkdocs documentation 105 | /site 106 | 107 | # mypy 108 | .mypy_cache/ 109 | 110 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # nokia-weight-sync 2 | Get weight from Nokia Health and update to Garmin Connect or Smashrun. 3 | 4 | ![nokia-weight-sync-logo](logo.png) 5 | 6 | ## Installation 7 | 8 | 1. Download / clone the repository. 9 | 10 | 2. Satisfy the following requirements: 11 | 12 | - Python 3.X 13 | - Python libraries: arrow, requests, requests-oauthlib 14 | 15 | 3. [Register](https://account.withings.com/partner/add_oauth2) an application with Nokia Health and obtain a consumer key and secret. 16 | 1. logo: the requirements are quite strict, [feel free to use this one](https://github.com/magnific0/nokia-weight-sync/blob/master/logo256w.png) 17 | 1. callback: you can pick anything, but if you want to do the automated authorization (you will be prompted for this), you need to pick the hostname/ip and port carefully. For example http://localhost:8087. 18 | - localhost: if you run nokia-weight-sync and do the authorization in the browser on the same device. This needs to be replaced by local or public ip/hostname if you run it on a server. 19 | - 8087: a port that is likely not used by other services. For a remote setup make sure the port is not firewalled. 20 | - http: https is available, but requires additional setup of certificates. For localhost http is fine. 21 | 22 | ## Usage 23 | 24 | 1. On first run you need to set-up your Nokia Health consumer key and secret: 25 | 26 | ./nokia-weight-sync.py -k CONSUMER_KEY -s CONSUMER_SECRET setup nokia 27 | 28 | 2. Follow the instructions on the screen and verify the application. 29 | 30 | 3. Register one or more destination services: 31 | 32 | - **Garmin Connect:** register your Garmin Connect credentials and sync your last measurement (provide GC password when asked): 33 | 34 | ./nokia-weight-sync.py -k user@example.com setup garmin 35 | 36 | - **Smashrun (implicit flow, recommended):** for user level authentication simply copy the access token (no registration, no refresh after expiry): 37 | 38 | ./nokia-weight-sync.py setup smashrun 39 | 40 | - **Smashrun (code flow):** register Smashrun API application keys and follow the authorization process to obtain your users refresh_token ([registration required](https://api.smashrun.com/register), refresh after expiry): 41 | 42 | ./nokia-weight-sync.py -k CLIENT_ID -s CLIENT_SECRET setup smashrun_code 43 | 44 | 4. Verify that the relevant sections for the services are added to ```config.ini```. 45 | 46 | 5. Synchronize (new) measurements: 47 | 48 | ./nokia-weight-sync.py sync garmin 49 | ./nokia-weight-sync.py sync smashrun 50 | 51 | **Important** Nokia Health API, Smashrun API, and Garmin Connect credentials are stored in ```config.ini```. If this file is compromised your Garmin Connect account, personal health data from Nokia Health, and activity data from Smashrun are at risk. 52 | 53 | ## Advanced 54 | 55 | See ```./nokia-weight-sync.py --help``` for more information. 56 | 57 | ## Notice 58 | 59 | nokia-weight-sync includes components the following open-source projects: 60 | 61 | * ```fit.py``` from [ikasamah/withings-garmin](https://github.com/ikasamah/withings-garmin), MIT License (c) 2013 Masayuki Hamasaki, adapted for Python 3. 62 | * ```garmin.py``` from [jaroslawhartman/withings-garmin-v2](https://github.com/jaroslawhartman/withings-garmin-v2), MIT License (c) 2013 Masayuki Hamasaki, adapted for Python 3. 63 | * ```nokia.py``` from [python-nokia](https://github.com/orcasgit/python-nokia), MIT License (c) 2012 Maxime Bouroumeau-Fuseau, 2017 ORCAS, unmodified. 64 | * ```sessioncache.py``` from [cpfair/tapiriik](https://github.com/cpfair/tapiriik/blob/187d1b97ce73cc35b5e2194eb4631ceff20499e3/tapiriik/services/sessioncache.py), Apache License 2.0, unmodified. 65 | * ```smashrun.py``` from [campbellr/smashrun-client](https://github.com/campbellr/smashrun-client), Apache License 2.0, several fixes. 66 | 67 | ## Support 68 | 69 | Please [open an issue](https://github.com/magnific0/nokia-weight-sync/issues/new) for support. 70 | 71 | ## Contributing 72 | 73 | Please contribute using [Github Flow](https://guides.github.com/introduction/flow/). Create a branch, add commits, and [open a pull request](https://github.com/magnific0/nokia-weight-sync/compare/). 74 | -------------------------------------------------------------------------------- /nokia.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | """ 4 | Python library for the Nokia Health API 5 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 6 | 7 | Nokia Health API 8 | 9 | 10 | Uses Oauth 2.0 to authentify. You need to obtain a consumer key 11 | and consumer secret from Nokia by creating an application 12 | here: 13 | 14 | Usage: 15 | 16 | auth = NokiaAuth(CLIENT_ID, CONSUMER_SECRET, CALLBACK_URL) 17 | authorize_url = auth.get_authorize_url() 18 | print("Go to %s allow the app and copy the url you are redirected to." % authorize_url) 19 | authorization_response = raw_input('Please enter your full authorization response url: ') 20 | creds = auth.get_credentials(authorization_response) 21 | 22 | client = NokiaApi(creds) 23 | measures = client.get_measures(limit=1) 24 | print("Your last measured weight: %skg" % measures[0].weight) 25 | 26 | creds = client.get_credentials() 27 | 28 | """ 29 | 30 | from __future__ import unicode_literals 31 | 32 | __title__ = 'nokia' 33 | __version__ = '0.4.0' 34 | __author__ = 'Maxime Bouroumeau-Fuseau, and ORCAS' 35 | __license__ = 'MIT' 36 | __copyright__ = 'Copyright 2012-2017 Maxime Bouroumeau-Fuseau, and ORCAS' 37 | 38 | __all__ = [str('NokiaCredentials'), str('NokiaAuth'), str('NokiaApi'), 39 | str('NokiaMeasures'), str('NokiaMeasureGroup')] 40 | 41 | import arrow 42 | import datetime 43 | import json 44 | 45 | from arrow.parser import ParserError 46 | from requests_oauthlib import OAuth2Session 47 | from oauthlib.oauth2 import WebApplicationClient 48 | 49 | class NokiaCredentials(object): 50 | def __init__(self, access_token=None, token_expiry=None, token_type=None, 51 | refresh_token=None, user_id=None, 52 | client_id=None, consumer_secret=None): 53 | self.access_token = access_token 54 | self.token_expiry = token_expiry 55 | self.token_type = token_type 56 | self.refresh_token = refresh_token 57 | self.user_id = user_id 58 | self.client_id = client_id 59 | self.consumer_secret = consumer_secret 60 | 61 | 62 | class NokiaAuth(object): 63 | URL = 'https://account.withings.com' 64 | 65 | def __init__(self, client_id, consumer_secret, callback_uri, 66 | scope='user.metrics'): 67 | self.client_id = client_id 68 | self.consumer_secret = consumer_secret 69 | self.callback_uri = callback_uri 70 | self.scope = scope 71 | 72 | def _oauth(self): 73 | return OAuth2Session(self.client_id, 74 | redirect_uri=self.callback_uri, 75 | scope=self.scope) 76 | 77 | def get_authorize_url(self): 78 | return self._oauth().authorization_url( 79 | '%s/oauth2_user/authorize2'%self.URL 80 | )[0] 81 | 82 | def get_credentials(self, code): 83 | tokens = self._oauth().fetch_token( 84 | '%s/oauth2/token' % self.URL, 85 | code=code, 86 | timeout=2, 87 | client_secret=self.consumer_secret) 88 | 89 | return NokiaCredentials( 90 | access_token=tokens['access_token'], 91 | token_expiry=str(ts()+int(tokens['expires_in'])), 92 | token_type=tokens['token_type'], 93 | refresh_token=tokens['refresh_token'], 94 | user_id=tokens['userid'], 95 | client_id=self.client_id, 96 | consumer_secret=self.consumer_secret, 97 | ) 98 | 99 | 100 | def is_date(key): 101 | return 'date' in key 102 | 103 | 104 | def is_date_class(val): 105 | return isinstance(val, (datetime.date, datetime.datetime, arrow.Arrow, )) 106 | 107 | 108 | # Calculate seconds since 1970-01-01 (timestamp) in a way that works in 109 | # Python 2 and Python3 110 | # https://docs.python.org/3/library/datetime.html#datetime.datetime.timestamp 111 | def ts(): 112 | return int(( 113 | datetime.datetime.utcnow() - datetime.datetime(1970, 1, 1) 114 | ).total_seconds()) 115 | 116 | 117 | class NokiaApi(object): 118 | URL = 'https://wbsapi.withings.net' 119 | 120 | def __init__(self, credentials): 121 | self.credentials = credentials 122 | self.token = { 123 | 'access_token': credentials.access_token, 124 | 'refresh_token': credentials.refresh_token, 125 | 'token_type': credentials.token_type, 126 | 'expires_in': str(int(credentials.token_expiry) - ts()), 127 | } 128 | oauth_client = WebApplicationClient(credentials.client_id, 129 | token=self.token, default_token_placement='query') 130 | self.client = OAuth2Session( 131 | credentials.client_id, 132 | token=self.token, 133 | client=oauth_client, 134 | auto_refresh_url='{}/oauth2/token'.format(NokiaAuth.URL), 135 | auto_refresh_kwargs={ 136 | 'client_id': credentials.client_id, 137 | 'client_secret': credentials.consumer_secret, 138 | }, 139 | token_updater=self.set_token 140 | ) 141 | 142 | def get_credentials(self): 143 | return self.credentials 144 | 145 | def set_token(self, token): 146 | self.token = token 147 | self.credentials.token_expiry = str( 148 | ts() + int(self.token['expires_in']) 149 | ) 150 | self.credentials.access_token = self.token['access_token'] 151 | self.credentials.refresh_token = self.token['refresh_token'] 152 | 153 | def request(self, service, action, params=None, method='GET', 154 | version=None): 155 | params = params or {} 156 | params['userid'] = self.credentials.user_id 157 | params['action'] = action 158 | for key, val in params.items(): 159 | if is_date(key) and is_date_class(val): 160 | params[key] = arrow.get(val).timestamp 161 | url_parts = filter(None, [self.URL, version, service]) 162 | r = self.client.request(method, '/'.join(url_parts), params=params,timeout=10) 163 | response = json.loads(r.content.decode()) 164 | if response['status'] != 0: 165 | raise Exception("Error code %s" % response['status']) 166 | return response.get('body', None) 167 | 168 | def get_user(self): 169 | return self.request('user', 'getbyuserid') 170 | 171 | def get_activities(self, **kwargs): 172 | r = self.request('measure', 'getactivity', params=kwargs, version='v2') 173 | activities = r['activities'] if 'activities' in r else [r] 174 | return [NokiaActivity(act) for act in activities] 175 | 176 | def get_measures(self, **kwargs): 177 | r = self.request('measure', 'getmeas', kwargs) 178 | return NokiaMeasures(r) 179 | 180 | def get_sleep(self, **kwargs): 181 | r = self.request('sleep', 'get', params=kwargs, version='v2') 182 | return NokiaSleep(r) 183 | 184 | def subscribe(self, callback_url, comment, **kwargs): 185 | params = {'callbackurl': callback_url, 'comment': comment} 186 | params.update(kwargs) 187 | self.request('notify', 'subscribe', params) 188 | 189 | def unsubscribe(self, callback_url, **kwargs): 190 | params = {'callbackurl': callback_url} 191 | params.update(kwargs) 192 | self.request('notify', 'revoke', params) 193 | 194 | def is_subscribed(self, callback_url, appli=1): 195 | params = {'callbackurl': callback_url, 'appli': appli} 196 | try: 197 | self.request('notify', 'get', params) 198 | return True 199 | except: 200 | return False 201 | 202 | def list_subscriptions(self, appli=1): 203 | r = self.request('notify', 'list', {'appli': appli}) 204 | return r['profiles'] 205 | 206 | 207 | class NokiaObject(object): 208 | def __init__(self, data): 209 | self.set_attributes(data) 210 | 211 | def set_attributes(self, data): 212 | self.data = data 213 | for key, val in data.items(): 214 | try: 215 | setattr(self, key, arrow.get(val) if is_date(key) else val) 216 | except ParserError: 217 | setattr(self, key, val) 218 | 219 | 220 | class NokiaActivity(NokiaObject): 221 | pass 222 | 223 | 224 | class NokiaMeasures(list, NokiaObject): 225 | def __init__(self, data): 226 | super(NokiaMeasures, self).__init__( 227 | [NokiaMeasureGroup(g) for g in data['measuregrps']]) 228 | self.set_attributes(data) 229 | 230 | 231 | class NokiaMeasureGroup(NokiaObject): 232 | MEASURE_TYPES = ( 233 | ('weight', 1), 234 | ('height', 4), 235 | ('fat_free_mass', 5), 236 | ('fat_ratio', 6), 237 | ('fat_mass_weight', 8), 238 | ('diastolic_blood_pressure', 9), 239 | ('systolic_blood_pressure', 10), 240 | ('heart_pulse', 11), 241 | ('temperature', 12), 242 | ('spo2', 54), 243 | ('body_temperature', 71), 244 | ('skin_temperature', 72), 245 | ('muscle_mass', 76), 246 | ('hydration', 77), 247 | ('bone_mass', 88), 248 | ('pulse_wave_velocity', 91) 249 | ) 250 | 251 | def __init__(self, data): 252 | super(NokiaMeasureGroup, self).__init__(data) 253 | for n, t in self.MEASURE_TYPES: 254 | self.__setattr__(n, self.get_measure(t)) 255 | 256 | def is_ambiguous(self): 257 | return self.attrib == 1 or self.attrib == 4 258 | 259 | def is_measure(self): 260 | return self.category == 1 261 | 262 | def is_target(self): 263 | return self.category == 2 264 | 265 | def get_measure(self, measure_type): 266 | for m in self.measures: 267 | if m['type'] == measure_type: 268 | return m['value'] * pow(10, m['unit']) 269 | return None 270 | 271 | 272 | class NokiaSleepSeries(NokiaObject): 273 | def __init__(self, data): 274 | super(NokiaSleepSeries, self).__init__(data) 275 | self.timedelta = self.enddate - self.startdate 276 | 277 | 278 | class NokiaSleep(NokiaObject): 279 | def __init__(self, data): 280 | super(NokiaSleep, self).__init__(data) 281 | self.series = [NokiaSleepSeries(series) for series in self.series] 282 | -------------------------------------------------------------------------------- /smashrun.py: -------------------------------------------------------------------------------- 1 | """ This module contains main user-facing Smashrun interface. 2 | 3 | """ 4 | from __future__ import division 5 | 6 | import json 7 | import datetime 8 | from itertools import islice 9 | 10 | from requests_oauthlib import OAuth2Session 11 | 12 | auth_url = "https://secure.smashrun.com/oauth2/authenticate" 13 | token_url = "https://secure.smashrun.com/oauth2/token" 14 | 15 | 16 | class Smashrun(object): 17 | def __init__(self, client_id=None, client_secret=None, client=None, 18 | auto_refresh_url=None, auto_refresh_kwargs=None, scope=None, 19 | redirect_uri=None, token=None, state=None, token_updater=None, 20 | **kwargs): 21 | self.session = OAuth2Session( 22 | client_id=client_id, 23 | client=client, 24 | auto_refresh_url=token_url, 25 | scope=scope, 26 | redirect_uri=redirect_uri, 27 | token=token, 28 | state=state, 29 | token_updater=token_updater, 30 | **kwargs 31 | ) 32 | self.client_secret = client_secret 33 | self.base_url = "https://api.smashrun.com/v1" 34 | 35 | @property 36 | def client_id(self): 37 | return self.session.client_id 38 | 39 | def get_auth_url(self): 40 | return self.session.authorization_url( 41 | auth_url, client_secret=self.client_secret) 42 | 43 | def fetch_token(self, **kwargs): 44 | """Fetch a new token using the supplied code. 45 | 46 | :param str code: A previously obtained auth code. 47 | 48 | """ 49 | if 'client_secret' not in kwargs: 50 | kwargs.update(client_secret=self.client_secret) 51 | return self.session.fetch_token(token_url, **kwargs) 52 | 53 | def refresh_token(self, **kwargs): 54 | """Refresh the authentication token. 55 | 56 | :param str refresh_token: The refresh token to use. May be empty if 57 | retrieved with ``fetch_token``. 58 | 59 | """ 60 | if 'client_secret' not in kwargs: 61 | kwargs.update(client_secret=self.client_secret) 62 | if 'client_id' not in kwargs: 63 | kwargs.update(client_id=self.client_id) 64 | return self.session.refresh_token(token_url, **kwargs) 65 | 66 | def get_activity(self, id_num): 67 | """Return the activity with the given id. 68 | 69 | Note that this contains more detailed information than returned 70 | by `get_activities`. 71 | 72 | """ 73 | url = self._build_url('my', 'activities', id_num) 74 | return self._json(url) 75 | 76 | def get_activities(self, count=10, since=None, style='summary', 77 | limit=None): 78 | """Iterate over all activities, from newest to oldest. 79 | 80 | :param count: The number of results to retrieve per page. 81 | :param since: Return only activities since this date. Can be either 82 | a timestamp or a datetime object. 83 | 84 | :param style: The type of records to return. May be one of 85 | 'summary', 'briefs', 'ids', or 'extended'. 86 | 87 | :param limit: The maximum number of activities to return for the given 88 | query. 89 | 90 | """ 91 | params = {} 92 | if since: 93 | params.update(fromDate=to_timestamp(since)) 94 | parts = ['my', 'activities', 'search'] 95 | if style != 'summary': 96 | parts.append(style) 97 | url = self._build_url(*parts) 98 | # TODO: return an Activity (or ActivitySummary?) class that can do 99 | # things like convert date and time fields to proper datetime objects 100 | return islice(self._iter(url, count, **params), limit) 101 | 102 | def get_badges(self): 103 | """Return all badges the user has earned.""" 104 | url = self._build_url('my', 'badges') 105 | return self._json(url) 106 | 107 | def get_notables(self, id_num): 108 | """Return the notables of the activity with the given id. 109 | """ 110 | url = self._build_url('my', 'activities', id_num, 'notables') 111 | return self._json(url) 112 | 113 | def get_polyline(self, id_num, style='google'): 114 | """Return the polyline of the activity with the given id. 115 | 116 | :param style: The type of polyline to return. May be one of 117 | 'google', 'svg', or 'geojson'. 118 | 119 | """ 120 | parts = ['my', 'activities', id_num, 'polyline'] 121 | if style != 'google': 122 | parts.append(style) 123 | url = self._build_url(*parts) 124 | 125 | return self._json(url) 126 | 127 | def get_splits(self, id_num, unit='mi'): 128 | """Return the splits of the activity with the given id. 129 | 130 | :param unit: The unit to use for splits. May be one of 131 | 'mi' or 'km'. 132 | 133 | """ 134 | url = self._build_url('my', 'activities', id_num, 'splits', unit) 135 | 136 | return self._json(url) 137 | 138 | def get_stats(self, year=None, month=None): 139 | """Return stats for the given year and month.""" 140 | parts = ['my', 'stats'] 141 | if month and not year: 142 | raise ValueError("month cannot be specified without year") 143 | if year: 144 | parts.append(year) 145 | if month: 146 | parts.append(year) 147 | url = self._build_url(*parts) 148 | return self._json(url) 149 | 150 | def get_current_weight(self): 151 | """Return the most recent weight recording.""" 152 | url = self._build_url('my', 'body', 'weight', 'latest') 153 | return self._json(url) 154 | 155 | def get_weight_history(self): 156 | """Return all weight recordings.""" 157 | url = self._build_url('my', 'body', 'weight') 158 | return self._json(url) 159 | 160 | def get_userinfo(self): 161 | """Return information about the current user.""" 162 | url = self._build_url('my', 'userinfo') 163 | return self._json(url) 164 | 165 | def create_weight(self, weight, date=None): 166 | """Submit a new weight record. 167 | 168 | :param weight: The weight, in kilograms. 169 | :param date: The date the weight was recorded. If not 170 | specified, the current date will be used. 171 | 172 | """ 173 | url = self._build_url('my', 'body', 'weight') 174 | data = {'weightInKilograms': weight} 175 | if date: 176 | if isinstance(date,str): 177 | data.update(date=date) 178 | else: 179 | if not date.is_aware(): 180 | raise ValueError("provided date is not timezone aware") 181 | data.update(date=date.isoformat()) 182 | headers = {'Content-Type': 'application/json; charset=utf8'} 183 | r = self.session.post(url, data=json.dumps(data), headers=headers) 184 | r.raise_for_status() 185 | return r 186 | 187 | def create_activity(self, data): 188 | """Create a new activity (run). 189 | 190 | :param data: The data representing the activity you want to upload. 191 | May be either JSON, GPX, or TCX. 192 | 193 | """ 194 | url = self._build_url('my', 'activities') 195 | if isinstance(data, dict): 196 | data = json.dumps(data) 197 | r = self.session.post(url, data=data) 198 | r.raise_for_status() 199 | return r 200 | 201 | def update_activity(self, id_num, data): 202 | """Update an existing activity (run). 203 | 204 | :param id_num: The activity ID to update 205 | :param data: The data representing the activity you want to upload. 206 | May be either JSON, GPX, or TCX. 207 | 208 | """ 209 | url = self._build_url('my', 'activities') 210 | if isinstance(data, dict): 211 | data = json.dumps(data) 212 | r = self.session.put(url, data=data) 213 | r.raise_for_status() 214 | return r 215 | 216 | def delete_activity(self, id_num): 217 | """Delete an activity (run). 218 | 219 | :param id_num: The activity ID to delete 220 | 221 | 222 | """ 223 | url = self._build_url('my', 'activities', id_num) 224 | r = self.session.delete(url) 225 | r.raise_for_status() 226 | return r 227 | 228 | def _iter(self, url, count, cls=None, **kwargs): 229 | page = 0 230 | while True: 231 | kwargs.update(count=count, page=page) 232 | r = self.session.get(url, params=kwargs) 233 | r.raise_for_status() 234 | data = r.json() 235 | if not data: 236 | break 237 | for d in data: 238 | if cls: 239 | yield cls(d) 240 | else: 241 | yield d 242 | page += 1 243 | 244 | def _build_url(self, *args, **kwargs): 245 | parts = [kwargs.get('base_url') or self.base_url] 246 | parts.extend(args) 247 | parts = [str(p) for p in parts] 248 | return "/".join(parts) 249 | 250 | def _json(self, url): 251 | response = self.session.get(url) 252 | response.raise_for_status() 253 | return response.json() 254 | 255 | 256 | def to_timestamp(dt): 257 | """Convert a datetime object to a unix timestamp. 258 | 259 | Note that unlike a typical unix timestamp, this is seconds since 1970 260 | *local time*, not UTC. 261 | 262 | If the passed in object is already a timestamp, then that value is 263 | simply returned unmodified. 264 | """ 265 | if isinstance(dt, int): 266 | return dt 267 | return int(total_seconds(dt.replace(tzinfo=None) - 268 | datetime.datetime(1970, 1, 1))) 269 | 270 | 271 | def total_seconds(delta): 272 | if hasattr(delta, 'total_seconds'): 273 | return delta.total_seconds() 274 | return (delta.microseconds + 275 | (delta.seconds + delta.days * 24 * 3600) * 10**6) / 10**6 276 | 277 | 278 | def is_aware(d): 279 | return d.tzinfo is not None and d.tzinfo.utcoffset(d) is not None 280 | -------------------------------------------------------------------------------- /fit.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from io import BytesIO as StringIO 4 | from struct import pack 5 | from struct import unpack 6 | from datetime import datetime 7 | import time 8 | 9 | 10 | def _calcCRC(crc, byte): 11 | table = [0x0000, 0xCC01, 0xD801, 0x1400, 0xF001, 0x3C00, 0x2800, 0xE401, 12 | 0xA001, 0x6C00, 0x7800, 0xB401, 0x5000, 0x9C01, 0x8801, 0x4400] 13 | # compute checksum of lower four bits of byte 14 | tmp = table[crc & 0xF] 15 | crc = (crc >> 4) & 0x0FFF 16 | crc = crc ^ tmp ^ table[byte & 0xF] 17 | # now compute checksum of upper four bits of byte 18 | tmp = table[crc & 0xF] 19 | crc = (crc >> 4) & 0x0FFF 20 | crc = crc ^ tmp ^ table[(byte >> 4) & 0xF] 21 | return crc 22 | 23 | 24 | class FitBaseType(object): 25 | """BaseType Definition 26 | 27 | see FIT Protocol Document(Page.20)""" 28 | enum = {'#': 0, 'endian': 0, 'field': 0x00, 'name': 'enum', 'invalid': 0xFF, 'size': 1} 29 | sint8 = {'#': 1, 'endian': 0, 'field': 0x01, 'name': 'sint8', 'invalid': 0x7F, 'size': 1} 30 | uint8 = {'#': 2, 'endian': 0, 'field': 0x02, 'name': 'uint8', 'invalid': 0xFF, 'size': 1} 31 | sint16 = {'#': 3, 'endian': 1, 'field': 0x83, 'name': 'sint16', 'invalid': 0x7FFF, 'size': 2} 32 | uint16 = {'#': 4, 'endian': 1, 'field': 0x84, 'name': 'uint16', 'invalid': 0xFFFF, 'size': 2} 33 | sint32 = {'#': 5, 'endian': 1, 'field': 0x85, 'name': 'sint32', 'invalid': 0x7FFFFFFF, 'size': 4} 34 | uint32 = {'#': 6, 'endian': 1, 'field': 0x86, 'name': 'uint32', 'invalid': 0xFFFFFFFF, 'size': 4} 35 | string = {'#': 7, 'endian': 0, 'field': 0x07, 'name': 'string', 'invalid': 0x00, 'size': 1} 36 | float32 = {'#': 8, 'endian': 1, 'field': 0x88, 'name': 'float32', 'invalid': 0xFFFFFFFF, 'size': 2} 37 | float64 = {'#': 9, 'endian': 1, 'field': 0x89, 'name': 'float64', 'invalid': 0xFFFFFFFFFFFFFFFF, 'size': 4} 38 | uint8z = {'#': 10, 'endian': 0, 'field': 0x0A, 'name': 'uint8z', 'invalid': 0x00, 'size': 1} 39 | uint16z = {'#': 11, 'endian': 1, 'field': 0x8B, 'name': 'uint16z', 'invalid': 0x0000, 'size': 2} 40 | uint32z = {'#': 12, 'endian': 1, 'field': 0x8C, 'name': 'uint32z', 'invalid': 0x00000000, 'size': 4} 41 | byte = {'#': 13, 'endian': 0, 'field': 0x0D, 'name': 'byte', 'invalid': 0xFF, 'size': 1} # array of byte, field is invalid if all bytes are invalid 42 | 43 | @staticmethod 44 | def get_format(basetype): 45 | formats = { 46 | 0: 'B', 1: 'b', 2: 'B', 3: 'h', 4: 'H', 5: 'i', 6: 'I', 7: 's', 8: 'f', 47 | 9: 'd', 10: 'B', 11: 'H', 12: 'I', 13: 'c', 48 | } 49 | return formats[basetype['#']] 50 | 51 | @staticmethod 52 | def pack(basetype, value): 53 | """function to avoid DeprecationWarning""" 54 | if basetype['#'] in (1,2,3,4,5,6,10,11,12): 55 | value = int(value) 56 | fmt = FitBaseType.get_format(basetype) 57 | return pack(fmt, value) 58 | 59 | 60 | class Fit(object): 61 | HEADER_SIZE = 12 62 | 63 | GMSG_NUMS = { 64 | 'file_id': 0, 65 | 'device_info': 23, 66 | 'weight_scale': 30, 67 | 'file_creator': 49, 68 | } 69 | 70 | 71 | class FitEncoder(Fit): 72 | def timestamp(self, t): 73 | """the timestamp in fit protocol is seconds since 74 | UTC 00:00 Dec 31 1989 (631065600)""" 75 | if isinstance(t, datetime): 76 | t = time.mktime(t.timetuple()) 77 | return t - 631065600 78 | 79 | 80 | class FitEncoder_Weight(FitEncoder): 81 | FILE_TYPE = 9 82 | LMSG_TYPE_FILE_INFO = 0 83 | LMSG_TYPE_FILE_CREATOR = 1 84 | LMSG_TYPE_DEVICE_INFO = 2 85 | LMSG_TYPE_WEIGHT_SCALE = 3 86 | 87 | def __init__(self): 88 | self.buf = StringIO() 89 | self.write_header() # create header first 90 | self.device_info_defined = False 91 | self.weight_scale_defined = False 92 | 93 | def __str__(self): 94 | orig_pos = self.buf.tell() 95 | self.buf.seek(0) 96 | lines = [] 97 | while True: 98 | b = self.buf.read(16) 99 | if not b: 100 | break 101 | lines.append(' '.join(['%02x' % ord(c) for c in b])) 102 | self.buf.seek(orig_pos) 103 | return '\n'.join(lines) 104 | 105 | def write_header(self, header_size=Fit.HEADER_SIZE, 106 | protocol_version=16, 107 | profile_version=108, 108 | data_size=0, 109 | data_type='.FIT'): 110 | self.buf.seek(0) 111 | s = pack('BBHI4s'.encode('ascii'), header_size, protocol_version, profile_version, data_size, data_type.encode('ascii')) 112 | self.buf.write(s) 113 | 114 | def _build_content_block(self, content): 115 | field_defs = [] 116 | values = [] 117 | for num, basetype, value, scale in content: 118 | s = pack('BBB', num, basetype['size'], basetype['field']) 119 | field_defs.append(s) 120 | if value is None: 121 | # invalid value 122 | value = basetype['invalid'] 123 | elif scale is not None: 124 | value *= scale 125 | values.append(FitBaseType.pack(basetype, value)) 126 | return (b''.join(field_defs), b''.join(values)) 127 | 128 | def write_file_info(self, serial_number=None, time_created=None, manufacturer=None, product=None, number=None): 129 | if time_created is None: 130 | time_created = datetime.now() 131 | 132 | content = [ 133 | (3, FitBaseType.uint32z, serial_number, None), 134 | (4, FitBaseType.uint32, self.timestamp(time_created), None), 135 | (1, FitBaseType.uint16, manufacturer, None), 136 | (2, FitBaseType.uint16, product, None), 137 | (5, FitBaseType.uint16, number, None), 138 | (0, FitBaseType.enum, self.FILE_TYPE, None), # type 139 | ] 140 | fields, values = self._build_content_block(content) 141 | 142 | # create fixed content 143 | msg_number = self.GMSG_NUMS['file_id'] 144 | fixed_content = pack('BBHB', 0, 0, msg_number, len(content)) # reserved, architecture(0: little endian) 145 | 146 | self.buf.write(b''.join([ 147 | # definition 148 | self.record_header(definition=True, lmsg_type=self.LMSG_TYPE_FILE_INFO), 149 | fixed_content, 150 | fields, 151 | #record 152 | self.record_header(lmsg_type=self.LMSG_TYPE_FILE_INFO), 153 | values, 154 | ])) 155 | 156 | 157 | def write_file_creator(self, software_version=None, hardware_version=None): 158 | content = [ 159 | (0, FitBaseType.uint16, software_version, None), 160 | (1, FitBaseType.uint8, hardware_version, None), 161 | ] 162 | fields, values = self._build_content_block(content) 163 | 164 | msg_number = self.GMSG_NUMS['file_creator'] 165 | fixed_content = pack('BBHB', 0, 0, msg_number, len(content)) # reserved, architecture(0: little endian) 166 | self.buf.write(b''.join([ 167 | # definition 168 | self.record_header(definition=True, lmsg_type=self.LMSG_TYPE_FILE_CREATOR), 169 | fixed_content, 170 | fields, 171 | #record 172 | self.record_header(lmsg_type=self.LMSG_TYPE_FILE_CREATOR), 173 | values, 174 | ])) 175 | 176 | def write_device_info(self, timestamp, serial_number=None, cum_operationg_time=None, manufacturer=None, 177 | product=None, software_version=None, battery_voltage=None, device_index=None, 178 | device_type=None, hardware_version=None, battery_status=None): 179 | content = [ 180 | (253, FitBaseType.uint32, self.timestamp(timestamp), 1), 181 | (3, FitBaseType.uint32z, serial_number, 1), 182 | (7, FitBaseType.uint32, cum_operationg_time, 1), 183 | (8, FitBaseType.uint32, None, None), # unknown field(undocumented) 184 | (2, FitBaseType.uint16, manufacturer, 1), 185 | (4, FitBaseType.uint16, product, 1), 186 | (5, FitBaseType.uint16, software_version, 100), 187 | (10, FitBaseType.uint16, battery_voltage, 256), 188 | (0, FitBaseType.uint8, device_index, 1), 189 | (1, FitBaseType.uint8, device_type, 1), 190 | (6, FitBaseType.uint8, hardware_version, 1), 191 | (11, FitBaseType.uint8, battery_status, None), 192 | ] 193 | fields, values = self._build_content_block(content) 194 | 195 | if not self.device_info_defined: 196 | header = self.record_header(definition=True, lmsg_type=self.LMSG_TYPE_DEVICE_INFO) 197 | msg_number = self.GMSG_NUMS['device_info'] 198 | fixed_content = pack('BBHB', 0, 0, msg_number, len(content)) # reserved, architecture(0: little endian) 199 | self.buf.write(header + fixed_content + fields) 200 | self.device_info_defined = True 201 | 202 | header = self.record_header(lmsg_type=self.LMSG_TYPE_DEVICE_INFO) 203 | self.buf.write(header + values) 204 | 205 | def write_weight_scale(self, timestamp, weight, percent_fat=None, percent_hydration=None, 206 | visceral_fat_mass=None, bone_mass=None, muscle_mass=None, basal_met=None, 207 | active_met=None, physique_rating=None, metabolic_age=None, visceral_fat_rating=None, 208 | bmi=None): 209 | content = [ 210 | (253, FitBaseType.uint32, self.timestamp(timestamp), 1), 211 | (0, FitBaseType.uint16, weight, 100), 212 | (1, FitBaseType.uint16, percent_fat, 100), 213 | (2, FitBaseType.uint16, percent_hydration, 100), 214 | (3, FitBaseType.uint16, visceral_fat_mass, 100), 215 | (4, FitBaseType.uint16, bone_mass, 100), 216 | (5, FitBaseType.uint16, muscle_mass, 100), 217 | (7, FitBaseType.uint16, basal_met, 4), 218 | (9, FitBaseType.uint16, active_met, 4), 219 | (8, FitBaseType.uint8, physique_rating, 1), 220 | (10, FitBaseType.uint8, metabolic_age, 1), 221 | (11, FitBaseType.uint8, visceral_fat_rating, 1), 222 | (13, FitBaseType.uint16, bmi, 10), 223 | ] 224 | fields, values = self._build_content_block(content) 225 | 226 | if not self.weight_scale_defined: 227 | header = self.record_header(definition=True, lmsg_type=self.LMSG_TYPE_WEIGHT_SCALE) 228 | msg_number = self.GMSG_NUMS['weight_scale'] 229 | fixed_content = pack('BBHB', 0, 0, msg_number, len(content)) # reserved, architecture(0: little endian) 230 | self.buf.write(header + fixed_content + fields) 231 | self.weight_scale_defined = True 232 | 233 | header = self.record_header(lmsg_type=self.LMSG_TYPE_WEIGHT_SCALE) 234 | self.buf.write(header + values) 235 | 236 | def record_header(self, definition=False, lmsg_type=0): 237 | msg = 0 238 | if definition: 239 | msg = 1 << 6 # 6th bit is a definition message 240 | return pack('B', msg + lmsg_type) 241 | 242 | def crc(self): 243 | orig_pos = self.buf.tell() 244 | self.buf.seek(0) 245 | 246 | crc = 0 247 | while(True): 248 | b = self.buf.read(1) 249 | if not b: 250 | break 251 | crc = _calcCRC(crc, unpack('b', b)[0]) 252 | self.buf.seek(orig_pos) 253 | return pack('H', crc) 254 | 255 | def finish(self): 256 | """re-weite file-header, then append crc to end of file""" 257 | data_size = self.get_size() - self.HEADER_SIZE 258 | self.write_header(data_size=data_size) 259 | crc = self.crc() 260 | self.buf.seek(0, 2) 261 | self.buf.write(crc) 262 | 263 | def get_size(self): 264 | orig_pos = self.buf.tell() 265 | self.buf.seek(0, 2) 266 | size = self.buf.tell() 267 | self.buf.seek(orig_pos) 268 | return size 269 | 270 | def getvalue(self): 271 | return self.buf.getvalue() 272 | 273 | -------------------------------------------------------------------------------- /garmin.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from sessioncache import SessionCache 4 | from datetime import datetime, timedelta 5 | import urllib.request 6 | import datetime 7 | import requests 8 | import re 9 | import sys 10 | import json 11 | 12 | # {{{ 13 | # Exception definitions used below from tapiriik/tapiriik/services/api.py 14 | # https://github.com/cpfair/tapiriik/blob/master/LICENSE 15 | class ServiceExceptionScope: 16 | Account = "account" 17 | Service = "service" 18 | # Unlike Account and Service-level blocking exceptions, these are implemented via ActivityRecord.FailureCounts 19 | # Eventually, all errors might be stored in ActivityRecords 20 | Activity = "activity" 21 | 22 | class ServiceException(Exception): 23 | def __init__(self, message, scope=ServiceExceptionScope.Service, block=False, user_exception=None, trigger_exhaustive=True): 24 | Exception.__init__(self, message) 25 | self.Message = message 26 | self.UserException = user_exception 27 | self.Block = block 28 | self.Scope = scope 29 | self.TriggerExhaustive = trigger_exhaustive 30 | 31 | def __str__(self): 32 | return self.Message + " (user " + str(self.UserException) + " )" 33 | 34 | class ServiceWarning(ServiceException): 35 | pass 36 | 37 | class APIException(ServiceException): 38 | pass 39 | 40 | class APIWarning(ServiceWarning): 41 | pass 42 | 43 | # Theoretically, APIExcludeActivity should actually be a ServiceException with block=True, scope=Activity 44 | # It's on the to-do list. 45 | 46 | class APIExcludeActivity(Exception): 47 | def __init__(self, message, activity=None, activity_id=None, permanent=True, user_exception=None): 48 | Exception.__init__(self, message) 49 | self.Message = message 50 | self.Activity = activity 51 | self.ExternalActivityID = activity_id 52 | self.Permanent = permanent 53 | self.UserException = user_exception 54 | 55 | def __str__(self): 56 | return self.Message + " (activity " + str(self.ExternalActivityID) + ")" 57 | 58 | class UserExceptionType: 59 | # Account-level exceptions (not a hardcoded thing, just to keep these seperate) 60 | Authorization = "auth" 61 | RenewPassword = "renew_password" 62 | Locked = "locked" 63 | AccountFull = "full" 64 | AccountExpired = "expired" 65 | AccountUnpaid = "unpaid" # vs. expired, which implies it was at some point function, via payment or trial or otherwise. 66 | NonAthleteAccount = "non_athlete_account" # trainingpeaks 67 | 68 | # Activity-level exceptions 69 | FlowException = "flow" 70 | Private = "private" 71 | NoSupplier = "nosupplier" 72 | NotTriggered = "notrigger" 73 | Deferred = "deferred" # They've instructed us not to synchronize activities for some time after they complete 74 | PredatesWindow = "predates_window" # They've instructed us not to synchronize activities before some date 75 | RateLimited = "ratelimited" 76 | MissingCredentials = "credentials_missing" # They forgot to check the "Remember these details" box 77 | NotConfigured = "config_missing" # Don't think this error is even possible any more. 78 | StationaryUnsupported = "stationary" 79 | NonGPSUnsupported = "nongps" 80 | TypeUnsupported = "type_unsupported" 81 | InsufficientData = "data_insufficient" # Some services demand more data than others provide (ahem, N+) 82 | DownloadError = "download" 83 | ListingError = "list" # Cases when a service fails listing, so nothing can be uploaded to it. 84 | UploadError = "upload" 85 | SanityError = "sanity" 86 | Corrupt = "corrupt" # Kind of a scary term for what's generally "some data is missing" 87 | Untagged = "untagged" 88 | LiveTracking = "live" 89 | UnknownTZ = "tz_unknown" 90 | System = "system" 91 | Other = "other" 92 | 93 | class UserException: 94 | def __init__(self, type, extra=None, intervention_required=False, clear_group=None): 95 | self.Type = type 96 | self.Extra = extra # Unimplemented - displayed as part of the error message. 97 | self.InterventionRequired = intervention_required # Does the user need to dismiss this error? 98 | self.ClearGroup = clear_group if clear_group else type # Used to group error messages displayed to the user, and let them clear a group that share a common cause. 99 | 100 | class LoginSucceeded(Exception): 101 | pass 102 | 103 | class LoginFailed(Exception): 104 | pass 105 | 106 | # }}} 107 | 108 | 109 | class GarminConnect(object): 110 | LOGIN_URL = 'https://connect.garmin.com/signin' 111 | UPLOAD_URL = 'https://connect.garmin.com/modern/proxy/upload-service/upload/.fit' 112 | 113 | _sessionCache = SessionCache(lifetime=timedelta(minutes=30), freshen_on_get=True) 114 | 115 | def create_opener(self, cookie): 116 | this = self 117 | class _HTTPRedirectHandler(urllib.request.HTTPRedirectHandler): 118 | def http_error_302(self, req, fp, code, msg, headers): 119 | if req.get_full_url() == this.LOGIN_URL: 120 | raise LoginSucceeded 121 | return urllib.request.HTTPRedirectHandler.http_error_302(self, req, fp, code, msg, headers) 122 | return urllib.request.build_opener(_HTTPRedirectHandler, urllib.request.HTTPCookieProcessor(cookie)) 123 | 124 | ############################################## 125 | # From https://github.com/cpfair/tapiriik 126 | 127 | def _get_session(self, record=None, email=None, password=None): 128 | session = requests.Session() 129 | 130 | # JSIG CAS, cool I guess. 131 | # Not quite OAuth though, so I'll continue to collect raw credentials. 132 | # Commented stuff left in case this ever breaks because of missing parameters... 133 | data = { 134 | "username": email, 135 | "password": password, 136 | "_eventId": "submit", 137 | "embed": "true", 138 | # "displayNameRequired": "false" 139 | } 140 | params = { 141 | "service": "https://connect.garmin.com/modern", 142 | "redirectAfterAccountLoginUrl": "http://connect.garmin.com/modern", 143 | "redirectAfterAccountCreationUrl": "http://connect.garmin.com/modern", 144 | # "webhost": "olaxpw-connect00.garmin.com", 145 | "clientId": "GarminConnect", 146 | "gauthHost": "https://sso.garmin.com/sso", 147 | # "rememberMeShown": "true", 148 | # "rememberMeChecked": "false", 149 | "consumeServiceTicket": "false", 150 | # "id": "gauth-widget", 151 | # "embedWidget": "false", 152 | # "cssUrl": "https://static.garmincdn.com/com.garmin.connect/ui/src-css/gauth-custom.css", 153 | # "source": "http://connect.garmin.com/en-US/signin", 154 | # "createAccountShown": "true", 155 | # "openCreateAccount": "false", 156 | # "usernameShown": "true", 157 | # "displayNameShown": "false", 158 | # "initialFocus": "true", 159 | # "locale": "en" 160 | } 161 | headers = { 162 | "origin": "https://sso.garmin.com" 163 | } 164 | 165 | # I may never understand what motivates people to mangle a perfectly good protocol like HTTP in the ways they do... 166 | preResp = session.get("https://sso.garmin.com/sso/signin", params=params) 167 | if preResp.status_code != 200: 168 | raise APIException("SSO prestart error %s %s" % (preResp.status_code, preResp.text)) 169 | 170 | ssoResp = session.post("https://sso.garmin.com/sso/signin", headers=headers, params=params, data=data, allow_redirects=False) 171 | if ssoResp.status_code != 200 or "temporarily unavailable" in ssoResp.text: 172 | raise APIException("SSO error %s %s" % (ssoResp.status_code, ssoResp.text)) 173 | 174 | if ">sendEvent('FAIL')" in ssoResp.text: 175 | raise APIException("Invalid login", block=True, user_exception=UserException(UserExceptionType.Authorization, intervention_required=True)) 176 | if ">sendEvent('ACCOUNT_LOCKED')" in ssoResp.text: 177 | raise APIException("Account Locked", block=True, user_exception=UserException(UserExceptionType.Locked, intervention_required=True)) 178 | 179 | if "renewPassword" in ssoResp.text: 180 | raise APIException("Reset password", block=True, user_exception=UserException(UserExceptionType.RenewPassword, intervention_required=True)) 181 | 182 | # self.print_cookies(cookies=session.cookies) 183 | 184 | # ...AND WE'RE NOT DONE YET! 185 | 186 | gcRedeemResp = session.get("https://connect.garmin.com/modern", allow_redirects=False) 187 | if gcRedeemResp.status_code != 302: 188 | raise APIException("GC redeem-start error %s %s" % (gcRedeemResp.status_code, gcRedeemResp.text)) 189 | 190 | url_prefix = "https://connect.garmin.com" 191 | 192 | # There are 6 redirects that need to be followed to get the correct cookie 193 | # ... :( 194 | max_redirect_count = 7 195 | current_redirect_count = 1 196 | while True: 197 | url = gcRedeemResp.headers["location"] 198 | 199 | # Fix up relative redirects. 200 | if url.startswith("/"): 201 | url = url_prefix + url 202 | url_prefix = "/".join(url.split("/")[:3]) 203 | gcRedeemResp = session.get(url, allow_redirects=False) 204 | 205 | if current_redirect_count >= max_redirect_count and gcRedeemResp.status_code != 200: 206 | raise APIException("GC redeem %d/%d error %s %s" % (current_redirect_count, max_redirect_count, gcRedeemResp.status_code, gcRedeemResp.text)) 207 | if gcRedeemResp.status_code == 200 or gcRedeemResp.status_code == 404: 208 | break 209 | current_redirect_count += 1 210 | if current_redirect_count > max_redirect_count: 211 | break 212 | 213 | self._sessionCache.Set(record.ExternalID if record else email, session.cookies) 214 | 215 | # self.print_cookies(session.cookies) 216 | 217 | return session 218 | 219 | def print_cookies(self, cookies): 220 | print("Cookies") 221 | 222 | for key, value in cookies.items(): 223 | print("Key: " + key + ", " + value) 224 | 225 | def login(self, username, password): 226 | 227 | session = self._get_session(email=username, password=password) 228 | try: 229 | res = session.get("https://connect.garmin.com/modern") 230 | 231 | userdata_json_str = re.search(r"VIEWER_SOCIAL_PROFILE\s*=\s*JSON\.parse\((.+)\);$", res.text, re.MULTILINE).group(1) 232 | userdata = json.loads(json.loads(userdata_json_str)) 233 | GCusername = userdata["displayName"] 234 | except Exception as e: 235 | raise APIException("Unable to retrieve username: %s" % e, block=True, user_exception=UserException(UserExceptionType.Authorization, intervention_required=True)) 236 | 237 | sys.stderr.write('Garmin Connect User Name: ' + GCusername + '\n') 238 | 239 | if not len(GCusername): 240 | raise APIException("Unable to retrieve username", block=True, user_exception=UserException(UserExceptionType.Authorization, intervention_required=True)) 241 | return (session) 242 | 243 | def upload_file(self, f, session): 244 | files = {"data": ("withings.fit", f)} 245 | 246 | res = session.post(self.UPLOAD_URL, 247 | files=files, 248 | headers={"nk": "NT"}) 249 | 250 | try: 251 | resp = res.json()["detailedImportResult"] 252 | except ValueError: 253 | if(res.status_code == 204): # HTTP result 204 - "no content" 254 | sys.stderr.write('No data to upload, try to use --fromdate and --todate\n') 255 | else: 256 | print("Bad response during GC upload: " + str(res.status_code)) 257 | raise APIException("Bad response during GC upload: %s %s" % (res.status_code, res.text)) 258 | 259 | return (res.status_code == 200 or res.status_code == 201 or res.status_code == 204) 260 | 261 | -------------------------------------------------------------------------------- /nokia-weight-sync.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | Nokia Health to Garmin Connect Weight Updater 4 | """ 5 | 6 | __author__ = "Jacco Geul" 7 | __version__ = "0.1.0" 8 | __license__ = "GPLv3" 9 | 10 | from optparse import OptionParser 11 | import configparser 12 | from fit import FitEncoder_Weight 13 | from garmin import GarminConnect 14 | from smashrun import Smashrun 15 | from oauthlib.oauth2 import MobileApplicationClient 16 | import urllib.parse 17 | import nokia 18 | import os.path 19 | import sys 20 | import time 21 | import getpass 22 | import base64 23 | from http.server import HTTPServer, BaseHTTPRequestHandler 24 | from urllib.parse import parse_qs, urlparse 25 | import ssl 26 | 27 | nokia_auth_code = None 28 | 29 | # Extremely basic HTTP server for handling authorization response 30 | class AuthorizationRepsponseHandler(BaseHTTPRequestHandler): 31 | def do_GET(self): 32 | global nokia_auth_code 33 | nokia_auth_code = parse_qs(urlparse(self.path).query).get('code', None)[0] 34 | self.send_response(200) 35 | self.send_header('Content-type', 'text/html') 36 | self.end_headers() 37 | self.wfile.write('

Authorization successful!

'.encode('utf-8')) 38 | 39 | # Do command processing 40 | class MyParser(OptionParser): 41 | def format_epilog(self, formatter): 42 | return self.epilog 43 | 44 | usage = "usage: %prog [options] command [service]" 45 | epilog = """ 46 | Commands: 47 | setup, sync, last, userinfo, subscribe, unsubscribe, list_subscriptions 48 | 49 | Services: 50 | nokia, garmin, smashrun, smashrun_code (setup only) 51 | 52 | Copyright (c) 2018 by Jacco Geul 53 | Licensed under GNU General Public License 3.0 54 | """ 55 | parser = MyParser(usage=usage,epilog=epilog,version=__version__) 56 | 57 | parser.add_option('-k', '--key', dest='key', help="Key/Username") 58 | parser.add_option('-s', '--secret', dest='secret', help="Secret/Password") 59 | parser.add_option('-u', '--callback', dest='callback', help="Callback/redirect URI") 60 | parser.add_option('-a', '--authorization-server', dest='auth_serv', action="store_true", default=None, help="Authorization server") 61 | parser.add_option('-c', '--config', dest='config', default='config.ini', help="Config file") 62 | 63 | (options, args) = parser.parse_args() 64 | 65 | if len(args) == 0: 66 | print("Missing command!") 67 | print("Available commands: setup, sync, last, userinfo, subscribe, unsubscribe, list_subscriptions") 68 | sys.exit(1) 69 | 70 | command = args.pop(0) 71 | 72 | config = configparser.ConfigParser() 73 | config.read(options.config) 74 | 75 | # Decode the Garmin password 76 | if config.has_section('garmin'): 77 | if config.has_option('garmin', 'password'): 78 | config.set('garmin', 'password', base64.b64decode(config.get('garmin', 'password').encode('ascii')).decode('ascii')) 79 | 80 | def setup_nokia( options, config ): 81 | """ Setup the Nokia Health API 82 | """ 83 | global nokia_auth_code 84 | if options.key is None: 85 | print("To set a connection with Nokia Health you must have registered an application at https://account.withings.com/partner/add_oauth2 .") 86 | options.key = input('Please enter the client id: ') 87 | 88 | if options.secret is None: 89 | options.secret = input('Please enter the consumer secret: ') 90 | 91 | if options.callback is None: 92 | options.callback = input('Please enter the callback url known by Nokia: ') 93 | 94 | if options.auth_serv is None: 95 | auth_serv_resp = input('Spin up HTTP server to automate authorization? [y/n] : ') 96 | if auth_serv_resp is 'y': 97 | options.auth_serv = True 98 | else: 99 | options.auth_serv = False 100 | 101 | if options.auth_serv: 102 | callback_parts = urlparse(options.callback) 103 | httpd_port = callback_parts.port 104 | httpd_ssl = callback_parts.scheme == 'https' 105 | if not httpd_port: 106 | httpd_port = 443 if httpd_ssl else 80 107 | certfile = None 108 | if httpd_ssl and not certfile: 109 | print("Your callback url is over https, but no certificate is present.") 110 | print("Change the scheme to http (also over at Nokia!) or specify a certfile above.") 111 | exit(0) 112 | 113 | auth = nokia.NokiaAuth(options.key, options.secret, options.callback) 114 | authorize_url = auth.get_authorize_url() 115 | print("Visit: %s\nand select your user and click \"Allow this app\"." % authorize_url) 116 | 117 | if options.auth_serv: 118 | httpd = HTTPServer(('', httpd_port), AuthorizationRepsponseHandler) 119 | if httpd_ssl: 120 | httpd.socket = ssl.wrap_socket(httpd.socket, certfile=certfile, server_side=True) 121 | httpd.socket.settimeout(100) 122 | httpd.handle_request() 123 | else: 124 | print("After redirection to your callback url find the authorization code in the url.") 125 | print("Example: https://your_original_callback?code=abcdef01234&state=XFZ") 126 | print(" example value to copy: abcdef01234") 127 | nokia_auth_code = input('Please enter the authorization code: ') 128 | creds = auth.get_credentials(nokia_auth_code) 129 | 130 | if not config.has_section('nokia'): 131 | config.add_section('nokia') 132 | 133 | config.set('nokia', 'consumer_key', options.key) 134 | config.set('nokia', 'consumer_secret', options.secret) 135 | config.set('nokia', 'callback_uri', options.callback) 136 | config.set('nokia', 'access_token', creds.access_token) 137 | config.set('nokia', 'token_expiry', creds.token_expiry) 138 | config.set('nokia', 'token_type', creds.token_type) 139 | config.set('nokia', 'refresh_token', creds.refresh_token) 140 | config.set('nokia', 'user_id', creds.user_id) 141 | 142 | def setup_garmin( options, config ): 143 | """ Setup the Garmin Connect credentials 144 | """ 145 | 146 | if options.key is None: 147 | options.key = input('Please enter your Garmin Connect username: ') 148 | 149 | if options.secret is None: 150 | options.secret = getpass.getpass('Please enter your Garmin Connect password: ') 151 | 152 | # Test out our new powers 153 | garmin = GarminConnect() 154 | session = garmin.login(options.key, options.secret) 155 | 156 | if not config.has_section('garmin'): 157 | config.add_section('garmin') 158 | 159 | config.set('garmin', 'username', options.key) 160 | config.set('garmin', 'password', options.secret) 161 | 162 | def setup_smashrun( options, config ): 163 | """ Setup Smashrun API implicit user level authentication 164 | """ 165 | mobile = MobileApplicationClient('client') # implicit flow 166 | client = Smashrun(client_id='client',client=mobile,client_secret='my_secret',redirect_uri='https://httpbin.org/get') 167 | auth_url = client.get_auth_url() 168 | print("Go to '%s' and log into Smashrun. After redirection, copy the access_token from the url." % auth_url[0]) 169 | print("Example url: https://httpbin.org/get#access_token=____01234-abcdefghijklmnopABCDEFGHIJLMNOP01234567890&token_type=[...]") 170 | print("Example access_token: ____01234-abcdefghijklmnopABCDEFGHIJLMNOP01234567890") 171 | token = input("Please enter your access token: " ) 172 | if not config.has_section('smashrun'): 173 | config.add_section('smashrun') 174 | config.set('smashrun', 'token', urllib.parse.unquote(token)) 175 | config.set('smashrun', 'type', 'implicit') 176 | 177 | def setup_smashrun_code( options, config ): 178 | """ Setup Smashrun API explicit code flow (for applications) 179 | """ 180 | if options.key is None: 181 | print("To set a connection with Smashrun you need to request an API key at https://api.smashrun.com/register .") 182 | options.key = input('Please the client id: ') 183 | 184 | if options.secret is None: 185 | options.secret = input('Please enter the client secret: ') 186 | 187 | client = Smashrun(client_id=options.key,client_secret=options.secret,redirect_uri='urn:ietf:wg:oauth:2.0:auto') 188 | auth_url = client.get_auth_url() 189 | print("Go to '%s' and authorize this application." % auth_url[0]) 190 | code = input('Please enter your the code provided: ') 191 | resp = client.fetch_token(code=code) 192 | 193 | if not config.has_section('smashrun'): 194 | config.add_section('smashrun') 195 | 196 | config.set('smashrun', 'client_id', options.key) 197 | config.set('smashrun', 'client_secret', options.secret) 198 | config.set('smashrun', 'refresh_token', resp['refresh_token']) 199 | config.set('smashrun', 'type', 'code') 200 | 201 | def save_config(): 202 | # Encode the Garmin password 203 | if config.has_section('garmin'): 204 | if config.has_option('garmin', 'password'): 205 | config.set('garmin', 'password', base64.b64encode( config.get('garmin', 'password').encode('ascii') ).decode('ascii')) 206 | 207 | # New Nokia tokens (if refreshed) 208 | if client_nokia: 209 | creds = client_nokia.get_credentials() 210 | if config.get('nokia', 'access_token') is not creds.access_token: 211 | config.set('nokia', 'access_token', creds.access_token) 212 | config.set('nokia', 'token_expiry', creds.token_expiry) 213 | config.set('nokia', 'refresh_token', creds.refresh_token) 214 | 215 | with open(options.config, 'w') as f: 216 | config.write(f) 217 | f.close() 218 | 219 | print("Config file saved to %s" % options.config) 220 | 221 | def auth_nokia( config ): 222 | """ Authenticate client with Nokia Health 223 | """ 224 | creds = nokia.NokiaCredentials(config.get('nokia', 'access_token'), 225 | config.get('nokia', 'token_expiry'), 226 | config.get('nokia', 'token_type'), 227 | config.get('nokia', 'refresh_token'), 228 | config.get('nokia', 'user_id'), 229 | config.get('nokia', 'consumer_key'), 230 | config.get('nokia', 'consumer_secret') 231 | ) 232 | client = nokia.NokiaApi(creds) 233 | return client 234 | 235 | def auth_smashrun( config ): 236 | """ Authenticate client with Smashrun 237 | """ 238 | 239 | if config.get('smashrun', 'type') == 'code': 240 | client = Smashrun(client_id=config.get('smashrun', 'client_id'), 241 | client_secret=config.get('smashrun', 'client_secret')) 242 | client.refresh_token(refresh_token=config.get('smashrun', 'refresh_token')) 243 | else: 244 | mobile = MobileApplicationClient('client') # implicit flow 245 | client = Smashrun(client_id='client', client=mobile, 246 | token={'access_token':config.get('smashrun', 'token'),'token_type':'Bearer'}) 247 | return client 248 | 249 | client_nokia = None 250 | if command != 'setup': 251 | client_nokia = auth_nokia( config ) 252 | 253 | if command == 'setup': 254 | 255 | if len(args) == 1: 256 | service = args[0] 257 | else: 258 | print("You must provide the name of the service to setup. Available services are: nokia, garmin, smashrun, smashrun_code.") 259 | sys.exit(1) 260 | 261 | if service == 'nokia': 262 | setup_nokia( options, config ) 263 | elif service == 'garmin': 264 | setup_garmin( options, config ) 265 | elif service == 'smashrun': 266 | setup_smashrun( options, config ) 267 | elif service == 'smashrun_code': 268 | setup_smashrun_code( options, config ) 269 | else: 270 | print('Unknown service (%s), available services are: nokia, garmin, smashrun, smashrun_code.') 271 | sys.exit(1) 272 | 273 | elif command == 'userinfo': 274 | print(client_nokia.get_user()) 275 | 276 | elif command == 'last': 277 | m = client_nokia.get_measures(limit=1)[0] 278 | 279 | print(m.date) 280 | if len(args) == 1: 281 | types = dict(nokia.NokiaMeasureGroup.MEASURE_TYPES) 282 | print(m.get_measure(types[args[0]])) 283 | else: 284 | for n, t in nokia.NokiaMeasureGroup.MEASURE_TYPES: 285 | print("%s: %s" % (n.replace('_', ' ').capitalize(), m.get_measure(t))) 286 | 287 | elif command == 'lastn': 288 | if len(args) != 1: 289 | print("You must supply the number of measurement groups to fetch.") 290 | sys.exit(1) 291 | 292 | # Get n last measurements 293 | mall = client_nokia.get_measures(limit=args[0]) 294 | 295 | for n, m in enumerate(mall): 296 | # Print clear header and date for each group 297 | print("--Group %i" % n) 298 | print(m.date) 299 | 300 | # Print all types one by one 301 | for n, t in nokia.NokiaMeasureGroup.MEASURE_TYPES: 302 | print("%s: %s" % (n.replace('_', ' ').capitalize(), m.get_measure(t))) 303 | print("") 304 | 305 | elif command == 'sync-preview': 306 | if len(args) == 1: 307 | service = args[0] 308 | else: 309 | print("You must provide the name of the service to sync. Available services are: garmin, smashrun.") 310 | sys.exit(1) 311 | 312 | # Get next measurements 313 | last_sync = int(config.get(service,'last_sync')) if config.has_option(service, 'last_sync') else 0 314 | mall = client_nokia.get_measures(lastupdate=last_sync) 315 | 316 | for n, m in enumerate(mall): 317 | # Print clear header and date for each group 318 | print("--Group %i" % n) 319 | print(m.date) 320 | 321 | # Print all types one by one 322 | for n, t in nokia.NokiaMeasureGroup.MEASURE_TYPES: 323 | print("%s: %s" % (n.replace('_', ' ').capitalize(), m.get_measure(t))) 324 | print("") 325 | 326 | elif command == 'sync': 327 | 328 | if len(args) == 1: 329 | service = args[0] 330 | else: 331 | print("You must provide the name of the service to sync. Available services are: garmin, smashrun.") 332 | sys.exit(1) 333 | 334 | # Get next measurements 335 | last_sync = int(config.get(service,'last_sync')) if config.has_option(service, 'last_sync') else 0 336 | groups = client_nokia.get_measures(lastupdate=last_sync) 337 | types = dict(nokia.NokiaMeasureGroup.MEASURE_TYPES) 338 | 339 | if len(groups) == 0: 340 | print("Their is no new measurement to sync.") 341 | save_config() 342 | sys.exit(0); 343 | 344 | if service == 'garmin': 345 | 346 | next_sync = groups[-1].date.timestamp 347 | 348 | # Do not repeatidly sync the same value 349 | if next_sync == last_sync: 350 | print('Last measurement was already synced') 351 | save_config() 352 | sys.exit(0) 353 | 354 | # Get height for BMI calculation 355 | height = None 356 | m = client_nokia.get_measures(limit=1, meastype=types['height']) 357 | if len(m): 358 | height = m[0].get_measure(types['height']) 359 | 360 | # create fit file 361 | fit = FitEncoder_Weight() 362 | fit.write_file_info() 363 | fit.write_file_creator() 364 | fit.write_device_info(timestamp=next_sync) 365 | for m in groups: 366 | weight = m.get_measure(types['weight']); 367 | if weight: 368 | bmi = None 369 | if height: 370 | bmi = round(weight / pow(height, 2), 1) 371 | 372 | fit.write_weight_scale(timestamp=m.date.timestamp, weight=weight, percent_fat=m.get_measure(types['fat_ratio']), 373 | percent_hydration=m.get_measure(types['hydration']), bone_mass=m.get_measure(types['bone_mass']), muscle_mass=m.get_measure(types['muscle_mass']), 374 | bmi=bmi) 375 | 376 | fit.finish() 377 | 378 | garmin = GarminConnect() 379 | session = garmin.login(config.get('garmin','username'), config.get('garmin','password')) 380 | r = garmin.upload_file(fit.getvalue(), session) 381 | if r: 382 | print("%d weights has been successfully updated to Garmin!" % (len(groups))) 383 | config.set('garmin','last_sync', str(next_sync)) 384 | 385 | elif service == 'smashrun': 386 | 387 | for m in reversed(groups): 388 | t = types['weight'] 389 | weight = m.get_measure(t) 390 | if weight: 391 | break 392 | 393 | print("Last weight from Nokia Health: %s kg taken at %s" % (weight, m.date)) 394 | 395 | 396 | # Do not repeatidly sync the same value 397 | if config.has_option('smashrun', 'last_sync'): 398 | if m.date.timestamp == int(config.get('smashrun','last_sync')): 399 | print('Last measurement was already synced') 400 | save_config() 401 | sys.exit(0) 402 | 403 | client_smashrun = auth_smashrun( config ) 404 | 405 | resp = client_smashrun.create_weight( weight, m.date.format('YYYY-MM-DD') ) 406 | 407 | if resp.status_code == 200: 408 | print('Weight has been successfully updated to Smashrun!') 409 | config.set('smashrun','last_sync', str(m.date.timestamp)) 410 | 411 | else: 412 | print('Unknown service (%s), available services are: nokia, garmin, smashrun') 413 | save_config() 414 | sys.exit(1) 415 | 416 | elif command == 'subscribe': 417 | client_nokia.subscribe(args[0], args[1]) 418 | print("Subscribed %s" % args[0]) 419 | 420 | elif command == 'unsubscribe': 421 | client_nokia.unsubscribe(args[0]) 422 | print("Unsubscribed %s" % args[0]) 423 | 424 | elif command == 'list_subscriptions': 425 | l = client_nokia.list_subscriptions() 426 | if len(l) > 0: 427 | for s in l: 428 | print(" - %s " % s['comment']) 429 | else: 430 | print("No subscriptions") 431 | 432 | else: 433 | print("Unknown command") 434 | print("Available commands: setup, sync, sync-preview, last, userinfo, subscribe, unsubscribe, list_subscriptions") 435 | sys.exit(1) 436 | 437 | save_config() 438 | sys.exit(0) 439 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------