Beispiel #1
0
    def __init__(self, log, api_id, api_secret, period, dataPath):
        try:
            """
            Create a withing instance, allowing to use withing api
            """
            self._log = log
            self.api_id = api_id
            self.api_secret = api_secret
            self.period = period
	    self._sensors = []

	    self._dataPath = dataPath 

            if not os.path.exists(self._dataPath) :
                self._log.info(u"Directory data not exist, trying create : %s" , self._dataPath)
                try :
                    os.mkdir(self._dataPath)
                    self._log.info(u"Withings data directory created : %s"  %self._dataPath)
                except Exception as e:
                    self._log.error(e.message)
                    raise withingException ("Withings data directory not exist : %s" % self._dataPath)
	    if not os.access(self._dataPath, os.W_OK) :
                self._log.error("User %s haven't write access on data directory : %s"  %(user,  self._dataPath))
    	        raise withingException ("User %s haven't write access on data directory : %s"  %(user,  self._dataPath))

            self.withing_config_file = os.path.join(os.path.dirname(__file__), '../data/withings.json')
	    self.auth = WithingsAuth(self.api_id, self.api_secret)
#	    self.open_token(self.auth)

            try:
    	        with open(self.withing_config_file, 'r') as withing_token_file:
                    self._log.debug(u"Opening File")
                    self.creds = pickle.load(withing_token_file)
                    self._log.debug(u"Getting user")
		    self.client = WithingsApi(self.creds)
		    self.user = self.client.get_user()
                    if self.user == None :
                        self.auth = WithingsAuth(self.api_key, self.api_secret)
		        self.authorize_url = self.auth.get_authorize_url()
		        print("Go to %s allow the app and copy your oauth_verifier" %self.authorize_url)
		        self.oauth_verifier = raw_input('Please enter your oauth_verifier: ')
		        self.creds = auth.get_credentials(self.oauth_verifier)
		        self.client = WithingsApi(creds)
		        self.user = self.client.get_user()
                        if user == None :
                            self._log.error(u"Error getting user, from code")
                            self._log.error(error)
                            sys.exit("refreshing token failed from refresh_token")
                            #TODO stop plugin
                        else :
                            self._log.warning(u"Token succesfully refresh with token_refresh from file")
                with open(self.withing_config_file, 'w') as withing_token_file:
                    pickle.dump(self.creds, withing_token_file)

            except ValueError:
                self._log.error(u"error reading Withing.")
                return
        except ValueError:
            self._log.error(u"error reading Withing.")
Beispiel #2
0
def withings_connect(client, oauth_verifier, oauth_token, oauth_secret):
    try:
        healthdevice = client.health_device
    except:
        healthdevice = HealthDevice(client=client)
    auth = WithingsAuth(WITHINGS_SETTINGS['CONSUMER_KEY'],
                        WITHINGS_SETTINGS['CONSUMER_SECRET'],
                        withings_get_callback_uri())
    auth.oauth_token = oauth_token
    auth.oauth_secret = oauth_secret
    print(oauth_verifier, oauth_token, oauth_secret)
    creds = auth.get_credentials(oauth_verifier)
    try:
        healthdevice = client.health_device
    except:
        healthdevice = HealthDevice(client=client)
    healthdevice.provider = HealthDevice.ProviderType.WITHINGS.value
    healthdevice.access_token = creds.access_token
    healthdevice.refresh_token = ''
    healthdevice.expires_at = datetime.now() + timedelta(days=365)
    healthdevice.meta = {
        'access_token_secret': creds.access_token_secret,
        'user_id': creds.user_id
    }
    healthdevice.save()
    return True
Beispiel #3
0
def withings_authorize_url(client):
    auth = WithingsAuth(WITHINGS_SETTINGS['CONSUMER_KEY'],
                        WITHINGS_SETTINGS['CONSUMER_SECRET'],
                        withings_get_callback_uri())
    authorize_url = auth.get_authorize_url()
    auth.oauth_token
    auth.oauth_secret
 def test_attribute_defaults(self):
     """ Make sure WithingsAuth attributes have the proper defaults """
     self.assertEqual(WithingsAuth.URL,
                      'https://oauth.withings.com/account')
     auth = WithingsAuth(self.consumer_key, self.consumer_secret)
     self.assertEqual(auth.oauth_token, None)
     self.assertEqual(auth.oauth_secret, None)
