def getAccountSettings(self, force): _interval = (60 * 60 * 24 * 7) - (60 * 60) # one week less one hour _next = getSettingAsInt('xbmcfilm_settings_last') + _interval stale = force if force: Debug("[XbmcFilm] Forcing a reload of settings from xbmcfilm.tv.") if not stale and time.time() >= _next: Debug("[XbmcFilm] xbmcfilm.tv account settings are stale, reloading.") stale = True if stale: if self.testAccount(): Debug("[XbmcFilm] Getting account settings for '%s'." % self.__username) url = "%s/account/settings/%s" % (self.__baseURL, self.__apikey) Debug("[XbmcFilm] getAccountSettings(url: %s)" % url) response = self.xbmcfilmRequest('POST', url, hideResponse=True) if response and 'status' in response: if response['status'] == 'success': del response['status'] setSetting('xbmcfilm_settings', json.dumps(response)) setSetting('xbmcfilm_settings_last', int(time.time())) self.settings = response else: Debug("[XbmcFilm] Loaded cached account settings for '%s'." % self.__username) s = getSetting('xbmcfilm_settings') self.settings = json.loads(s)
def getAccountSettings(self, force=False): _interval = (60 * 60 * 24 * 7) - (60 * 60) # one week less one hour _next = getSettingAsInt('trakt_settings_last') + _interval stale = force if force: Debug("[traktAPI] Forcing a reload of settings from trakt.tv.") if not stale and time.time() >= _next: Debug("[traktAPI] trakt.tv account settings are stale, reloading.") stale = True if stale: if self.testAccount(): Debug("[traktAPI] Getting account settings for '%s'." % self.__username) url = "%s/account/settings/%s" % (self.__baseURL, self.__apikey) Debug("[traktAPI] getAccountSettings(url: %s)" % url) response = self.traktRequest('POST', url, hideResponse=True) if response and 'status' in response: if response['status'] == 'success': del response['status'] setSetting('trakt_settings', json.dumps(response)) setSetting('trakt_settings_last', int(time.time())) self.settings = response else: Debug("[traktAPI] Loaded cached account settings for '%s'." % self.__username) s = getSetting('trakt_settings') self.settings = json.loads(s)
def updateSettings(self): if getSetting('authorization'): _auth = loads(getSetting('authorization')) else: _auth = {} if self.authorization != _auth: self.authorization = _auth user = self.getUser() if user and 'user' in user: setSetting('user', user['user']['username']) else: setSetting('user', '')
def authenticate(self, pin=None): # Attempt authentication (retrieve new token) with Trakt.configuration.http(retry=True): try: # Exchange `code` for `access_token` logger.debug("Exchanging pin for access token") self.authorization = Trakt['oauth'].token_exchange(pin, 'urn:ietf:wg:oauth:2.0:oob') if not self.authorization: logger.debug("Authentication Failure") return False else: setSetting('authorization', dumps(self.authorization)) return True except Exception as ex: message = createError(ex) logger.fatal(message) logger.debug("Cannot connect to server") notification('Trakt', getString(32023))
def onClick(self, control): #print 'onClick: %s' % (control) logger.debug('onClick: %s' % (control)) if control == AUTH_BUTTON: if not self.__get_token(): logger.debug("Authentification error") notification(getString(32157), getString(32147), 5000) return self.auth = True if control == LATER_BUTTON: notification(getString(32157), getString(32150), 5000) setSetting('last_reminder', str(int(time.time()))) if control == NEVER_BUTTON: notification(getString(32157), getString(32151), 5000) setSetting('last_reminder', '-1') if control in [AUTH_BUTTON, LATER_BUTTON, NEVER_BUTTON]: self.close()
def authenticate(self, pin=None): # Attempt authentication (retrieve new token) with Trakt.configuration.http(retry=True): try: # Exchange `code` for `access_token` logger.debug("Exchanging pin for access token") self.authorization = Trakt['oauth'].token_exchange( pin, 'urn:ietf:wg:oauth:2.0:oob') if not self.authorization: logger.debug("Authentication Failure") return False else: setSetting('authorization', dumps(self.authorization)) return True except Exception as ex: message = createError(ex) logger.fatal(message) logger.debug("Cannot connect to server") notification('Trakt', getString(32023))
def testAccount(self, force=False): if self.__username == "": notification('trakt', getString( 1106)) # please enter your Username and Password in settings setSetting('account_valid', False) return False elif self.__password == "": notification( "trakt", getString(1107)) # please enter your Password in settings setSetting('account_valid', False) return False if not getSettingAsBool('account_valid') or force: Debug("[traktAPI] Testing account '%s'." % self.__username) url = "%s/account/test/%s" % (self.__baseURL, self.__apikey) Debug("[traktAPI] testAccount(url: %s)" % url) args = json.dumps({ 'username': self.__username, 'password': self.__password }) response = None try: # get data from trakt.tv response = self.__getData(url, args) except traktError, e: if isinstance(e, traktAuthProblem): Debug( "[traktAPI] testAccount(): Account '%s' failed authentication. (%s)" % (self.__username, e.value)) elif isinstance(e, traktServerBusy): Debug("[traktAPI] testAccount(): Server Busy (%s)" % e.value) elif isinstance(e, traktNetworkError): Debug("[traktAPI] testAccount(): Network error: %s" % e.value) elif isinstance(e, traktUnknownError): Debug("[traktAPI] testAccount(): Other problem (%s)" % e.value) else: pass if response: data = None try: data = json.loads(response) except ValueError: pass if 'status' in data: if data['status'] == 'success': setSetting('account_valid', True) Debug( "[traktAPI] testAccount(): Account '%s' is valid." % self.__username) return True
def testAccount(self, force=False): if self.__username == "": notification('trakt', getString(1106)) # please enter your Username and Password in settings setSetting('account_valid', False) return False elif self.__password == "": notification("trakt", getString(1107)) # please enter your Password in settings setSetting('account_valid', False) return False if not getSettingAsBool('account_valid') or force: Debug("[traktAPI] Testing account '%s'." % self.__username) url = "%s/account/test/%s" % (self.__baseURL, self.__apikey) Debug("[traktAPI] testAccount(url: %s)" % url) args = json.dumps({'username': self.__username, 'password': self.__password}) response = None try: # get data from trakt.tv response = self.__getData(url, args) except traktError, e: if isinstance(e, traktAuthProblem): Debug("[traktAPI] testAccount(): Account '%s' failed authentication. (%s)" % (self.__username, e.value)) elif isinstance(e, traktServerBusy): Debug("[traktAPI] testAccount(): Server Busy (%s)" % e.value) elif isinstance(e, traktNetworkError): Debug("[traktAPI] testAccount(): Network error: %s" % e.value) elif isinstance(e, traktUnknownError): Debug("[traktAPI] testAccount(): Other problem (%s)" % e.value) else: pass if response: data = None try: data = json.loads(response) except ValueError: pass if 'status' in data: if data['status'] == 'success': setSetting('account_valid', True) Debug("[traktAPI] testAccount(): Account '%s' is valid." % self.__username) return True
def traktRequest(self, method, url, args=None, returnStatus=False, returnOnFailure=False, silent=True, passVersions=False, hideResponse=False): raw = None data = None jdata = {} retries = getSettingAsInt('retries') if args is None: args = {} if not (method == 'POST' or method == 'GET'): Debug("[traktAPI] traktRequest(): Unknown method '%s'." % method) return None if method == 'POST': # debug log before username and sha1hash are injected Debug("[traktAPI] traktRequest(): Request data: '%s'." % str(json.dumps(args))) # inject username/pass into json data args['username'] = self.__username args['password'] = self.__password # check if plugin version needs to be passed if passVersions: args['plugin_version'] = __addonversion__ args['media_center_version'] = xbmc.getInfoLabel( 'system.buildversion') args['media_center_date'] = xbmc.getInfoLabel( 'system.builddate') # convert to json data jdata = json.dumps(args) Debug( "[traktAPI] traktRequest(): Starting retry loop, maximum %i retries." % retries) # start retry loop for i in range(retries): Debug("[traktAPI] traktRequest(): (%i) Request URL '%s'" % (i, url)) # check if we are closing if xbmc.abortRequested: Debug("[traktAPI] traktRequest(): (%i) xbmc.abortRequested" % i) break try: # get data from trakt.tv raw = self.__getData(url, jdata) except traktError, e: if isinstance(e, traktServerBusy): Debug("[traktAPI] traktRequest(): (%i) Server Busy (%s)" % (i, e.value)) xbmc.sleep(5000) elif isinstance(e, traktAuthProblem): Debug( "[traktAPI] traktRequest(): (%i) Authentication Failure (%s)" % (i, e.value)) setSetting('account_valid', False) notification('trakt', getString(1110)) return elif isinstance(e, traktNetworkError): Debug("[traktAPI] traktRequest(): (%i) Network error: %s" % (i, e.value)) if e.timeout: notification('trakt', getString(1108) + " (timeout)") # can't connect to trakt xbmc.sleep(5000) elif isinstance(e, traktUnknownError): Debug( "[traktAPI] traktRequest(): (%i) Other problem (%s)" % (i, e.value)) else: pass xbmc.sleep(1000) continue # check if we are closing if xbmc.abortRequested: Debug("[traktAPI] traktRequest(): (%i) xbmc.abortRequested" % i) break # check that returned data is not empty if not raw: Debug("[traktAPI] traktRequest(): (%i) JSON Response empty" % i) xbmc.sleep(1000) continue try: # get json formatted data data = json.loads(raw) if hideResponse: Debug( "[traktAPI] traktRequest(): (%i) JSON response recieved, response not logged" % i) else: Debug( "[traktAPI] traktRequest(): (%i) JSON response: '%s'" % (i, str(data))) except ValueError: # malformed json response Debug( "[traktAPI] traktRequest(): (%i) Bad JSON response: '%s'" % (i, raw)) if not silent: notification('trakt', getString(1109) + ": Bad response from trakt") # Error # check for the status variable in JSON data if data and 'status' in data: if data['status'] == 'success': break elif returnOnFailure and data['status'] == 'failure': Debug( "[traktAPI] traktRequest(): Return on error set, breaking retry." ) break elif 'error' in data and data['status'] == 'failure': Debug( "[traktAPI] traktRequest(): (%i) JSON Error '%s' -> '%s'" % (i, data['status'], data['error'])) xbmc.sleep(1000) continue else: pass # check to see if we have data, an empty array is still valid data, so check for None only if not data is None: Debug( "[traktAPI] traktRequest(): Have JSON data, breaking retry." ) break xbmc.sleep(500)
pass if 'status' in data: if data['status'] == 'success': setSetting('account_valid', True) Debug( "[traktAPI] testAccount(): Account '%s' is valid." % self.__username) return True else: return True notification('trakt', getString(1110)) # please enter your Password in settings setSetting('account_valid', False) return False # url: http://api.trakt.tv/account/settings/<apikey> # returns: all settings for authenticated user def getAccountSettings(self, force=False): _interval = (60 * 60 * 24 * 7) - (60 * 60) # one week less one hour _next = getSettingAsInt('trakt_settings_last') + _interval stale = force if force: Debug("[traktAPI] Forcing a reload of settings from trakt.tv.") if not stale and time.time() >= _next: Debug("[traktAPI] trakt.tv account settings are stale, reloading.")
def traktRequest(self, method, url, args=None, returnStatus=False, returnOnFailure=False, silent=True, passVersions=False, hideResponse=False): raw = None data = None jdata = {} retries = getSettingAsInt('retries') if args is None: args = {} if not (method == 'POST' or method == 'GET'): Debug("[traktAPI] traktRequest(): Unknown method '%s'." % method) return None if method == 'POST': # debug log before username and sha1hash are injected Debug("[traktAPI] traktRequest(): Request data: '%s'." % str(json.dumps(args))) # inject username/pass into json data args['username'] = self.__username args['password'] = self.__password # check if plugin version needs to be passed if passVersions: args['plugin_version'] = __addonversion__ args['media_center_version'] = xbmc.getInfoLabel('system.buildversion') args['media_center_date'] = xbmc.getInfoLabel('system.builddate') # convert to json data jdata = json.dumps(args) Debug("[traktAPI] traktRequest(): Starting retry loop, maximum %i retries." % retries) # start retry loop for i in range(retries): Debug("[traktAPI] traktRequest(): (%i) Request URL '%s'" % (i, url)) # check if we are closing if xbmc.abortRequested: Debug("[traktAPI] traktRequest(): (%i) xbmc.abortRequested" % i) break try: # get data from trakt.tv raw = self.__getData(url, jdata) except traktError, e: if isinstance(e, traktServerBusy): Debug("[traktAPI] traktRequest(): (%i) Server Busy (%s)" % (i, e.value)) elif isinstance(e, traktAuthProblem): Debug("[traktAPI] traktRequest(): (%i) Authentication Failure (%s)" % (i, e.value)) setSetting('account_valid', False) notification('trakt', getString(1110)) return elif isinstance(e, traktNetworkError): Debug("[traktAPI] traktRequest(): (%i) Network error: %s" % (i, e.value)) if e.timeout: notification('trakt', getString(1108) + " (timeout)") # can't connect to trakt xbmc.sleep(5000) elif isinstance(e, traktUnknownError): Debug("[traktAPI] traktRequest(): (%i) Other problem (%s)" % (i, e.value)) else: pass xbmc.sleep(1000) continue # check if we are closing if xbmc.abortRequested: Debug("[traktAPI] traktRequest(): (%i) xbmc.abortRequested" % i) break # check that returned data is not empty if not raw: Debug("[traktAPI] traktRequest(): (%i) JSON Response empty" % i) xbmc.sleep(1000) continue try: # get json formatted data data = json.loads(raw) if hideResponse: Debug("[traktAPI] traktRequest(): (%i) JSON response recieved, response not logged" % i) else: Debug("[traktAPI] traktRequest(): (%i) JSON response: '%s'" % (i, str(data))) except ValueError: # malformed json response Debug("[traktAPI] traktRequest(): (%i) Bad JSON response: '%s'", (i, raw)) if not silent: notification('trakt', getString(1109) + ": Bad response from trakt") # Error # check for the status variable in JSON data if 'status' in data: if data['status'] == 'success': break elif returnOnFailure and data['status'] == 'failure': Debug("[traktAPI] traktRequest(): Return on error set, breaking retry.") break else: Debug("[traktAPI] traktRequest(): (%i) JSON Error '%s' -> '%s'" % (i, data['status'], data['error'])) xbmc.sleep(1000) continue # check to see if we have data, an empty array is still valid data, so check for None only if not data is None: Debug("[traktAPI] traktRequest(): Have JSON data, breaking retry.") break xbmc.sleep(500)
try: data = json.loads(response) except ValueError: pass if 'status' in data: if data['status'] == 'success': setSetting('account_valid', True) Debug("[traktAPI] testAccount(): Account '%s' is valid." % self.__username) return True else: return True notification('trakt', getString(1110)) # please enter your Password in settings setSetting('account_valid', False) return False # url: http://api.trakt.tv/account/settings/<apikey> # returns: all settings for authenticated user def getAccountSettings(self): if self.testAccount(): url = "%s/account/settings/%s" % (self.__baseURL, self.__apikey) Debug("[traktAPI] getAccountSettings(url: %s)" % url) response = self.traktRequest('POST', url, hideResponse=True) if response: if 'status' in response: if response['status'] == 'success': self.settings = response # url: http://api.trakt.tv/<show|movie>/watching/<apikey>
def on_token_refreshed(self, response): # OAuth token refreshed, save token for future calls self.authorization = response setSetting('authorization', dumps(self.authorization)) logger.debug('Token refreshed')