def login(self): #get session token self.log('Getting session token...') session = requests.Session() html = session.get(self.base_url).text self.token = bs(html).find('input', {'type': 'hidden'})['value'] control.set_setting('tvm_token', self.token) #login to tvmaze payload = { '_csrf': self.token, 'LoginForm[password]': self.password, 'LoginForm[username]': self.username, 'LoginForm[rememberMe]': '0', 'LoginForm[rememberMe]': '1' } check = session.post(self.base_url, data=payload) check = ((check.text).encode('ascii', 'ignore')) if 'Unknown username/email' in check: self.log('Unknown username/email') self.login_error = True self.login_message = 'Unknown username/email' elif 'Incorrect password' in check: self.log('Incorrect password') self.login_error = True self.login_message = 'Incorrect password' else: self.login_error = False self.login_message = 'Logged in successfully' with open(COOKIE, 'wb') as f: pickle.dump(session.cookies, f)
def onClick(self, control2): print 'onClick: %s' % (control2) if control2 == AUTH_BUTTON: if not self.__get_token(): control.infoDialog('Trakt PIN Authorization Failed.', 'Trakt ERROR') return self.auth = True self.close() if control2 == LATER_BUTTON: control.infoDialog(control.lang(32157) + control.lang(32150)) control.set_setting('last_reminder', str(int(time.time()))) if control == NEVER_BUTTON: control.infoDialog(control.lang(32157) + control.lang(32151)) control.set_setting('last_reminder', '-1') if control in [AUTH_BUTTON, LATER_BUTTON, NEVER_BUTTON]: self.close()
def __get_token(self): pin = self.pin_edit_control.getText().strip() print("PIN", pin) if pin: try: trakt_api = TraktAPI2(use_https=False, timeout=300) result = trakt_api.get_token(pin=pin) print("---", result) control.set_setting('trakt_oauth_token', result['access_token']) control.set_setting('trakt_refresh_token', result['refresh_token']) TOKEN = result['access_token'] trakt_api = TraktAPI2(TOKEN, use_https=False, timeout=300) profile = trakt_api.get_user_profile(cached=False) print("Profile", profile) print("Profile", profile['username']) control.set_setting('trakt_user', profile['username']) control.infoDialog('Trakt Authorization Success !', 'Trakt Success') return True except Exception as e: print('Trakt Authorization Failed: %s') % (e) control.infoDialog('Trakt Authorization Failed: ' + str(e), 'Trakt ERROR') return False return False
def __get_token(self): pin = self.pin_edit_control.getText().strip() print("PIN",pin) if pin: try: trakt_api = TraktAPI2(use_https=False, timeout=300) result = trakt_api.get_token(pin=pin) print("---",result) control.set_setting('trakt_oauth_token', result['access_token']) control.set_setting('trakt_refresh_token', result['refresh_token']) TOKEN = result['access_token'] trakt_api = TraktAPI2(TOKEN, use_https=False, timeout=300) profile = trakt_api.get_user_profile(cached=False) print("Profile",profile) print("Profile",profile['username']) control.set_setting('trakt_user', profile['username']) control.infoDialog('Trakt Authorization Success !', 'Trakt Success') return True except Exception as e: print('Trakt Authorization Failed: %s') % (e) control.infoDialog('Trakt Authorization Failed: '+str(e), 'Trakt ERROR') return False return False
def __call_trakt(self, url, method=None, data=None, params=None, auth=True, cache_limit=.25, cached=True): res_headers = {} #if not cached: cache_limit = 0 #db_cache_limit = cache_limit if cache_limit > 8 else 8 json_data = json.dumps(data) if data else None headers = {'Content-Type': 'application/json', 'trakt-api-key': V2_API_KEY, 'trakt-api-version': 2} url = '%s%s%s' % (self.protocol, BASE_URL, url) if params: url = url + '?' + urllib.urlencode(params) #db_connection = DB_Connection() #created, cached_headers, cached_result = db_connection.get_cached_url(url, json_data, db_cache_limit) #if cached_result and (time.time() - created) < (60 * 60 * cache_limit): # result = cached_result # res_headers = dict(cached_headers) # log_utils.log('Got cached result for: %s' % (url), log_utils.LOGDEBUG) auth_retry = False while True: try: if auth: headers.update({'Authorization': 'Bearer %s' % (self.token)}) print('Trakt Call: %s, header: %s, data: %s cache_limit: %s cached: %s') % (url, headers, data, cache_limit, cached) request = urllib2.Request(url, data=json_data, headers=headers) if method is not None: request.get_method = lambda: method.upper() response = urllib2.urlopen(request, timeout=self.timeout) result = '' while True: data = response.read() if not data: break result += data res_headers = dict(response.info().items()) #db_connection.cache_url(url, result, json_data, response.info().items()) break except (ssl.SSLError, socket.timeout) as e: control.infoDialog('Temporary Trakt Error: ' + str(e), "Trakt ERROR") raise TransientTraktError('Temporary Trakt Error: ' + str(e)) except urllib2.URLError as e: if isinstance(e, urllib2.HTTPError): if e.code in TEMP_ERRORS: control.infoDialog('Temporary Trakt Error: ' + str(e),"Trakt ERROR") raise TransientTraktError('Temporary Trakt Error: ' + str(e)) elif e.code == 401 or e.code == 405: # token is fine, profile is private if e.info().getheader('X-Private-User') == 'true': control.infoDialog('Object is No Longer Available (%s)' % (e.code),"Trakt ERROR") raise TraktAuthError('Object is No Longer Available (%s)' % (e.code)) # auth failure retry or a token request elif auth_retry or url.endswith('/token'): self.token = None control.set_setting('trakt_oauth_token', '') control.set_setting('trakt_refresh_token', '') control.infoDialog('Trakt Call Authentication Failed (%s)' % (e.code),"Trakt ERROR") raise TraktAuthError('Trakt Call Authentication Failed (%s)' % (e.code)) # first try token fail, try to refresh token else: result = self.get_token() self.token = result['access_token'] control.set_setting('trakt_oauth_token', result['access_token']) control.set_setting('trakt_refresh_token', result['refresh_token']) auth_retry = True elif e.code == 404: control.infoDialog('Object Not Found (%s)' % (e.code), "Trakt ERROR") raise TraktNotFoundError('Object Not Found (%s)' % (e.code)) else: raise elif isinstance(e.reason, socket.timeout) or isinstance(e.reason, ssl.SSLError): control.infoDialog('Temporary Trakt Error: ' + str(e),"Trakt ERROR") raise TransientTraktError('Temporary Trakt Error: ' + str(e)) else: control.infoDialog('Trakt Error: ' + str(e), "Trakt ERROR") raise TraktError('Trakt Error: ' + str(e)) except: raise try: js_data = json.loads(result) if 'x-sort-by' in res_headers and 'x-sort-how' in res_headers: js_data = utils2.sort_list(res_headers['x-sort-by'], res_headers['x-sort-how'], js_data) except ValueError: js_data = '' if result: print('Invalid JSON Trakt API Response: %s - |%s|' % (url, js_data)) print('Trakt Response: %s' % (response)) return js_data
def __call_trakt(self, url, method=None, data=None, params=None, auth=True, cache_limit=0.25, cached=True): res_headers = {} # if not cached: cache_limit = 0 # db_cache_limit = cache_limit if cache_limit > 8 else 8 json_data = json.dumps(data) if data else None headers = {"Content-Type": "application/json", "trakt-api-key": V2_API_KEY, "trakt-api-version": 2} url = "%s%s%s" % (self.protocol, BASE_URL, url) if params: url = url + "?" + urllib.urlencode(params) # db_connection = DB_Connection() # created, cached_headers, cached_result = db_connection.get_cached_url(url, json_data, db_cache_limit) # if cached_result and (time.time() - created) < (60 * 60 * cache_limit): # result = cached_result # res_headers = dict(cached_headers) # log_utils.log('Got cached result for: %s' % (url), log_utils.LOGDEBUG) auth_retry = False while True: try: if auth: headers.update({"Authorization": "Bearer %s" % (self.token)}) print("Trakt Call: %s, header: %s, data: %s cache_limit: %s cached: %s") % ( url, headers, data, cache_limit, cached, ) request = urllib2.Request(url, data=json_data, headers=headers) if method is not None: request.get_method = lambda: method.upper() response = urllib2.urlopen(request, timeout=self.timeout) result = "" while True: data = response.read() if not data: break result += data res_headers = dict(response.info().items()) # db_connection.cache_url(url, result, json_data, response.info().items()) break except (ssl.SSLError, socket.timeout) as e: control.infoDialog("Temporary Trakt Error: " + str(e), "Trakt ERROR") raise TransientTraktError("Temporary Trakt Error: " + str(e)) except urllib2.URLError as e: if isinstance(e, urllib2.HTTPError): if e.code in TEMP_ERRORS: control.infoDialog("Temporary Trakt Error: " + str(e), "Trakt ERROR") raise TransientTraktError("Temporary Trakt Error: " + str(e)) elif e.code == 401 or e.code == 405: # token is fine, profile is private if e.info().getheader("X-Private-User") == "true": control.infoDialog("Object is No Longer Available (%s)" % (e.code), "Trakt ERROR") raise TraktAuthError("Object is No Longer Available (%s)" % (e.code)) # auth failure retry or a token request elif auth_retry or url.endswith("/token"): self.token = None control.set_setting("trakt_oauth_token", "") control.set_setting("trakt_refresh_token", "") control.infoDialog("Trakt Call Authentication Failed (%s)" % (e.code), "Trakt ERROR") raise TraktAuthError("Trakt Call Authentication Failed (%s)" % (e.code)) # first try token fail, try to refresh token else: result = self.get_token() self.token = result["access_token"] control.set_setting("trakt_oauth_token", result["access_token"]) control.set_setting("trakt_refresh_token", result["refresh_token"]) auth_retry = True elif e.code == 404: control.infoDialog("Object Not Found (%s)" % (e.code), "Trakt ERROR") raise TraktNotFoundError("Object Not Found (%s)" % (e.code)) else: raise elif isinstance(e.reason, socket.timeout) or isinstance(e.reason, ssl.SSLError): control.infoDialog("Temporary Trakt Error: " + str(e), "Trakt ERROR") raise TransientTraktError("Temporary Trakt Error: " + str(e)) else: control.infoDialog("Trakt Error: " + str(e), "Trakt ERROR") raise TraktError("Trakt Error: " + str(e)) except: raise try: js_data = json.loads(result) if "x-sort-by" in res_headers and "x-sort-how" in res_headers: js_data = utils2.sort_list(res_headers["x-sort-by"], res_headers["x-sort-how"], js_data) except ValueError: js_data = "" if result: print("Invalid JSON Trakt API Response: %s - |%s|" % (url, js_data)) print("Trakt Response: %s" % (response)) return js_data
def get_cid(): id = control.setting('client_id') if id == '': id = str(randint(0, 0x7fffffff)) control.set_setting('client_id', id) return id