Beispiel #5
0
    def open_token(self, auth):
            try:
    	        with open(withing_config_file, 'r') as withing_token_file:
                    self._log.debug(u"Opening File")
                    self.creds = pickle.load(withing_token_file)
                    self._log.debug(u"Getting user")
		    self.client = WithingsApi(self.creds)
		    self.user = self.client.get_user()
                    if user == None :
                        self.auth = WithingsAuth(self.api_key, self.api_secret)
		        self.authorize_url = self.auth.get_authorize_url()
		        print("Go to %s allow the app and copy your oauth_verifier" %self.authorize_url)
		        self.oauth_verifier = raw_input('Please enter your oauth_verifier: ')
		        self.creds = auth.get_credentials(self.oauth_verifier)
		        self.client = WithingsApi(creds)
		        self.user = self.client.get_user()
                        if user == None :
                            self._log.error(u"Error getting user, from code")
                            self._log.error(error)
                            sys.exit("refreshing token failed from refresh_token")
                            #TODO stop plugin
                        else :
                            self._log.warning(u"Token succesfully refresh with token_refresh from file")
                with open(withing_config_file, 'w') as withing_token_file:
                    pickle.dump(self.creds, withing_token_file)

            except:
                self._log.error(u"Error with file saved or no file saved")
                self._log.error(u"Go to Advanced page to generate a new token file")
 def test_attributes(self):
     """ Make sure the WithingsAuth objects have the right attributes """
     assert hasattr(WithingsAuth, 'URL')
     auth = WithingsAuth(self.consumer_key, self.consumer_secret)
     assert hasattr(auth, 'consumer_key')
     self.assertEqual(auth.consumer_key, self.consumer_key)
     assert hasattr(auth, 'consumer_secret')
     self.assertEqual(auth.consumer_secret, self.consumer_secret)
def withings_redirect(request):
    auth = WithingsAuth(WITHINGS_SETTINGS['CONSUMER_KEY'],
                        WITHINGS_SETTINGS['CONSUMER_SECRET'],
                        healthdevice.withings_get_callback_uri())
    authorize_url = auth.get_authorize_url()
    request.session['withings_oauth_token'] = auth.oauth_token
    request.session['withings_oauth_secret'] = auth.oauth_secret
    context = {'authorize_url': authorize_url}
    return render(request, 'healthdevices/oauth_redirect.html', context)
 def test_get_authorize_url(self):
     """ Make sure the get_authorize_url function works as expected """
     auth = WithingsAuth(self.consumer_key, self.consumer_secret)
     # Returns the OAuth1Session.authorization_url results
     self.assertEqual(auth.get_authorize_url(), 'URL')
     # oauth_token and oauth_secret have now been set to the values
     # returned by OAuth1Session.fetch_request_token
     self.assertEqual(auth.oauth_token, 'fake_oauth_token')
     self.assertEqual(auth.oauth_secret, 'fake_oauth_token_secret')
Beispiel #9
0
def getWithingsClient():
    auth = WithingsAuth(CONSUMER_KEY, CONSUMER_SECRET)
    authorize_url = auth.get_authorize_url()
    print "Go to %s allow the app and copy your oauth_verifier" % authorize_url

    oauth_verifier = raw_input('Please enter your oauth_verifier: ')
    creds = auth.get_credentials(oauth_verifier)

    client = WithingsApi(creds)
    return client
 def test_get_credentials(self):
     """ Make sure the get_credentials function works as expected """
     auth = WithingsAuth(self.consumer_key, self.consumer_secret)
     # Returns an authorized WithingsCredentials object
     creds = auth.get_credentials('FAKE_OAUTH_VERIFIER')
     assert isinstance(creds, WithingsCredentials)
     # Check that the attributes of the WithingsCredentials object are
     # correct.
     self.assertEqual(creds.access_token, 'fake_oauth_token')
     self.assertEqual(creds.access_token_secret, 'fake_oauth_token_secret')
     self.assertEqual(creds.consumer_key, self.consumer_key)
     self.assertEqual(creds.consumer_secret, self.consumer_secret)
     self.assertEqual(creds.user_id, 'FAKEID')
Beispiel #11
0
# copied from https://github.com/maximebf/python-withings/blob/master/README.md

from withings import WithingsAuth, WithingsApi
from settings import CONSUMER_KEY, CONSUMER_SECRET

auth = WithingsAuth(CONSUMER_KEY, CONSUMER_SECRET)
authorize_url = auth.get_authorize_url()
print "Go to %s allow the app and copy your oauth_verifier" % authorize_url

oauth_verifier = raw_input('Please enter your oauth_verifier: ')
creds = auth.get_credentials(oauth_verifier)

client = WithingsApi(creds)
measures = client.get_measures(limit=1)
print "Your last measured weight: %skg" % measures[0].weight
def get_auth(CONSUMER_KEY,CONSUMER_SECRET):
    auth = WithingsAuth(CONSUMER_KEY, CONSUMER_SECRET)
    with open(withing_temp_file, 'w') as withing_auth_file:
        pickle.dump(auth, withing_auth_file)
    return auth