def _authenticate(self, attempts=RETRY_TOKEN, session=None, wait=1.0): """Authenticate user against Ring API.""" url = API_URI + NEW_SESSION_ENDPOINT loop = 0 # make a copy as we're mutating headers in the loop below # which would cause issues with _get_oauth_token() # which expects a non mutated HEADERS copy modified_headers = HEADERS.copy() while loop <= attempts: modified_headers['Authorization'] = \ 'Bearer {}'.format(self._get_oauth_token()) loop += 1 try: if session is None: req = self.session.post((url), data=POST_DATA, headers=modified_headers) else: req = session except requests.exceptions.RequestException as err_msg: _LOGGER.error("Error!! %s", err_msg) raise if not req: time.sleep(wait) # add a pause or you'll get rate limited continue # if token is expired, refresh credentials and try again if req.status_code == 200 or req.status_code == 201: # the only way to get a JSON with token is via POST, # so we need a special conditional for 201 code if req.status_code == 201: data = req.json().get('profile') self.token = data.get('authentication_token') self.is_connected = True self.params = {'api_version': API_VERSION, 'auth_token': self.token} if self._persist_token and self._push_token_notify_url: url = API_URI + PERSIST_TOKEN_ENDPOINT PERSIST_TOKEN_DATA['auth_token'] = self.token PERSIST_TOKEN_DATA['device[push_notification_token]'] = \ self._push_token_notify_url req = self.session.put((url), headers=modified_headers, data=PERSIST_TOKEN_DATA) # update token if reuse_session is True if self._reuse_session: self.cache['account'] = self.username self.cache['token'] = self.token _save_cache(self.cache, self.cache_file) return True self.is_connected = False req.raise_for_status() return True
def _update_alert(self): """Verify if alert received is still valid.""" # alert is no longer valid if self.alert and self.alert_expires_at: if datetime.now() >= self.alert_expires_at: self.alert = None self.alert_expires_at = None _save_cache(self._ring.cache, self._ring.cache_file)
def _authenticate(self, attempts=RETRY_TOKEN, session=None): """Authenticate user against Ring API.""" url = API_URI + NEW_SESSION_ENDPOINT loop = 0 while loop <= attempts: loop += 1 try: if session is None: req = self.session.post((url), data=POST_DATA, headers=HEADERS) else: req = session except requests.exceptions.RequestException as err_msg: _LOGGER.error("Error!! %s", err_msg) raise if not req: continue # if token is expired, refresh credentials and try again if req.status_code == 200 or req.status_code == 201: # the only way to get a JSON with token is via POST, # so we need a special conditional for 201 code if req.status_code == 201: data = req.json().get('profile') self.token = data.get('authentication_token') self.is_connected = True self.params = { 'api_version': API_VERSION, 'auth_token': self.token } if self._persist_token and self._push_token_notify_url: url = API_URI + PERSIST_TOKEN_ENDPOINT PERSIST_TOKEN_DATA['auth_token'] = self.token PERSIST_TOKEN_DATA['device[push_notification_token]'] = \ self._push_token_notify_url req = self.session.put((url), headers=HEADERS, data=PERSIST_TOKEN_DATA) # update token if reuse_session is True if self._reuse_session: self.cache['account'] = self.username self.cache['token'] = self.token _save_cache(self.cache, self.cache_file) return True self.is_connected = False req.raise_for_status()
def _authenticate(self, attempts=RETRY_TOKEN, session=None): """Authenticate user against Ring API.""" url = API_URI + NEW_SESSION_ENDPOINT loop = 0 while loop <= attempts: loop += 1 try: if session is None: req = self.session.post((url), data=POST_DATA, headers=HEADERS) else: req = session except: raise # if token is expired, refresh credentials and try again if req.status_code == 200 or req.status_code == 201: # the only way to get a JSON with token is via POST, # so we need a special conditional for 201 code if req.status_code == 201: data = req.json().get('profile') self.token = data.get('authentication_token') self.is_connected = True self.params = {'api_version': API_VERSION, 'auth_token': self.token} if self._persist_token and self._push_token_notify_url: url = API_URI + PERSIST_TOKEN_ENDPOINT PERSIST_TOKEN_DATA['auth_token'] = self.token PERSIST_TOKEN_DATA['device[push_notification_token]'] = \ self._push_token_notify_url req = self.session.put((url), headers=HEADERS, data=PERSIST_TOKEN_DATA) # update token if reuse_session is True if self._reuse_session: self.cache['account'] = self.username self.cache['token'] = self.token _save_cache(self.cache, self.cache_file) return True self.is_connected = False req.raise_for_status()
def check_alerts(self): """Return JSON when motion or ring is detected.""" url = API_URI + DINGS_ENDPOINT self.update() try: resp = self._ring.query(url)[0] except (IndexError, TypeError): return None if resp: timestamp = resp.get('now') + resp.get('expires_in') self.alert = resp self.alert_expires_at = datetime.fromtimestamp(timestamp) # save to a pickle data if self.alert: _save_cache(self._ring.cache, self._ring.cache_file) return True return None
def test_read_cache_dict(self): """Test _read_cache with expected dict.""" self.assertTrue(_save_cache(CACHE_ATTRS, CACHE)) self.assertIsInstance(_read_cache(CACHE), dict) os.remove(CACHE)
def test_read_cache(self): """Test _read_cache method.""" self.assertTrue(_save_cache(DATA, CACHE)) self.assertIsInstance(_read_cache(CACHE), dict) os.remove(CACHE)
def test_exists_cache(self): """Test _exists_cache method.""" self.assertTrue(_save_cache(DATA, CACHE)) self.assertTrue(_exists_cache(CACHE)) os.remove(CACHE)
def test_initiliaze_clean_cache(self): """Test _clean_cache method.""" self.assertTrue(_save_cache(DATA, CACHE)) self.assertIsInstance(_clean_cache(CACHE), dict) os.remove(CACHE)
def alert(self, value): """Set attribute to alert.""" self._ring.cache['alerts'] = value _save_cache(self._ring.cache, self._ring.cache_file) return True