def revoke(self): try: control.setSetting('premiumize.token', '') control.setSetting('premiumize.username', '') control.dialog.ok(control.lang(40057), control.lang(32314)) except: log_utils.error()
def get_token(self): try: url = oauth_base_url + 'token' postData = {'client_id': self.client_ID, 'client_secret': self.secret, 'code': self.device_code, 'grant_type': 'http://oauth.net/grant_type/device/1.0'} response = requests.post(url, data=postData) # log_utils.log('Authorizing Real Debrid Result: | %s |' % response, level=log_utils.LOGDEBUG) if '[204]' in str(response): return False, str(response) if 'Temporarily Down For Maintenance' in response.text: control.notification(message='Real-Debrid Temporarily Down For Maintenance', icon=rd_icon) log_utils.log('Real-Debrid Temporarily Down For Maintenance', level=log_utils.LOGWARNING) return False, response.text else: response = response.json() if 'error' in str(response): log_utils.log('response=%s' % str(response), __name__) message = response.get('error') control.notification(message=message, icon=rd_icon) log_utils.log('Real-Debrid Error: %s' % message, level=log_utils.LOGWARNING) return False, response self.token = response['access_token'] control.sleep(500) account_info = self.account_info() username = account_info['username'] control.setSetting('realdebrid.username', username) control.setSetting('realdebrid.client_id', self.client_ID) control.setSetting('realdebrid.secret', self.secret,) control.setSetting('realdebrid.token', self.token) control.setSetting('realdebrid.refresh', response['refresh_token']) return True, None except: log_utils.error('Real Debrid Authorization Failed : ') return False, None
def revoke(self): try: control.setSetting('alldebrid.username', '') control.setSetting('alldebrid.token', '') control.dialog.ok(control.lang(40059), control.lang(32314)) except: log_utils.error()
def account_info_to_dialog(self): from datetime import datetime import math try: accountInfo = self.account_info() expires = datetime.fromtimestamp(accountInfo['premium_until']) days_remaining = (expires - datetime.today()).days expires = expires.strftime("%A, %B %d, %Y") points_used = int( math.floor(float(accountInfo['space_used']) / 1073741824.0)) space_used = float(int(accountInfo['space_used'])) / 1073741824 percentage_used = str( round(float(accountInfo['limit_used']) * 100.0, 1)) items = [] items += [control.lang(40040) % accountInfo['customer_id']] items += [control.lang(40041) % expires] items += [control.lang(40042) % days_remaining] items += [control.lang(40043) % points_used] items += [control.lang(40044) % space_used] items += [control.lang(40045) % percentage_used] return control.selectDialog(items, 'Premiumize') except: log_utils.error() pass return
def account_info_to_dialog(self): from datetime import datetime import time try: userInfo = self.account_info() try: expires = datetime.strptime(userInfo['expiration'], FormatDateTime) except: expires = datetime(*(time.strptime(userInfo['expiration'], FormatDateTime)[0:6])) days_remaining = (expires - datetime.today()).days expires = expires.strftime("%A, %B %d, %Y") items = [] items += [control.lang(40035) % userInfo['email']] items += [control.lang(40036) % userInfo['username']] items += [control.lang(40037) % userInfo['type'].capitalize()] items += [control.lang(40041) % expires] items += [control.lang(40042) % days_remaining] items += [control.lang(40038) % userInfo['points']] return control.selectDialog(items, 'Real-Debrid') except: log_utils.error() pass return
def create_session_id(self): try: if control.setting('tmdb.username') == '' or control.setting('tmdb.password') == '': control.notification(title='default', message=32683, icon='ERROR') return url = self.auth_base_link + '/token/new?api_key=%s' % API_key result = requests.get(url).json() # token = result.get('request_token').encode('utf-8') token = result.get('request_token') url2 = self.auth_base_link + '/token/validate_with_login?api_key=%s' % API_key username = control.setting('tmdb.username') password = control.setting('tmdb.password') post2 = {"username": "******" % username, "password": "******" % password, "request_token": "%s" % token} result2 = requests.post(url2, data=post2).json() url3 = self.auth_base_link + '/session/new?api_key=%s' % API_key post3 = {"request_token": "%s" % token} result3 = requests.post(url3, data=post3).json() if result3.get('success') is True: session_id = result3.get('session_id') msg = '%s' % ('username ='******'[CR]password ='******'[CR]token = ' + token + '[CR]confirm?') if control.yesnoDialog(msg): control.setSetting('tmdb.session_id', session_id) control.notification(title='default', message=32679, icon='default') else: control.notification(title='default', message=32680, icon='ERROR') except: log_utils.error()
def account_info(self): try: accountInfo = self._get(account_info_url) return accountInfo except: log_utils.error() return None
def call(self, path, data=None, with_auth=True, method=None, return_str=False, suppress_error_notification=False): try: def error_notification(line1, error): if suppress_error_notification: return return control.notification(title='default', message='%s: %s' % (line1, error), icon=trakt_icon) def send_query(): resp = None if with_auth: try: if time.time() > self.expires_at: self.refresh_token() except: pass headers['Authorization'] = 'Bearer ' + self.token try: if data is not None: resp = requests.post(self.api_endpoint % path, json=data, headers=headers, timeout=timeout) else: resp = requests.get(self.api_endpoint % path, headers=headers, timeout=timeout) except requests.exceptions.RequestException as e: error_notification('Trakt Error', str(e)) except Exception as e: error_notification('', str(e)) return resp timeout = 15.0 headers = {'Content-Type': 'application/json', 'trakt-api-version': '2', 'trakt-api-key': self.client_id} response = send_query() response.encoding = 'utf-8' if return_str: return response try: result = response.json() except: result = None return result except: log_utils.error()
def get_device_token(self, device_codes): try: data = {"code": device_codes["device_code"], "client_id": self.client_id, "client_secret": self.client_secret} start = time.time() expires_in = device_codes['expires_in'] verification_url = control.lang(32513) % str(device_codes['verification_url']) user_code = control.lang(32514) % str(device_codes['user_code']) control.progressDialog.create(control.lang(32073), control.progress_line % (verification_url, user_code, '')) try: time_passed = 0 while not control.progressDialog.iscanceled() and time_passed < expires_in: try: response = self.call("oauth/device/token", data=data, with_auth=False, suppress_error_notification=True) except requests.HTTPError as e: log_utils.log('Request Error: %s' % str(e), __name__, log_utils.LOGDEBUG) if e.response.status_code != 400: raise e progress = int(100 * time_passed / expires_in) control.progressDialog.update(progress) control.sleep(max(device_codes['interval'], 1)*1000) else: if not response: continue else: return response time_passed = time.time() - start finally: control.progressDialog.close() return None except: log_utils.error()
def refresh_token(self): traktToken = None traktRefresh = None traktExpires = None data = { "client_id": self.client_id, "client_secret": self.client_secret, "redirect_uri": "urn:ietf:wg:oauth:2.0:oob", "grant_type": "refresh_token", "refresh_token": control.setting('trakt.refresh') } response = self.call("oauth/token", data=data, with_auth=False, return_str=True) try: code = str(response[1]) except: code = '' if code.startswith('5') or ( response and isinstance(response, py_tools.string_types) and '<html' in response ) or not response: # covers Maintenance html responses ["Bad Gateway", "We're sorry, but something went wrong (500)"]) log_utils.log('Temporary Trakt Server Problems', level=log_utils.LOGNOTICE) control.notification(title=32315, message=33676) return False elif response and code in ['423']: log_utils.log('Locked User Account - Contact Trakt Support: %s' % str(response[0]), level=log_utils.LOGWARNING) control.notification(title=32315, message=33675) return False if response and code not in ['401', '405']: try: response = response.json() except: log_utils.error() return False if 'error' in response and response['error'] == 'invalid_grant': log_utils.log('Please Re-Authorize your Trakt Account: %s' % response['error'], __name__, level=log_utils.LOGWARNING) control.notification(title=32315, message=33677) return False traktToken = response["access_token"] traktRefresh = response["refresh_token"] traktExpires = time.time() + 7776000 control.setSetting('trakt.token', traktToken) control.setSetting('trakt.refresh', traktRefresh) control.setSetting('trakt.expires', str(traktExpires)) self.token = traktToken
def six_decode(txt, char='utf-8'): try: if isPY3 and isinstance(txt, binary_type): txt = txt.decode(char) return txt except: from myaccounts.modules import log_utils log_utils.error() return txt
def revoke(self): try: control.setSetting('realdebrid.client_id', '') control.setSetting('realdebrid.secret', '') control.setSetting('realdebrid.token', '') control.setSetting('realdebrid.refresh', '') control.setSetting('realdebrid.username', '') control.dialog.ok(control.lang(40058), control.lang(32314)) except: log_utils.error()
def ensure_text(s, encoding='utf-8', errors='strict'): try: if isinstance(s, binary_type): return s.decode(encoding, errors) elif isinstance(s, text_type): return s except: from myaccounts.modules import log_utils log_utils.error() return s
def account_info_to_dialog(self): from datetime import datetime, timedelta try: account_info, stats = self.extended_account_info() username = account_info['user']['username'] timezone = account_info['account']['timezone'] joined = control.jsondate_to_datetime( account_info['user']['joined_at'], "%Y-%m-%dT%H:%M:%S.%fZ") private = account_info['user']['private'] vip = account_info['user']['vip'] if vip: vip = '%s Years' % str(account_info['user']['vip_years']) total_given_ratings = stats['ratings']['total'] movies_collected = stats['movies']['collected'] movies_watched = stats['movies']['watched'] movies_watched_minutes = ("{:0>8}".format( str(timedelta( minutes=stats['movies']['minutes'])))).split(', ') movies_watched_minutes = control.lang(40071) % ( movies_watched_minutes[0], movies_watched_minutes[1].split(':')[0], movies_watched_minutes[1].split(':')[1]) shows_collected = stats['shows']['collected'] shows_watched = stats['shows']['watched'] episodes_watched = stats['episodes']['watched'] episodes_watched_minutes = ("{:0>8}".format( str(timedelta( minutes=stats['episodes']['minutes'])))).split(', ') episodes_watched_minutes = control.lang(40071) % ( episodes_watched_minutes[0], episodes_watched_minutes[1].split(':')[0], episodes_watched_minutes[1].split(':')[1]) heading = control.lang(32315) items = [] items += [control.lang(40036) % username] items += [control.lang(40063) % timezone] items += [control.lang(40064) % joined] items += [control.lang(40065) % private] items += [control.lang(40066) % vip] items += [control.lang(40067) % str(total_given_ratings)] items += [ control.lang(40068) % (movies_collected, movies_watched, movies_watched_minutes) ] items += [control.lang(40069) % (shows_collected, shows_watched)] items += [ control.lang(40070) % (episodes_watched, episodes_watched_minutes) ] return control.selectDialog(items, heading) except: log_utils.error() return
def ensure_str(s, encoding='utf-8', errors='strict'): from myaccounts.modules import log_utils try: if not isinstance(s, (text_type, binary_type)): return log_utils.log("not expecting type '%s'" % type(s), __name__, log_utils.LOGDEBUG) if isPY2 and isinstance(s, text_type): s = s.encode(encoding, errors) elif isPY3 and isinstance(s, binary_type): s = s.decode(encoding, errors) return s except: log_utils.error() return s
def revoke_session_id(self): try: if control.setting('tmdb.session_id') == '': return url = self.auth_base_link + '/session?api_key=%s' % API_key post = {"session_id": "%s" % control.setting('tmdb.session_id')} result = requests.delete(url, data=post).json() if result.get('success') is True: control.setSetting('tmdb.session_id', '') control.notification(title='default', message=32681, icon='default') else: control.notification(title='default', message=32682, icon='ERROR') except: log_utils.error()
def _get(self, url, url_append=''): result = None try: if self.token == '': return None url = base_url + url + '?agent=%s&apikey=%s' % ( user_agent, self.token) + url_append result = requests.get(url, timeout=self.timeout).json() if result.get('status') == 'success': if 'data' in result: result = result['data'] except requests.exceptions.ConnectionError: control.notification(title='default', message=40073, icon=ad_icon) except BaseException: log_utils.error() return result
def _get(self, url): try: response = requests.get(url, headers=self.headers, timeout=15).json() if 'status' in response: if response.get('status') == 'success': return response if response.get( 'status') == 'error' and self.server_notifications: control.notification(title='default', message=response.get('message'), icon='default') except: log_utils.error() return response
def auth_loop(self): control.sleep(self.auth_step * 1000) url = 'client_id=%s&code=%s' % (self.client_ID, self.device_code) url = oauth_base_url + credentials_url % url response = json.loads(requests.get(url).text) if 'error' in response: return # else: try: control.progressDialog.close() self.client_ID = response['client_id'] self.secret = response['client_secret'] except: log_utils.error() control.okDialog(title='default', message=control.lang(40019)) return
def run(self): log_utils.log('My Accounts checking available updates', log_utils.LOGNOTICE) try: import re import requests repo_xml = requests.get('https://raw.githubusercontent.com/a4k-openproject/repository.myaccounts/master/zips/addons.xml') if repo_xml.status_code != 200: log_utils.log('Could not connect to My Accounts repo XML, status: %s' % repo_xml.status_code, log_utils.LOGNOTICE) return repo_version = re.findall(r'<addon id=\"script.module.myaccounts\".*version=\"(\d*.\d*.\d*.\d*)\"', repo_xml.text)[0] local_version = control.addonVersion() if control.check_version_numbers(local_version, repo_version): while control.condVisibility('Library.IsScanningVideo'): control.sleep(10000) log_utils.log('A newer version of My Accounts is available. Installed Version: v%s, Repo Version: v%s' % (local_version, repo_version), log_utils.LOGNOTICE) control.notification(title = 'default', message = 'A new verison of My Accounts is available from the repository. Please consider updating to v%s' % repo_version, icon = 'default', time=5000, sound=False) except: log_utils.error() pass
def refresh_token(self): try: self.client_ID = control.setting('realdebrid.client_id') self.secret = control.setting('realdebrid.secret') self.device_code = control.setting('realdebrid.refresh') log_utils.log( 'Refreshing Expired Real Debrid Token: |%s|%s|' % (self.client_ID, self.device_code), __name__, log_utils.LOGDEBUG) if not self.get_token(): self.revoke() log_utils.log('Unable to Refresh Real Debrid Token', __name__, log_utils.LOGDEBUG) else: log_utils.log('Real Debrid Token Successfully Refreshed', __name__, log_utils.LOGDEBUG) return True except: log_utils.error() return False
def account_info_to_dialog(self): from datetime import datetime try: account_info = self.account_info()['user'] username = account_info['username'] email = account_info['email'] status = 'Premium' if account_info['isPremium'] else 'Not Active' expires = datetime.fromtimestamp(account_info['premiumUntil']) days_remaining = (expires - datetime.today()).days heading = control.lang(40059).upper() items = [] items += [control.lang(40036) % username] items += [control.lang(40035) % email] items += [control.lang(40037) % status] items += [control.lang(40041) % expires] items += [control.lang(40042) % days_remaining] return control.selectDialog(items, 'All Debrid') except: log_utils.error() return
def auth(self): try: code = self.get_device_code() token = self.get_device_token(code) if token: expires_at = time.time() + 60 * 60 * 24 * 30 control.setSetting('trakt.expires', str(expires_at)) control.setSetting('trakt.token', token["access_token"]) control.setSetting('trakt.refresh', token["refresh_token"]) control.sleep(1000) try: user = self.call("users/me", with_auth=True) control.setSetting('trakt.username', str(user['username'])) except: pass control.notification(message=40074, icon=trakt_icon) return True control.notification(message=40075, icon=trakt_icon) return False except: log_utils.error()
def refresh_token(self): try: self.client_ID = control.setting('realdebrid.client_id') self.secret = control.setting('realdebrid.secret') self.device_code = control.setting('realdebrid.refresh') if not self.client_ID or not self.secret or not self.device_code: return False # avoid if previous refresh attempt revoked accnt, loops twice. log_utils.log('Refreshing Expired Real Debrid Token: | %s | %s |' % (self.client_ID, self.device_code), __name__, log_utils.LOGDEBUG) success, error = self.get_token() if not success: if not 'Temporarily Down For Maintenance' in error: if any(value == error.get('error_code') for value in [9, 12, 13, 14]): self.revoke() # empty all auth settings to force a re-auth on next use control.notification(message='Real-Debrid Auth revoked due to: %s' % error.get('error'), icon=rd_icon) log_utils.log('Unable to Refresh Real Debrid Token: %s' % error.get('error'), level=log_utils.LOGWARNING) return False else: log_utils.log('Real Debrid Token Successfully Refreshed', level=log_utils.LOGDEBUG) return True except: log_utils.error() return False
def _get(self, url, fail_check=False, token_ck=False): try: original_url = url url = rest_base_url + url if self.token == '': log_utils.log('No Real Debrid Token Found', __name__, log_utils.LOGDEBUG) return None # if not fail_check: # with fail_check=True new token does not get added if '?' not in url: url += "?auth_token=%s" % self.token else: url += "&auth_token=%s" % self.token response = requests.get(url, timeout=15).json() if 'bad_token' in str(response) or 'Bad Request' in str(response): if not fail_check: if self.refresh_token() and token_ck: return response = self._get(original_url, fail_check=True) return response except: log_utils.error() return None