コード例 #1
0
ファイル: root.py プロジェクト: varunrai/Masterani-Redux
def main_menu():
    upgrade_warning = control.setting("upgrade.warning")

    if upgrade_warning is "":
        import xbmcgui
        xbmcgui.Dialog().ok("Masterani Redux Warning",
                                    " \n\nIt has come to our attention that the addon stopped working for some people. During our investigation in the matter,"
                                    " we found that security upgrades rendered Kodi 16 unable to fetch the required data.\n\n"
                                    "If the addon is unable to load anything, you are affected by this. Please update your Kodi to the latest version.")
        control.setSetting("upgrade.warning", "shown")

    lastvisited = control.setting("anime.lastvisited")
    if int(lastvisited) != 0:
        add_last_visited(lastvisited)

    add_favorites()

    items = [
        {'name': "Recent",
         'action': "recent"},

        {'name': "Popular Today",
         'action': "popular"},

        {'name': "Anime",
         'action': "list"},

        {'name': "Search",
         'action': 'search'},

        {'name': "Tools",
         'action': "tools"}
    ]
    add_directory(items)
コード例 #2
0
    def get_api(self):

        try:

            api_key = self.api_key

            if api_key == '':
                if self.user_name == '' or self.user_pass == '':
                    return

                else:
                    s = requests.Session()
                    link = (self.base_link + self.login_link % (self.user_name, self.user_pass))
                    p = s.post(link)
                    p = json.loads(p.text)

                    if p['status'] == 'ok':
                        api_key = p['api_key']
                        control.setSetting('furk.api', api_key)
                    else:
                        pass

            return api_key

        except:
            print("Unexpected error in Furk Script: check_api", sys.exc_info()[0])
            exc_type, exc_obj, exc_tb = sys.exc_info()
            print(exc_type, exc_tb.tb_lineno)
            pass
コード例 #3
0
ファイル: kitsu.py プロジェクト: varunrai/Masterani-Redux
def auth():
    email = control.setting("kitsu.user")
    password = control.setting("kitsu.pass")
    resp = requests.post("https://kitsu.io/api/oauth/token",
                          params={"grant_type": "password", "username": email, "password": password})
    print resp
    token = json.loads(resp.text)['access_token']
    control.setSetting("kitsu.token", token)
    useridScrobble_resp = requests.get('https://kitsu.io/api/edge/users?filter[self]=true', headers=kitsu_headers())
    userid = json.loads(useridScrobble_resp.text)['data'][0]['id']
    control.setSetting("kitsu.userid", userid) 
コード例 #4
0
ファイル: movies.py プロジェクト: YourFriendCaspian/dotfiles
    def search_new(self):
        t = control.lang(32010).encode('utf-8')
        k = control.keyboard('', t) ; k.doModal()
        q = k.getText().strip() if k.isConfirmed() else None
        if not q: return


        search_history = control.setting('moviesearch')
        if q not in search_history.split('\n'):
            control.setSetting('moviesearch', q + '\n' + search_history)


        url = self.search_link + urllib.quote_plus(q)
        self.get(url)
コード例 #5
0
ファイル: trakt.py プロジェクト: varunrai/Masterani-Redux
def __getTrakt(url, post=None):
    try:
        url = urlparse.urljoin(BASE_URL, url)
        post = json.dumps(post) if post else None
        headers = {'Content-Type': 'application/json', 'trakt-api-key': V2_API_KEY, 'trakt-api-version': 2}

        if getTraktCredentialsInfo():
            headers.update({'Authorization': 'Bearer %s' % control.setting('trakt.token')})

        result = client.request(url, post=post, headers=headers, output='extended', error=True)

        resp_code = result[1]
        resp_header = result[2]
        result = result[0]

        if resp_code in ['500', '502', '503', '504', '520', '521', '522', '524']:
            log_utils.log('Temporary Trakt Error: %s' % resp_code, log_utils.LOGWARNING)
            return
        elif resp_code in ['404']:
            log_utils.log('Object Not Found : %s' % resp_code, log_utils.LOGWARNING)
            return
        elif resp_code in ['429']:
            log_utils.log('Trakt Rate Limit Reached: %s' % resp_code, log_utils.LOGWARNING)
            return

        if resp_code not in ['401', '405']:
            return result, resp_header

        oauth = urlparse.urljoin(BASE_URL, '/oauth/token')
        opost = {'client_id': V2_API_KEY, 'client_secret': CLIENT_SECRET, 'redirect_uri': REDIRECT_URI, 'grant_type': 'refresh_token', 'refresh_token': control.setting('trakt.refresh')}

        result = client.request(oauth, post=json.dumps(opost), headers=headers)
        result = utils.json_loads_as_str(result)

        token, refresh = result['access_token'], result['refresh_token']

        control.setSetting(id='trakt.token', value=token)
        control.setSetting(id='trakt.refresh', value=refresh)

        headers['Authorization'] = 'Bearer %s' % token

        result = client.request(url, post=post, headers=headers, output='extended', error=True)
        return result[0], result[2]
    except Exception as e:
        log_utils.log('Unknown Trakt Error: %s' % e, log_utils.LOGWARNING)
        pass
コード例 #6
0
ファイル: kitsu.py プロジェクト: varunrai/Masterani-Redux
 def kitsu_logout(self):
     control.setSetting("kitsu.token", '')
     control.setSetting("kitsu.userid", '')
     control.setSetting("kitsu.login_auth", '')
     control.refresh()
     dialog = xbmcgui.Dialog()
     dialog.ok('Kitsu', 'Logout successful')
コード例 #7
0
ファイル: trakt.py プロジェクト: sokam/kodiprofile
def getTrakt(url, post=None):
    try:
        url = urlparse.urljoin('http://api-v2launch.trakt.tv', url)

        headers = {'Content-Type': 'application/json', 'trakt-api-key': 'c029c80fd3d3a5284ee820ba1cf7f0221da8976b8ee5e6c4af714c22fc4f46fa', 'trakt-api-version': '2'}

        if not post == None: post = json.dumps(post)


        if getTraktCredentialsInfo() == False:
            result = client.request(url, post=post, headers=headers)
            return result


        headers['Authorization'] = 'Bearer %s' % control.setting('trakt.token')

        result = client.request(url, post=post, headers=headers, output='response', error=True)
        if not (result[0] == '401' or result[0] == '405'): return result[1]


        oauth = 'http://api-v2launch.trakt.tv/oauth/token'
        opost = {'client_id': 'c029c80fd3d3a5284ee820ba1cf7f0221da8976b8ee5e6c4af714c22fc4f46fa', 'client_secret': '90a1840447a1e39d350023263902fe7010338d19789e6260f18df56a8b07a68a', 'redirect_uri': 'urn:ietf:wg:oauth:2.0:oob', 'grant_type': 'refresh_token', 'refresh_token': control.setting('trakt.refresh')}

        result = client.request(oauth, post=json.dumps(opost), headers=headers)
        result = json.loads(result)

        token, refresh = result['access_token'], result['refresh_token']

        control.setSetting(id='trakt.token', value=token)
        control.setSetting(id='trakt.refresh', value=refresh)

        headers['Authorization'] = 'Bearer %s' % token

        result = client.request(url, post=post, headers=headers)
        return result
    except:
        pass
コード例 #8
0
ファイル: trakt.py プロジェクト: azumimuo/family-xbmc-addon
def getTrakt(url, post=None):
    try:
        url = urlparse.urljoin('http://api-v2launch.trakt.tv', url)

        headers = {'Content-Type': 'application/json', 'trakt-api-key': '3b76e1b99fa4a5b27f63e04307754751514d88916195ea8abc1c48eeef68f0d9', 'trakt-api-version': '2'}

        if not post == None: post = json.dumps(post)


        if getTraktCredentialsInfo() == False:
            result = client.request(url, post=post, headers=headers)
            return result


        headers['Authorization'] = 'Bearer %s' % control.setting('trakt.token')

        result = client.request(url, post=post, headers=headers, output='extended', error=True)
        if not (result[1] == '401' or result[1] == '405'): return result[0]


        oauth = 'http://api-v2launch.trakt.tv/oauth/token'
        opost = {'client_id': '3b76e1b99fa4a5b27f63e04307754751514d88916195ea8abc1c48eeef68f0d9', 'client_secret': 'b0be7e72b647bcb44f2846b29729028e5d75fa710b91812027ae79cc48456a16', 'redirect_uri': 'urn:ietf:wg:oauth:2.0:oob', 'grant_type': 'refresh_token', 'refresh_token': control.setting('trakt.refresh')}

        result = client.request(oauth, post=json.dumps(opost), headers=headers)
        result = json.loads(result)

        token, refresh = result['access_token'], result['refresh_token']

        control.setSetting(id='trakt.token', value=token)
        control.setSetting(id='trakt.refresh', value=refresh)

        headers['Authorization'] = 'Bearer %s' % token

        result = client.request(url, post=post, headers=headers)
        return result
    except:
        pass
コード例 #9
0
ファイル: kitsu.py プロジェクト: varunrai/Masterani-Redux
 def kitsu_login(self):
     try:
         token_url = 'https://kitsu.io/api/oauth/token'
         resp = requests.post(token_url, params={"grant_type": "password", "username": '******' %(control.getSetting("kitsu.email")), "password": '******' %(control.getSetting("kitsu.password"))})
         token = json.loads(resp.text)['access_token']
         control.setSetting("kitsu.token", token)
         useridScrobble_resp = requests.get('https://kitsu.io/api/edge/users?filter[self]=true', headers=self.kitsu_headers())
         userid = json.loads(useridScrobble_resp.text)['data'][0]['id']
         control.setSetting("kitsu.userid", userid)
         control.setSetting("kitsu.login_auth", 'Kitsu')
         dialog = xbmcgui.Dialog()
         dialog.ok('Kitsu', 'Login successful')
     except:
         dialog = xbmcgui.Dialog()
         dialog.ok('Kitsu', 'Login error. Incorrect email or password.')
コード例 #10
0
def scrapecloud(title, match, year=None, season=None, episode=None):
	progress = control.progressDialogBG
	filesOnly = control.setting('scraper.filesonly')
	cachedSession = control.setting('cachecloud.remember')
	cached_time, cached_results = cloudCache(mode='get')
	
	if cached_time != '0' and cached_time != None:
		if cachedSession == 'true': r = cached_results
		else:
			cachedLabel = "Cached Cloud: %s" % cached_time
			results = [cachedLabel, 'New Cloud Scrape', '[AUTO] Cached Cloud until Next Start']
			select = control.selectDialog(results)
			if select == 0: r = cached_results
			elif select == 1: 
				progress.create('Scraping Your Cloud','Please Wait...')
				progress.update(100,'Scraping Your Cloud','Please Wait...')
				r = PremiumizeScraper().sources()
				cloudCache(mode='write', data=r)
			elif select == 2: 
				control.setSetting(id='cachecloud.remember', value='true')
				progress.create('Scraping Your Cloud','Please Wait...')
				progress.update(100,'Scraping Your Cloud','Please Wait...')
				r = PremiumizeScraper().sources()
				cloudCache(mode='write', data=r)
	else:
		progress.create('Scraping Your Cloud','Please Wait...')
		progress.update(100,'Scraping Your Cloud','Please Wait...')
		
		r = PremiumizeScraper().sources()
		cloudCache(mode='write', data=r)

	labels = []
	sources = []
	types = []
	IDs = []
	
	normalSources = []
	exactSources  = []
	
	titleCheck = cleantitle.get(title)
	exactPlay = False
	if season != None:
		epcheck    = "s%02de%02d" % (int(season), int(episode))
		epcheck_2  = "%02dx%02d"  % (int(season), int(episode))
		epcheck_3  = "%sx%s[._ -]" %(season, episode)
				
		exactCheck_1 = titleCheck + epcheck
		exactCheck_2 = titleCheck + epcheck_2
		exactCheck_3 = titleCheck + epcheck_3
	else:
		if year == '' or year == None or year == '0': year = ''
		exactCheck_1 = titleCheck + year
		exactCheck_2 = titleCheck + year
		exactCheck_3 = titleCheck + year		

	
	for x in r:
		cm = []
		type = x['type']
		if filesOnly == 'true':
			if type.lower() != 'file': continue
		fileLabel = type
		id = x['id']
		name = x['name'].encode('utf-8')
		name = normalize(name)

		if match == 'true': 
			if not cleantitle.get(title) in cleantitle.get(name): continue

		normalSources.append(x)
		if exactCheck_1 in cleantitle.get(name) or exactCheck_2 in cleantitle.get(name) or exactCheck_3 in cleantitle.get(name):
			exactSources.append(x)
			
	if len(exactSources) > 0: 
		content = exactSources
		exactPlay = True
			
	else: content = normalSources
	
	for result in content:
		cm = []
		type = result['type']
		fileLabel = type
		id = result['id']
		name = result['name'].encode('utf-8')
		name = normalize(name)
		
		playLink = '0'
		isFolder = True
		isPlayable = 'false'
		url = '0'
		if type == 'file':
			if control.setting('transcoded.play') == 'true':
				try:
					playLink = result['stream_link']
					if not "http" in playLink: playLink = result['link']
					type = 'TRANSCODED'
				except: playLink = result['link']
			else:
				playLink = result['link']
			ext = playLink.split('.')[-1]
			if not ext.lower() in VALID_EXT: continue
			fileLabel = type + " " + str(ext)
			try: 
				size = result['size']
				size = getSize(size)
			except: size = ''
			if size != '': fileLabel = fileLabel + " | " + str(size)
			isFolder = False
			isPlayable = 'true'
			url = playLink
			#AUTOPLAY
			if exactPlay == True and control.setting('scraper.autoplay') == 'true': return url, id
			
		label = "[B]" + fileLabel.upper() + " |[/B] " + str(name) 
		labels.append(label)
		sources.append(url)
		types.append(type)
		IDs.append(id)
	
	try: progress.close()
	except:pass
	try: progress.close()
	except:pass
	
	if len(sources) < 1: return '0'
	select = control.selectDialog(labels)
	if select == -1: return '0'
	selected_type = types[select]
	
	selected_url = sources[select]

	selected_id = IDs[select]
	
	if selected_type != 'file': 
		selected_url = dialogselect_folder(selected_id)
	return selected_url	, selected_id
コード例 #11
0
ファイル: __init__.py プロジェクト: vphuc81/MyRepository
    def get_vk_token():
        import xbmcgui
        import xbmcaddon
        from resources.lib.modules import vkAuth

        if not bool(control.setting("enable_vk")):
            return False

        # flag if a vk.com token is valid
        validVKToken = False

        # if empty vk.com email xor password
        if bool(control.setting('vk_email') == "") ^ bool(control.setting('vk_password') == ""):
            dialog = xbmcgui.Dialog()
            ok = dialog.ok("VK", "Please enter your VK.com credentials")
            control.setSetting('vk_token', '')
            xbmcaddon.Addon().openSettings()
            return False
            # if empty vk.com email and password
        elif control.setting('vk_email') == "" and control.setting('vk_password') == "":
            control.setSetting('vk_token_email', '')
            control.setSetting('vk_token_password', '')
            control.setSetting('vk_token', '')
            # display vk.com account need message
            dialog = xbmcgui.Dialog()
            ok = dialog.ok("VK", "Please Enter your VK.com credentials")
            xbmcaddon.Addon().openSettings()
            return False
        # if credentials are given
        else:
            # check if user changed vk_email/vk_password or if vk_token_email/vk_token_password is empty (need reauth)
            if control.setting('vk_token_email') != control.setting('vk_email') or control.setting(
                    'vk_token_password') != control.setting('vk_password'):
                control.setSetting('vk_token_email', '')
                control.setSetting('vk_token_password', '')
                control.setSetting('vk_token', '')
            # check current token
            if control.setting('vk_token'): validVKToken = vkAuth.isTokenValid(control.setting('vk_token'))
            # if the token provided is not valid, login and generate a new one
            if validVKToken != True:
                # login in vk.com - get the token
                email = control.setting('vk_email')
                passw = control.setting('vk_password')
                try:
                    token = vkAuth.auth(email, passw, 2648691, 'audio,offline,video')
                except:
                    token = False
                # check login status
                if token == False:
                    dialog = xbmcgui.Dialog()
                    ok = dialog.ok("VK Log in Failed", "Please enter your VK.com credentials")
                    xbmcaddon.Addon().openSettings()
                    return False
                else:
                    # test the new token
                    validVKToken = vkAuth.isTokenValid(token)
                    # if there was an error, inform the user
                    if validVKToken != True:
                        dialog = xbmcgui.Dialog()
                        ok = dialog.ok("VK Log in Failed", "Reason" + validVKToken)
                        xbmcaddon.Addon().openSettings()
                        return False
                    else:
                        control.setSetting('vk_token_email', email)
                        control.setSetting('vk_token_password', passw)
                        control.setSetting('vk_token', token)
                        return token
            else:
                return control.setting('vk_token')
コード例 #12
0
ファイル: trakt.py プロジェクト: azumimuo/family-xbmc-addon
def authTrakt(openSettings = True):
	# NB: Seems like there is a Kodi bug that you can't write the same setting twice in one execution.
	# After writing the second time, the settings still contains the first value.
	# Only write once.
	user = ''
	token = ''
	refresh = ''
	try:
		if getTraktCredentialsInfo() == True:
			if interface.Dialog.option(title = 32315, message = control.lang(32511).encode('utf-8') + ' ' + control.lang(32512).encode('utf-8')):
				pass
			else: # Bubbles
				return False

		result = getTrakt('/oauth/device/code', {'client_id': base64.b64decode(traktCI)}, direct = True)
		result = json.loads(result)
		expires_in = int(result['expires_in'])
		device_code = result['device_code']
		interval = result['interval']

		message = interface.Translation.string(33494) + interface.Format.newline()
		message += '     ' + interface.Translation.string(33381) + ': ' + interface.Format.fontBold(result['verification_url'])
		message += interface.Format.newline()
		message += '     ' + interface.Translation.string(33495) + ': ' + interface.Format.fontBold(result['user_code'])
		message += interface.Format.newline() + interface.Translation.string(33978)

		clipboard.Clipboard.copy(result['user_code'])
		progressDialog = interface.Dialog.progress(title = 32315, message = message, background = False)

		for i in range(0, expires_in):
			try:
				if progressDialog.iscanceled(): break
				time.sleep(1)
				if not float(i) % interval == 0: raise Exception()
				r = getTrakt('/oauth/device/token', {'client_id': base64.b64decode(traktCI), 'client_secret': base64.b64decode(traktCS), 'code': device_code}, direct = True)
				r = json.loads(r)
				if 'access_token' in r: break
			except:
				pass

		try: progressDialog.close()
		except: pass

		token, refresh = r['access_token'], r['refresh_token']

		headers = {'Content-Type': 'application/json', 'trakt-api-key': base64.b64decode(traktCI), 'trakt-api-version': '2', 'Authorization': 'Bearer %s' % token}

		result = client.request('http://api-v2launch.trakt.tv/users/me', headers=headers)
		result = json.loads(result)

		user = result['username']
	except:
		pass

	control.setSetting(id='accounts.informants.trakt.user', value=user)
	control.setSetting(id='accounts.informants.trakt.token', value=token)
	control.setSetting(id='accounts.informants.trakt.refresh', value=refresh)

	if openSettings:
		tools.Settings.launch(category = tools.Settings.CategoryAccounts)

	return {'user' : user, 'token' : token, 'refresh' : refresh}
コード例 #13
0
    def _authenticate(self, username, password, service_id, retry=1):

        instance_id = self.get_instance_id()

        payload = {
            'payload': {
                'email': username,
                'password': password,
                'serviceId': service_id
            }
        }
        headers = {
            'content-type': 'application/json; charset=UTF-8',
            'accept': 'application/json, text/javascript',
            'Accept-Encoding': 'gzip',
            'Authorization': 'IIDToken com.globo.hydra|%s' % instance_id
        }

        control.log('POST %s' % self.ENDPOINT_URL)
        control.log(headers)

        response = cache.get(requests.post,
                             1,
                             self.ENDPOINT_URL,
                             json=payload,
                             headers=headers,
                             lock_obj=auth_lock,
                             table='globoplay')

        control.log('GLOBOPLAY AUTHENTICATION RESPONSE: %s' %
                    response.status_code)
        control.log(response.content)

        success = response.status_code < 400

        if not success:
            cache.clear_item(requests.post,
                             self.ENDPOINT_URL,
                             json=payload,
                             headers=headers,
                             table='globoplay')

        if response.status_code == 500 or response.status_code == 498:
            control.setSetting('globoplay_instance_id', None)
            if retry > 0:
                return self._authenticate(username, password, service_id,
                                          retry - 1)

        try:
            message = (response.json().get('userMessage')
                       or '').encode('utf-8')
        except:
            message = response.content

        brplay_id = self.hash_user_credentials(username, password, service_id)
        return {
            'GLBID': response.cookies.get('GLBID'),
            'brplay_id': brplay_id,
            'success': success,
            'error_message': message
        }
コード例 #14
0
ファイル: auth.py プロジェクト: scivolant/plugin.video.brplay
def login(validate=True):

    credentials = control.setting('nowonline_credentials')

    if credentials:
        control.log('Found credentials cached')
        result = pickle.loads(credentials)
        if validate_login(result, validate):
            return result

        control.log('Validation failed, trying to login...')

    username = control.setting('nowonline_account')
    password = control.setting('nowonline_password')

    url = 'https://www.nowonline.com.br/AGL/1.1/R/ENG/{platform}/ALL/NET/USER/SESSIONS'.format(platform=PLATFORM)

    header = {
        'referer': 'https://www.nowonline.com.br/'
    }

    data = {
        "credentials":
            {
                "username": username,
                "password": password,
                "type": "net"
            }
    }

    device_id = None

    if PLATFORM != 'PCTV':
        device_id = control.setting('nowonline_device_id')
        if not device_id:
            device_id = str(uuid.uuid4()).upper()
            control.setSetting('nowonline_device_id', device_id)

        data['deviceInfo'] = {
            "deviceId": device_id,
            "deviceIdType": "DEVICEID"
        }

    control.log('GET %s' % url)

    response = requests.post(url, json=data, headers=header, proxies=proxy)

    response.raise_for_status()

    # response_data = response.json()
    avs_cookie = response.cookies.get('avs_cookie')
    avs_user_info = response.cookies.get('avs_user_info')
    dt_cookie = response.cookies.get('dtCookie')
    login_info = response.cookies.get('LoginInfo')
    session_id = response.cookies.get('sessionId')
    x_xsrf_token = response.headers.get('X-Xsrf-Token')

    credentials = {
        'platform': PLATFORM,
        'cookies': {
            'avs_cookie': avs_cookie,
            'avs_user_info': avs_user_info,
            'dtCookie': dt_cookie,
            'LoginInfo': login_info,
            'sessionId': session_id,
        },
        'headers': {
            'X-Xsrf-Token': x_xsrf_token
        }
    }

    if PLATFORM != 'PCTV':
        credentials['deviceId'] = device_id

    control.log(credentials)

    control.setSetting('nowonline_credentials', pickle.dumps(credentials))

    return credentials
コード例 #15
0
    def authTrakt(self):
        try:
            import threading, xbmc

            check = checkCredentials()
            if check == 'true':
                yes = control.yesnoDialog(
                    control.lang(32511).encode('utf-8'),
                    control.lang(32512).encode('utf-8'), '', 'Trakt')
                if yes:
                    control.setSetting(id='trakt.user', value='')
                    control.setSetting(id='trakt.token', value='')
                    control.setSetting(id='trakt.refresh', value='')
                    control.infoDialog('Trakt Account Reset: DONE',
                                       sound=True,
                                       icon='INFO')
                raise Exception()
            result = getTraktAsJson('/oauth/device/code',
                                    {'client_id': CLIENT_ID})
            #print ("TRAKT AUTH")
            #print (result)
            verification_url = (control.lang(32513) %
                                result['verification_url'])
            user_code = (control.lang(32514) % result['user_code'])
            expires_in = int(result['expires_in'])
            device_code = result['device_code']
            interval = result['interval']
            #print (user_code, expires_in, device_code)

            message = verification_url + " - " + user_code
            progressDialog = control.progressDialog
            progressDialog.create('Trakt Auth', message)

            for i in range(0, expires_in):
                try:
                    time.sleep(1)
                    if progressDialog.iscanceled(): break

                    if not float(i) % interval == 0: raise Exception()
                    percent = (i * 100) / expires_in
                    progressDialog.update(int(percent), message)

                    token, refresh = self.getAuth(device_code)
                    if self.Authorized: break
                    if self.dialgClosed: break
                except:
                    pass

            try:
                xbmc.executebuiltin('Dialog.Close(all,true)')
            except:
                pass
            try:
                xbmc.executebuiltin('Dialog.Close(all,true)')
            except:
                pass

            if self.Authorized:
                headers = {
                    'Content-Type': 'application/json',
                    'trakt-api-key': CLIENT_ID,
                    'trakt-api-version': '2',
                    'Authorization': 'Bearer %s' % token
                }

                result = requests.get(urllib.parse.urljoin(
                    BASE_URL, '/users/me'),
                                      headers=headers).content
                result = utils.json_loads_as_str(result)

                user = result['username']
                control.infoDialog('Trakt Account Verified')
                control.setSetting(id='trakt.user', value=user)
                control.setSetting(id='trakt.token', value=token)
                control.setSetting(id='trakt.refresh', value=refresh)
                control.setSetting(id='indicators.alt', value='1')

            raise Exception()
        except:
            pass
コード例 #16
0
def __getTrakt(url, post=None, method='get'):
    try:
        url = urllib.parse.urljoin(BASE_URL, url)
        post = json.dumps(post) if post else None
        if post == None: post == ''
        headers = {
            'Content-Type': 'application/json',
            'trakt-api-key': CLIENT_ID,
            'trakt-api-version': '2'
        }

        if getTraktCredentialsInfo():
            headers.update({
                'Authorization':
                'Bearer %s' % control.setting('trakt.token')
            })

        if any(value in url for value in post_links): method = 'post'
        if method == 'post':
            result = requests.post(url, data=post, headers=headers)
        elif method == 'get':
            result = requests.get(url, params=post, headers=headers)
        elif method == 'delete':
            result = requests.delete(url, headers=headers)

        resp_code = str(result.status_code)
        resp_header = result.headers
        result = result.content

        # #print ("TRAKT url", url)
        ##print ("TRAKT RESULT", result)

        if resp_code in [
                '500', '502', '503', '504', '520', '521', '522', '524'
        ]:
            log_utils.log('Temporary Trakt Error: %s' % resp_code,
                          log_utils.LOGWARNING)

            return
        elif resp_code in ['404']:
            log_utils.log('Object Not Found : %s' % resp_code,
                          log_utils.LOGWARNING)
            return

        if resp_code not in ['401', '405']:
            return result, resp_header

        oauth = urllib.parse.urljoin(BASE_URL, '/oauth/token')
        opost = {
            'client_id': CLIENT_ID,
            'client_secret': CLIENT_SECRET,
            'redirect_uri': REDIRECT_URI,
            'grant_type': 'refresh_token',
            'refresh_token': control.setting('trakt.refresh')
        }

        result = requests.post(oauth, data=json.dumps(opost),
                               headers=headers).content
        result = utils.json_loads_as_str(result)
        # #print ("TRAKT RESULT2", result)

        token, refresh = result['access_token'], result['refresh_token']

        control.setSetting(id='trakt.token', value=token)
        control.setSetting(id='trakt.refresh', value=refresh)

        headers['Authorization'] = 'Bearer %s' % token

        if any(value in url for value in post_links):
            result = requests.post(url, data=post, headers=headers)
        elif url in sync_history:
            result = requests.post(url, data=post, headers=headers)
        else:
            result = requests.get(url, params=post, headers=headers)

        resp_header2 = result.headers
        result2 = result.content
        return result2, resp_header2

    except Exception as e:
        log_utils.log('Unknown Trakt Error: %s' % e, log_utils.LOGWARNING)
        pass
コード例 #17
0
ファイル: auth.py プロジェクト: IMthEGREAT1/felipe.repository
 def clearCredentials(self):
     control.setSetting(self.GLOBOSAT_CREDENTIALS, None)
     self.credentials = {}
コード例 #18
0
ファイル: auth.py プロジェクト: IMthEGREAT1/felipe.repository
 def _save_credentials(self):
     control.setSetting(self.GLOBOSAT_CREDENTIALS,
                        pickle.dumps(self.credentials))
     control.log("Saving credentials with key: %s" %
                 self.GLOBOSAT_CREDENTIALS)
コード例 #19
0
                   premiered,
                   meta,
                   select=select)

elif action == 'directPlay':
    from resources.lib.sources import sources
    sources().directPlay(url, title, year, imdb, tvdb, tmdb, season, episode,
                         tvshowtitle, premiered, meta, id)

elif action == 'authRealDebrid':
    from resources.lib.modules import control
    from tvresolver import debrid
    token = debrid.authRealDebrid()
    if token != '' and token != '0' and token != None:
        status = 'Tv Resolver Authorized'
        control.setSetting(id='realdebrid.status', value=status)
        control.openSettings('3.1')

elif action == 'testItem':
    from resources.lib.api import fanarttv
    imdb = '121361'
    query = 'tv'
    fanarttv.get(imdb, query)
elif action == 'testSources':
    from resources.lib.sources import sources
    sources().advtestmode()

elif action == 'nextaired':
    from resources.lib.api import tvdbapi
    tvdbapi.airingtoday().get()
コード例 #20
0
ファイル: service.py プロジェクト: AisenT/aenemapyrepo
# -*- coding: utf-8 -*-

from resources.lib.modules import control
control.setSetting(id='first.start', value='true')  # FORCE NEW CACHE

# class Service():
# def __init__(self, *args):
# addonName = 'Premiumize Transfers'

# def ServiceEntryPoint(self):
# monitor = xbmc.Monitor()

# while not monitor.abortRequested():
# # check every 5 mins
# if monitor.waitForAbort(100):
# # Abort was requested while waiting. We should exit
# break

# control.execute('RunPlugin(plugin://plugin.video.realizer/?action=transferMonitor)')

# if transferMonitor !='false': Service().ServiceEntryPoint()
コード例 #21
0
def get_live_channels():

    start_date = datetime.datetime.utcnow()
    stop_date = start_date + datetime.timedelta(hours=6)

    url = 'https://api.pluto.tv/v2/channels?start=' + start_date.strftime(
        '%Y-%m-%dT%H:00:00.000Z') + '&stop=' + stop_date.strftime(
            '%Y-%m-%dT%H:00:00.000Z')

    response = cache.get(requests.get, 4, url, proxies=proxy,
                         table='pluto').json()

    now_str = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.000Z')

    for channel in response:

        if 'timelines' not in channel:
            continue

        program = next(p for p in channel['timelines']
                       if p['start'] <= now_str < p['stop'])

        is_live = program.get('liveBroadcast', False)
        live_text = u' (' + control.lang(32004) + u')' if is_live else u''

        title = program.get('title')
        sub_title = program.get('episode', {}).get('name')
        thumb = program.get('episode', {}).get('series', {}).get(
            'featuredImage', {}).get('path') or program.get('episode', {}).get(
                'poster', {}).get('path') or None
        fanart = thumb
        logo = channel['colorLogoPNG']['path']

        program_name = title + (u': ' + sub_title if sub_title else u'')

        duration_milliseconds = int(program['episode']['duration'])
        start_time = util.strptime_workaround(program['start'],
                                              '%Y-%m-%dT%H:%M:%S.%fZ')
        stop_time = start_time + datetime.timedelta(
            milliseconds=duration_milliseconds)

        program_time_desc = datetime.datetime.strftime(
            start_time, '%H:%M') + ' - ' + datetime.datetime.strftime(
                stop_time, '%H:%M')
        tags = [program_time_desc]

        description = '%s | %s' % (program_time_desc, program.get(
            'episode', {}).get('description'))

        studio = channel['name']

        label = u"[B]%s[/B][I] - %s[/I]%s" % (studio, program_name, live_text)

        genres = [
            program.get('episode', {}).get('genre').upper(),
            program.get('episode', {}).get('subGenre').upper(),
            program.get('episode', {}).get('series', {}).get('type').upper()
        ]

        sid = control.setting('pluto_sid')
        if not sid:
            sid = str(uuid.uuid4())
            control.setSetting('pluto_sid', sid)
        did = control.setting('pluto_did')
        if not did:
            did = str(uuid.uuid4())
            control.setSetting('pluto_did', did)

        video_url = u'https://service-stitcher.clusters.pluto.tv/stitch/hls/channel/{channel}/master.m3u8?deviceType=web&deviceMake=Chrome&deviceModel=Chrome&sid={sid}&deviceId={did}&deviceVersion=74.0.3729.131&appVersion=2.5.1-f9a6096b469cfe5e4f1cc92cc697e8500e57891c&deviceDNT=0&userId=&advertisingId=&deviceLat=38.8177&deviceLon=-77.1527&app_name=&appName=&buildVersion=&appStoreUrl=&architecture='.format(
            channel=channel['_id'], sid=sid, did=did)
        # video_url = channel.get('stitched', {}).get('urls', [])[0].get('url')

        yield {
            'url':
            video_url,
            'IsPlayable':
            True,
            'label':
            label,
            'title':
            label,
            'studio':
            'Pluto TV',
            'tvshowtitle':
            title,
            'sorttitle':
            program_name,
            'dateadded':
            datetime.datetime.strftime(start_time, '%Y-%m-%d %H:%M:%S'),
            'plot':
            description,
            'tag':
            tags,
            'duration':
            duration_milliseconds / 1000,
            'adult':
            False,
            'genre':
            genres,
            'year':
            program.get('episode', {}).get('clip',
                                           {}).get('originalReleaseDate',
                                                   '')[0:4],
            'rating':
            program.get('episode', {}).get('rating'),
            'episode':
            program.get('episode', {}).get('number'),
            'art': {
                'icon': logo,
                'thumb': thumb,
                'tvshow.poster': thumb,
                'clearlogo': logo,
                'fanart': fanart
            }
        }
コード例 #22
0
def __getTrakt(url, post=None):
    try:
        url = urlparse.urljoin(BASE_URL, url)
        post = json.dumps(post) if post else None
        headers = {
            "Content-Type": "application/json",
            "trakt-api-key": V2_API_KEY,
            "trakt-api-version": 2,
        }

        if getTraktCredentialsInfo():
            headers.update({
                "Authorization":
                "Bearer %s" % control.setting("trakt.token")
            })

        result = client.request(url,
                                post=post,
                                headers=headers,
                                output="extended",
                                error=True)

        resp_code = result[1]
        resp_header = result[2]
        result = result[0]

        if resp_code in [
                "500", "502", "503", "504", "520", "521", "522", "524"
        ]:
            log_utils.log("Temporary Trakt Error: %s" % resp_code,
                          log_utils.LOGWARNING)
            return
        elif resp_code in ["404"]:
            log_utils.log("Object Not Found : %s" % resp_code,
                          log_utils.LOGWARNING)
            return
        elif resp_code in ["429"]:
            log_utils.log("Trakt Rate Limit Reached: %s" % resp_code,
                          log_utils.LOGWARNING)
            return

        if resp_code not in ["401", "405"]:
            return result, resp_header

        oauth = urlparse.urljoin(BASE_URL, "/oauth/token")
        opost = {
            "client_id": V2_API_KEY,
            "client_secret": CLIENT_SECRET,
            "redirect_uri": REDIRECT_URI,
            "grant_type": "refresh_token",
            "refresh_token": control.setting("trakt.refresh"),
        }

        result = client.request(oauth, post=json.dumps(opost), headers=headers)
        result = utils.json_loads_as_str(result)

        token, refresh = result["access_token"], result["refresh_token"]

        control.setSetting(id="trakt.token", value=token)
        control.setSetting(id="trakt.refresh", value=refresh)

        headers["Authorization"] = "Bearer %s" % token

        result = client.request(url,
                                post=post,
                                headers=headers,
                                output="extended",
                                error=True)
        return result[0], result[2]
    except Exception as e:
        log_utils.log("Unknown Trakt Error: %s" % e, log_utils.LOGWARNING)
        pass
コード例 #23
0
def authTrakt():
    try:
        if getTraktCredentialsInfo() == True:
            if control.yesnoDialog(
                    control.lang(30479).encode('utf-8'),
                    control.lang(30481).encode('utf-8'), '', 'Trakt',
                    control.lang(30483).encode('utf-8'),
                    control.lang(30482).encode('utf-8')):
                control.setSetting(id='trakt.user', value='')
                control.setSetting(id='trakt.token', value='')
                control.setSetting(id='trakt.refresh', value='')
            raise Exception()

        if control.yesnoDialog(
                control.lang(30484).encode('utf-8') +
                '[COLOR skyblue]http://trakt.tv/pin/7920[/COLOR]',
                control.lang(30485).encode('utf-8'),
                control.lang(30486).encode('utf-8'), 'Trakt',
                control.lang(30487).encode('utf-8'),
                control.lang(30488).encode('utf-8')):
            raise Exception()

        k = control.keyboard('', control.lang(30487).encode('utf-8'))
        k.doModal()
        pin = k.getText() if k.isConfirmed() else None
        if pin == '' or pin == None: raise Exception()

        trakt_base = 'http://api-v2launch.trakt.tv'

        headers = {
            'Content-Type': 'application/json',
            'trakt-api-key':
            'c029c80fd3d3a5284ee820ba1cf7f0221da8976b8ee5e6c4af714c22fc4f46fa',
            'trakt-api-version': '2'
        }

        post = {
            'client_id':
            'c029c80fd3d3a5284ee820ba1cf7f0221da8976b8ee5e6c4af714c22fc4f46fa',
            'client_secret':
            '90a1840447a1e39d350023263902fe7010338d19789e6260f18df56a8b07a68a',
            'redirect_uri': 'urn:ietf:wg:oauth:2.0:oob',
            'grant_type': 'authorization_code',
            'code': pin
        }

        result = client.request(urlparse.urljoin(trakt_base, '/oauth/token'),
                                post=json.dumps(post),
                                headers=headers)
        result = json.loads(result)

        token, refresh = result['access_token'], result['refresh_token']

        headers['Authorization'] = 'Bearer %s' % token

        result = client.request(urlparse.urljoin(trakt_base, '/users/me'),
                                headers=headers)
        result = json.loads(result)

        user = result['username']

        control.setSetting(id='trakt.user', value=user)
        control.setSetting(id='trakt.token', value=token)
        control.setSetting(id='trakt.refresh', value=refresh)
        raise Exception()
    except:
        control.openSettings('3.1')
コード例 #24
0
def rdAuthorize():
    try:
        CLIENT_ID = 'X245A4XAIBGVM'
        USER_AGENT = 'Kodi Master Reborn/3.0'

        if not '' in credentials()['realdebrid'].values():
            if control.yesnoDialog(
                    control.lang(32531).encode('utf-8'),
                    control.lang(32532).encode('utf-8'), '', 'RealDebrid'):
                control.setSetting(id='realdebrid.id', value='')
                control.setSetting(id='realdebrid.secret', value='')
                control.setSetting(id='realdebrid.token', value='')
                control.setSetting(id='realdebrid.refresh', value='')
                control.setSetting(id='realdebrid.auth', value='')
            raise Exception()

        headers = {'User-Agent': USER_AGENT}
        url = 'https://api.real-debrid.com/oauth/v2/device/code?client_id=%s&new_credentials=yes' % (
            CLIENT_ID)
        result = client.request(url, headers=headers)
        result = json.loads(result)
        verification_url = (control.lang(32533) %
                            result['verification_url']).encode('utf-8')
        user_code = (control.lang(32534) % result['user_code']).encode('utf-8')
        device_code = result['device_code']
        interval = result['interval']

        progressDialog = control.progressDialog
        progressDialog.create('RealDebrid', verification_url, user_code)

        for i in range(0, 3600):
            try:
                if progressDialog.iscanceled(): break
                time.sleep(1)
                if not float(i) % interval == 0: raise Exception()
                url = 'https://api.real-debrid.com/oauth/v2/device/credentials?client_id=%s&code=%s' % (
                    CLIENT_ID, device_code)
                result = client.request(url, headers=headers, error=True)
                result = json.loads(result)
                if 'client_secret' in result: break
            except:
                pass

        try:
            progressDialog.close()
        except:
            pass

        id, secret = result['client_id'], result['client_secret']

        url = 'https://api.real-debrid.com/oauth/v2/token'
        post = urllib.urlencode({
            'client_id':
            id,
            'client_secret':
            secret,
            'code':
            device_code,
            'grant_type':
            'http://oauth.net/grant_type/device/1.0'
        })

        result = client.request(url, post=post, headers=headers)
        result = json.loads(result)

        token, refresh = result['access_token'], result['refresh_token']

        control.setSetting(id='realdebrid.id', value=id)
        control.setSetting(id='realdebrid.secret', value=secret)
        control.setSetting(id='realdebrid.token', value=token)
        control.setSetting(id='realdebrid.refresh', value=refresh)
        control.setSetting(id='realdebrid.auth', value='*************')
        raise Exception()
    except:
        control.openSettings('3.16')
コード例 #25
0
def authTrakt():
    try:
        if getTraktCredentialsInfo() == True:
            if control.yesnoDialog(
                    control.lang(32511).encode("utf-8"),
                    control.lang(32512).encode("utf-8"),
                    "",
                    "Trakt",
            ):
                control.setSetting(id="trakt.user", value="")
                control.setSetting(id="trakt.token", value="")
                control.setSetting(id="trakt.refresh", value="")
            raise Exception()

        result = getTraktAsJson("/oauth/device/code",
                                {"client_id": V2_API_KEY})
        verification_url = (control.lang(32513) %
                            result["verification_url"]).encode("utf-8")
        user_code = (control.lang(32514) % result["user_code"]).encode("utf-8")
        expires_in = int(result["expires_in"])
        device_code = result["device_code"]
        interval = result["interval"]

        progressDialog = control.progressDialog
        progressDialog.create("Trakt", verification_url, user_code)

        for i in range(0, expires_in):
            try:
                if progressDialog.iscanceled():
                    break
                time.sleep(1)
                if not float(i) % interval == 0:
                    raise Exception()
                r = getTraktAsJson(
                    "/oauth/device/token",
                    {
                        "client_id": V2_API_KEY,
                        "client_secret": CLIENT_SECRET,
                        "code": device_code,
                    },
                )
                if "access_token" in r:
                    break
            except:
                pass

        try:
            progressDialog.close()
        except:
            pass

        token, refresh = r["access_token"], r["refresh_token"]

        headers = {
            "Content-Type": "application/json",
            "trakt-api-key": V2_API_KEY,
            "trakt-api-version": 2,
            "Authorization": "Bearer %s" % token,
        }

        result = client.request(urlparse.urljoin(BASE_URL, "/users/me"),
                                headers=headers)
        result = utils.json_loads_as_str(result)

        user = result["username"]

        control.setSetting(id="trakt.user", value=user)
        control.setSetting(id="trakt.token", value=token)
        control.setSetting(id="trakt.refresh", value=refresh)
        raise Exception()
    except:
        control.openSettings("3.1")
コード例 #26
0
def syncMyAccounts(silent=False):
	try:
		all_acct = myaccounts.getAll()
		trakt_acct = all_acct.get('trakt')
		if control.setting('trakt.username') != trakt_acct.get('username'):
			control.setSetting('trakt.isauthed', 'true')
			control.setSetting('trakt.token', trakt_acct.get('token'))
			control.setSetting('trakt.username', trakt_acct.get('username'))
			control.setSetting('trakt.refresh', trakt_acct.get('refresh'))
			control.setSetting('trakt.expires', trakt_acct.get('expires'))
		ad_acct = all_acct.get('alldebrid')
		if control.setting('alldebrid.username') != ad_acct.get('username'):
			control.setSetting('alldebrid.token', ad_acct.get('token'))
			control.setSetting('alldebrid.username', ad_acct.get('username'))
		pm_acct = all_acct.get('premiumize')
		if control.setting('premiumize.username') != pm_acct.get('username'):
			control.setSetting('premiumize.token', pm_acct.get('token'))
			control.setSetting('premiumize.username', pm_acct.get('username'))
		rd_acct = all_acct.get('realdebrid')
		if control.setting('realdebrid.username') != rd_acct.get('username'):
			control.setSetting('realdebrid.token', rd_acct.get('token'))
			control.setSetting('realdebrid.username', rd_acct.get('username'))
			control.setSetting('realdebrid.client_id', rd_acct.get('client_id'))
			control.setSetting('realdebrid.refresh', rd_acct.get('refresh'))
			control.setSetting('realdebrid.secret', rd_acct.get('secret'))
		fanart_acct = all_acct.get('fanart_tv')
		if control.setting('fanart.tv.api.key') != fanart_acct.get('api_key'):
			control.setSetting('fanart.tv.api.key', fanart_acct.get('api_key'))
		tmdb_acct = all_acct.get('tmdb')
		if control.setting('tmdb.api.key') != tmdb_acct.get('api_key'):
			control.setSetting('tmdb.api.key', tmdb_acct.get('api_key'))
		if control.setting('tmdb.username') != tmdb_acct.get('username'):
			control.setSetting('tmdb.username', tmdb_acct.get('username'))
		if control.setting('tmdb.password') != tmdb_acct.get('password'):
			control.setSetting('tmdb.password', tmdb_acct.get('password'))
		if control.setting('tmdb.session_id') != tmdb_acct.get('session_id'):
			control.setSetting('tmdb.session_id', tmdb_acct.get('session_id'))
		tvdb_acct = all_acct.get('tvdb')
		if control.setting('tvdb.api.key') != tvdb_acct.get('api_key'):
			control.setSetting('tvdb.api.key', tvdb_acct.get('api_key'))
		imdb_acct = all_acct.get('imdb')
		if control.setting('imdb.user') != imdb_acct.get('user'):
			control.setSetting('imdb.user', imdb_acct.get('user'))
		fu_acct = all_acct.get('furk')
		if control.setting('furk.username') != fu_acct.get('username'):
			control.setSetting('furk.username', fu_acct.get('username'))
			control.setSetting('furk.password', fu_acct.get('password'))
		if fu_acct.get('api_key', None):
			if control.setting('furk.api') != fu_acct.get('api_key'):
				control.setSetting('furk.api', fu_acct.get('api_key'))
		if not silent: control.notification(message=32114)
	except:
			log_utils.error()
コード例 #27
0
    def get_instance_id(self):
        globoplay_instance_id = control.setting('globoplay_instance_id')

        if not globoplay_instance_id:
            checkin_url = 'https://device-provisioning.googleapis.com/checkin'
            post_data = {
                "checkin": {
                    "iosbuild": {
                        "model": "iPhone10,6",
                        "os_version": "IOS_14.4"
                    },
                    "last_checkin_msec": 0,
                    "type": 2,
                    "user_number": 0
                },
                "digest": "",
                "fragment": 0,
                "id": 0,
                "locale": "pt",
                "security_token": 0,
                "time_zone": "America/Sao_Paulo",
                "user_serial_number": 0,
                "version": 2
            }
            control.log('POST %s' % checkin_url)
            response = requests.post(
                checkin_url,
                json=post_data,
                headers={
                    'User-Agent': 'Globoplay/1 CFNetwork/1220.1 Darwin/20.3.0'
                })

            control.log(response.content)

            response.raise_for_status()
            response = response.json()

            security_token = response.get('security_token')
            android_id = response.get('android_id')
            version_info = response.get('version_info')

            installations_url = 'https://firebaseinstallations.googleapis.com/v1/projects/globo-play/installations/'
            post_data = {
                "appId": "1:846115935537:ios:c91952b14380e445",
                "authVersion": "FIS_v2",
                "sdkVersion": "i:7.1.0"
            }
            control.log('POST %s' % installations_url)
            response = requests.post(
                installations_url,
                json=post_data,
                headers={
                    'User-Agent': 'Globoplay/1 CFNetwork/1220.1 Darwin/20.3.0',
                    'x-goog-api-key':
                    'AIzaSyDbGxO8Bw7cfT5BYiAQTnReVItGEXlpnhY',
                    'x-firebase-client':
                    'apple-platform/ios apple-sdk/18B79 appstore/true deploy/cocoapods device/iPhone10,6 fire-abt/7.1.0 fire-analytics/7.3.0 fire-fcm/7.1.0 fire-iid/7.1.0 fire-install/7.1.0 fire-ios/7.1.0 fire-perf/7.0.1 fire-rc/7.1.0 firebase-crashlytics/7.1.0 os-version/14.4 swift/true xcode/12B45b',
                    'x-firebase-client-log-type': '3',
                    'x-ios-bundle-identifier': 'com.globo.hydra'
                })

            control.log(response.content)
            response.raise_for_status()

            response = response.json()

            fid = response.get('fid')
            auth_token = response.get('authToken', {}).get('token')

            register_url = 'https://fcmtoken.googleapis.com/register'
            post_data = {
                'X-osv': '14.4',
                'device': android_id,
                'X-scope': '*',
                'plat': '2',
                'app': 'com.globo.hydra',
                'app_ver': '3.91.0',
                'X-cliv': 'fiid-7.1.0',
                'sender': '846115935537',
                'X-subtype': '846115935537',
                'appid': fid,
                'gmp_app_id': '1:846115935537:ios:c91952b14380e445'
            }

            headers = {
                'x-firebase-client':
                'apple-platform/ios apple-sdk/18B79 appstore/true deploy/cocoapods device/iPhone10,6 fire-abt/7.1.0 fire-analytics/7.3.0 fire-fcm/7.1.0 fire-iid/7.1.0 fire-install/7.1.0 fire-ios/7.1.0 fire-perf/7.0.1 fire-rc/7.1.0 firebase-crashlytics/7.1.0 os-version/14.4 swift/true xcode/12B45b',
                'authorization':
                'AidLogin %s:%s' % (android_id, security_token),
                'x-firebase-client-log-type': '1',
                'app': 'com.globo.hydra',
                'user-agent': 'Globoplay/1 CFNetwork/1220.1 Darwin/20.3.0',
                'info': version_info,
                'x-goog-firebase-installations-auth': auth_token,
                'content-type': 'application/x-www-form-urlencoded'
            }

            control.log('POST %s' % register_url)
            control.log(headers)
            control.log(post_data)

            response = requests.post(register_url,
                                     data=post_data,
                                     headers=headers).content

            if not response.startswith('token='):
                raise Exception(response)

            globoplay_instance_id = response.replace('token=', '')

            control.log('NEW INSTANCE_ID: %s' % globoplay_instance_id)

            control.setSetting('globoplay_instance_id', globoplay_instance_id)

        return globoplay_instance_id
コード例 #28
0
content = params.get('content')

windowedtrailer = params.get('windowedtrailer')
windowedtrailer = int(windowedtrailer) if windowedtrailer in ("0", "1") else 0

if action == None:
    from resources.lib.indexers import navigator
    from resources.lib.modules import cache
    run = control.setting('first.info')
    navigator.navigator().root()
    if run == '': run = 'true'
    if cache._find_cache_version(): run = 'true'

    if run == 'true':
        navigator.navigator().news_local()
        control.setSetting(id='first.info', value='false')
    cache.cache_version_check()
    navigator.navigator().root()

elif action == 'newsNavigator':
    from resources.lib.indexers import navigator
    navigator.navigator().news()

elif action == 'movieNavigator':
    from resources.lib.indexers import navigator
    navigator.navigator().movies()

elif action == 'movieliteNavigator':
    from resources.lib.indexers import navigator
    navigator.navigator().movies(lite=True)
コード例 #29
0
 def _save_credentials(self):
     control.setSetting(self.get_credentials_key(),
                        pickle.dumps(self.credentials))
     control.setSetting(self.get_userdata_key(),
                        pickle.dumps(self.user_data))
コード例 #30
0
def getTrakt(url, post = None, cache = True, check = True, timestamp = None, extended = False, direct = False, authentication = None):
    try:
        if not url.startswith(BASE_URL):
            url = urlparse.urljoin(BASE_URL, url)

        if authentication:
            valid = True
            token = authentication['token']
            refresh = authentication['refresh']
        else:
            valid = getTraktCredentialsInfo() is True
            token = control.setting('trakt.token')
            refresh = control.setting('trakt.refresh')

        headers = {'Content-Type': 'application/json', 'trakt-api-key': V2_API_KEY, 'trakt-api-version': '2'}

        if not post is None: post = json.dumps(post)

        if direct or not valid:
            result = client.request(url, post = post, headers = headers)
            return result

        headers['Authorization'] = 'Bearer %s' % token
        result = client.request(url, post = post, headers = headers, output = 'extended', error = True)
        if result and not (result[1] == '401' or result[1] == '405'):
            if check: _cacheCheck()
            if extended: return result[0], result[2]
            else: return result[0]

        try: code = str(result[1])
        except: code = ''

        if code.startswith('5') or (result and isinstance(result, basestring) and '<html' in result) or not result:
            return _error(url = url, post = post, timestamp = timestamp, message = 33676)

        oauth = urlparse.urljoin(BASE_URL, '/oauth/token')
        opost = {'client_id': V2_API_KEY, 'client_secret': CLIENT_SECRET, 'redirect_uri': 'urn:ietf:wg:oauth:2.0:oob', 'grant_type': 'refresh_token', 'refresh_token': refresh}

        result = client.request(oauth, post = json.dumps(opost), headers = headers, error = True)

        try: code = str(result[1])
        except: code = ''

        if code.startswith('5') or not result or (result and isinstance(result, basestring) and '<html' in result):
            return _error(url = url, post = post, timestamp = timestamp, message = 33676)
        elif result and code in ['404']:
            return _error(url = url, post = post, timestamp = timestamp, message = 33786)
        elif result and code in ['401', '405']:
            return _error(url = url, post = post, timestamp = timestamp, message = 33677)

        result = json.loads(result)

        token, refresh = result['access_token'], result['refresh_token']
        control.setSetting('trakt.token', token)
        control.setSetting('trakt.refresh', refresh)

        headers['Authorization'] = 'Bearer %s' % token

        result = client.request(url, post = post, headers = headers, output = 'extended')
        if check: _cacheCheck()

        if extended: return result[0], result[2]
        else: return result[0]
    except:
        import traceback
        traceback.print_exc()

    return None
コード例 #31
0
ファイル: trakt.py プロジェクト: azumimuo/family-xbmc-addon
def getTrakt(url, post = None, cache = True, check = True, timestamp = None, extended = False, direct = False, authentication = None):
	try:
		if not url.startswith('http://api-v2launch.trakt.tv'):
			url = urlparse.urljoin('http://api-v2launch.trakt.tv', url)

		if authentication:
			valid = True
			token = authentication['token']
			refresh = authentication['refresh']
		else:
			valid = getTraktCredentialsInfo() == True
			token = control.setting('accounts.informants.trakt.token')
			refresh = control.setting('accounts.informants.trakt.refresh')

		headers = {'Content-Type': 'application/json', 'trakt-api-key': base64.b64decode(traktCI), 'trakt-api-version': '2'}

		if not post == None: post = json.dumps(post)

		if direct or not valid:
			result = client.request(url, post = post, headers = headers)
			return result

		headers['Authorization'] = 'Bearer %s' % token

		result = client.request(url, post = post, headers = headers, output = 'extended', error = True)
		if result and not (result[1] == '401' or result[1] == '405'):
			if check: _cacheCheck()
			if extended: return result[0], result[2]
			else: return result[0]

		try: code = str(result[1])
		except: code = ''

		if code.startswith('5') or (result and isinstance(result, basestring) and '<html' in result) or not result:
			return _error(url = url, post = post, timestamp = timestamp, message = 33676)

		oauth = 'http://api-v2launch.trakt.tv/oauth/token'
		opost = {'client_id': base64.b64decode(traktCI), 'client_secret': base64.b64decode(traktCS), 'redirect_uri': 'urn:ietf:wg:oauth:2.0:oob', 'grant_type': 'refresh_token', 'refresh_token': refresh}

		result = client.request(oauth, post = json.dumps(opost), headers = headers, error = True)

		try: code = str(result[1])
		except: code = ''

		if code.startswith('5') or not result or (result and isinstance(result, basestring) and '<html' in result):
			return _error(url = url, post = post, timestamp = timestamp, message = 33676)
		elif result and code in ['404']:
			return _error(url = url, post = post, timestamp = timestamp, message = 33786)
		elif result and code in ['401', '405']:
			return _error(url = url, post = post, timestamp = timestamp, message = 33677)

		result = json.loads(result)

		token, refresh = result['access_token'], result['refresh_token']
		control.setSetting(id='accounts.informants.trakt.token', value = token)
		control.setSetting(id='accounts.informants.trakt.refresh', value = refresh)

		headers['Authorization'] = 'Bearer %s' % token

		result = client.request(url, post = post, headers = headers, output = 'extended')

		if check: _cacheCheck()

		if extended: return result[0], result[2]
		else: return result[0]
	except:
		tools.Logger.error()

	return None
コード例 #32
0
    def revoke_auth(self):
        control.setSetting('alldebrid.token', '')
        control.setSetting('alldebrid.username', '')
        control.okDialog(title=40059, message=40009)


# # from resolveURL
# def get_all_hosters(self):
# hosters = []
# url = '{0}/user/hosts?agent={1}&apikey={2}'.format(api_url, urllib_parse.quote_plus(AGENT), self.get_setting('token'))
# try:
# result = self.net.http_GET(url, headers=self.headers).content
# js_data = json.loads(result)
# if js_data.get('status', False) == "success":
# js_data = js_data.get('data')
# regexes = [value.get('regexp') for _, value in js_data.get('hosts', {}).items()
# if value.get('status', False)]
# hosters = [re.compile(regex) for regex in regexes]
# logger.log_debug('AllDebrid hosters : {0}'.format(len(hosters)))
# regexes = [value.get('regexp') for _, value in js_data.get('streams', {}).items()]
# streamers = []
# for regex in regexes:
# try:
# streamers.append(re.compile(regex))
# except:
# pass
# logger.log_debug('AllDebrid Streamers : {0}'.format(len(streamers)))
# hosters.extend(streamers)
# logger.log_debug('AllDebrid Total hosters : {0}'.format(len(hosters)))
# else:
# logger.log_error('Error getting AD Hosters')
# except Exception as e:
# logger.log_error('Error getting AD Hosters: {0}'.format(e))
# return hosters

# # from resolveURL
# def get_hosts(self):
# hosts = []
# url = '{0}/hosts/domains?agent={1}&apikey={2}'.format(api_url, urllib_parse.quote_plus(AGENT), self.get_setting('token'))
# try:
# js_result = self.net.http_GET(url, headers=self.headers).content
# js_data = json.loads(js_result)
# if js_data.get('status', False) == "success":
# # hosts = [host.replace('www.', '') for host in js_data.get('hosts', [])]
# hosts = js_data.get('data').get('hosts')
# hosts.extend(js_data.get('data').get('streams'))
# if self.get_setting('torrents') == 'true':
# hosts.extend(['torrent', 'magnet'])
# logger.log_debug('AllDebrid hosts : {0}'.format(hosts))
# else:
# logger.log_error('Error getting AD Hosts')
# except Exception as e:
# logger.log_error('Error getting AD Hosts: {0}'.format(e))
# return hosts

# # from resolveURL
# def valid_url(self, url, host):
# logger.log_debug('in valid_url {0} : {1}'.format(url, host))
# if url:
# if url.lower().startswith('magnet:') and self.get_setting('torrents') == 'true':
# return True
# if self.hosters is None:
# self.hosters = self.get_all_hosters()
# for regexp in self.hosters:
# if re.search(regexp, url):
# logger.log_debug('AllDebrid Match found')
# return True
# elif host:
# if self.hosts is None:
# self.hosts = self.get_hosts()
# if any(host in item for item in self.hosts):
# return True
# return False
コード例 #33
0
#     cache.cache_version_check()
#     navigator.navigator().root()

if action == None:
    from resources.lib.modules import cache
    from resources.lib.indexers import navigator
    cache.cache_version_check()
    navigator.navigator().root()

elif action == "toggleAllHosters":
    sourcelist = []
    sourceList = sources.hoster_providers
    for i in sourceList:
        source_setting = 'provider.' + i
        try:
            control.setSetting(source_setting, params['setting'])
        except:
            pass
#     xbmc.log('All Hoster providers = %s' % sourceList,2)
#     control.openSettings("plugin.video.infinity")

elif action == 'newsNavigator':
    from resources.lib.indexers import navigator
    navigator.navigator().news()

elif action == 'movieNavigator':
    from resources.lib.indexers import navigator
    navigator.navigator().movies()

elif action == 'movieliteNavigator':
    from resources.lib.indexers import navigator
コード例 #34
0
windowedtrailer = int(windowedtrailer) if windowedtrailer in ("0", "1") else 0
notificationSound = False if control.setting(
    'notification.sound') == 'false' else True

if action is None:
    from resources.lib.menus import navigator
    from resources.lib.modules import cache
    run = control.setting('first.info')
    if run == '':
        run = 'true'  #clean install scenerio
    if cache._find_cache_version():
        run = 'true'  #check whether plugin.video.venom has been updated-use to be for script.module.venom
    if run == 'true':
        from resources.lib.modules import changelog
        changelog.get()
        control.setSetting(id='first.info', value='false')
    cache.cache_version_check()
    navigator.Navigator().root()

####################################################
#---News and Updates
####################################################
elif action == 'infoCheck':
    from resources.lib.menus import navigator
    navigator.Navigator().infoCheck('')

elif action == 'ShowNews':
    from resources.lib.modules import newsinfo
    newsinfo.news()

elif action == 'ShowChangelog':
コード例 #35
0
ファイル: trakt.py プロジェクト: azumimuo/family-xbmc-addon
def authTrakt():
    try:
        if getTraktCredentialsInfo() == True:
            if control.yesnoDialog('An account already exists.', 'Do you want to reset?', '', 'Trakt'):
                control.setSetting(id='trakt.user', value='')
                control.setSetting(id='trakt.token', value='')
                control.setSetting(id='trakt.refresh', value='')
            raise Exception()

        result = getTrakt('/oauth/device/code', {'client_id': '3b76e1b99fa4a5b27f63e04307754751514d88916195ea8abc1c48eeef68f0d9'})
        result = json.loads(result)
        verification_url = ('1) Visit : [COLOR skyblue]%s[/COLOR]' % result['verification_url']).encode('utf-8')
        user_code = ('2) When prompted enter : [COLOR skyblue]%s[/COLOR]' % result['user_code']).encode('utf-8')
        expires_in = int(result['expires_in'])
        device_code = result['device_code']
        interval = result['interval']

        progressDialog = control.progressDialog
        progressDialog.create('Trakt', verification_url, user_code)

        for i in range(0, expires_in):
            try:
                if progressDialog.iscanceled(): break
                time.sleep(1)
                if not float(i) % interval == 0: raise Exception()
                r = getTrakt('/oauth/device/token', {'client_id': '3b76e1b99fa4a5b27f63e04307754751514d88916195ea8abc1c48eeef68f0d9', 'client_secret': 'b0be7e72b647bcb44f2846b29729028e5d75fa710b91812027ae79cc48456a16', 'code': device_code})
                r = json.loads(r)
                if 'access_token' in r: break
            except:
                pass

        try: progressDialog.close()
        except: pass

        token, refresh = r['access_token'], r['refresh_token']

        headers = {'Content-Type': 'application/json', 'trakt-api-key': '3b76e1b99fa4a5b27f63e04307754751514d88916195ea8abc1c48eeef68f0d9', 'trakt-api-version': '2', 'Authorization': 'Bearer %s' % token}

        result = client.request('http://api-v2launch.trakt.tv/users/me', headers=headers)
        result = json.loads(result)

        user = result['username']

        control.setSetting(id='trakt.user', value=user)
        control.setSetting(id='trakt.token', value=token)
        control.setSetting(id='trakt.refresh', value=refresh)
        raise Exception()
    except:
        control.openSettings('0.1')
コード例 #36
0
ファイル: trakt.py プロジェクト: CYBERxNUKE/xbmc-addon
def authTrakt():
    try:
        if getTraktCredentialsInfo() == True:
            if control.yesnoDialog(control.lang(32511).encode('utf-8'), control.lang(32512).encode('utf-8'), '', 'Trakt'):
                control.setSetting(id='trakt.user', value='')
                control.setSetting(id='trakt.token', value='')
                control.setSetting(id='trakt.refresh', value='')
            raise Exception()

        result = getTraktAsJson('/oauth/device/code', {'client_id': V2_API_KEY})
        verification_url = (control.lang(32513) % result['verification_url']).encode('utf-8')
        user_code = (control.lang(32514) % result['user_code']).encode('utf-8')
        expires_in = int(result['expires_in'])
        device_code = result['device_code']
        interval = result['interval']

        progressDialog = control.progressDialog
        progressDialog.create('Trakt', verification_url, user_code)

        for i in range(0, expires_in):
            try:
                if progressDialog.iscanceled(): break
                time.sleep(1)
                if not float(i) % interval == 0: raise Exception()
                r = getTraktAsJson('/oauth/device/token', {'client_id': V2_API_KEY, 'client_secret': CLIENT_SECRET, 'code': device_code})
                if 'access_token' in r: break
            except:
                pass

        try: progressDialog.close()
        except: pass

        token, refresh = r['access_token'], r['refresh_token']

        headers = {'Content-Type': 'application/json', 'trakt-api-key': V2_API_KEY, 'trakt-api-version': 2, 'Authorization': 'Bearer %s' % token}


        result = client.request(urlparse.urljoin(BASE_URL, '/users/me'), headers=headers)
        result = utils.json_loads_as_str(result)

        user = result['username']

        control.setSetting(id='trakt.user', value=user)
        control.setSetting(id='trakt.token', value=token)
        control.setSetting(id='trakt.refresh', value=refresh)
        raise Exception()
    except:
        control.openSettings('3.1')
コード例 #37
0
ファイル: player.py プロジェクト: azumimuo/family-xbmc-addon
 def onPlayBackStarted(self):
     control.setSetting("anime.lastvisited", str(self.anime_id))
     pass
コード例 #38
0
ファイル: player.py プロジェクト: varunrai/Masterani-Redux
 def onPlayBackStarted(self):
     control.execute('Dialog.Close(all,true)')
     control.setSetting("anime.lastvisited", str(self.anime_id))
     pass
コード例 #39
0
ファイル: player.py プロジェクト: CandyFace/Masterani-Redux
 def onPlayBackStarted(self):
     control.execute('Dialog.Close(all,true)')
     control.setSetting("anime.lastvisited", str(self.anime_id))
     pass
コード例 #40
0
ファイル: trakt.py プロジェクト: SuzwagKururugi/Masterani
def authTrakt():
    try:
        if getTraktCredentialsInfo() == True:
            if control.yesnoDialog('An account already exists.',
                                   'Do you want to reset?', '', 'Trakt'):
                control.setSetting(id='trakt.user', value='')
                control.setSetting(id='trakt.token', value='')
                control.setSetting(id='trakt.refresh', value='')
            raise Exception()

        result = getTrakt(
            '/oauth/device/code', {
                'client_id':
                '3b76e1b99fa4a5b27f63e04307754751514d88916195ea8abc1c48eeef68f0d9'
            })
        result = json.loads(result)
        verification_url = ('1) Visit : [COLOR skyblue]%s[/COLOR]' %
                            result['verification_url']).encode('utf-8')
        user_code = ('2) When prompted enter : [COLOR skyblue]%s[/COLOR]' %
                     result['user_code']).encode('utf-8')
        expires_in = int(result['expires_in'])
        device_code = result['device_code']
        interval = result['interval']

        progressDialog = control.progressDialog
        progressDialog.create('Trakt', verification_url, user_code)

        for i in range(0, expires_in):
            try:
                if progressDialog.iscanceled(): break
                time.sleep(1)
                if not float(i) % interval == 0: raise Exception()
                r = getTrakt(
                    '/oauth/device/token', {
                        'client_id':
                        '3b76e1b99fa4a5b27f63e04307754751514d88916195ea8abc1c48eeef68f0d9',
                        'client_secret':
                        'b0be7e72b647bcb44f2846b29729028e5d75fa710b91812027ae79cc48456a16',
                        'code': device_code
                    })
                r = json.loads(r)
                if 'access_token' in r: break
            except:
                pass

        try:
            progressDialog.close()
        except:
            pass

        token, refresh = r['access_token'], r['refresh_token']

        headers = {
            'Content-Type': 'application/json',
            'trakt-api-key':
            '3b76e1b99fa4a5b27f63e04307754751514d88916195ea8abc1c48eeef68f0d9',
            'trakt-api-version': '2',
            'Authorization': 'Bearer %s' % token
        }

        result = client.request('http://api-v2launch.trakt.tv/users/me',
                                headers=headers)
        result = json.loads(result)

        user = result['username']

        control.setSetting(id='trakt.user', value=user)
        control.setSetting(id='trakt.token', value=token)
        control.setSetting(id='trakt.refresh', value=refresh)
        raise Exception()
    except:
        control.openSettings('0.1')
コード例 #41
0
 def clearCacheSearch(self):
     control.idle()
     if control.yesnoDialog(control.lang(32056).encode('utf-8'), '', ''):
         control.setSetting('tvsearch', '')
         control.setSetting('moviesearch', '')
         control.refresh()
コード例 #42
0
 def save_theme(self):
     control.setSetting('appearance.1', self.selectedArtwork)
     self.close()
     control.refresh()
コード例 #43
0
ファイル: trakt.py プロジェクト: vanhung1710/MyRepository
def authTrakt():
    try:
        if getTraktCredentialsInfo() == True:
            if control.yesnoDialog(control.lang(32511).encode('utf-8'), control.lang(32512).encode('utf-8'), '', 'Trakt'):
                control.setSetting(id='trakt.user', value='')
                control.setSetting(id='trakt.token', value='')
                control.setSetting(id='trakt.refresh', value='')
            raise Exception()

        result = getTrakt('/oauth/device/code', {'client_id': 'c029c80fd3d3a5284ee820ba1cf7f0221da8976b8ee5e6c4af714c22fc4f46fa'})
        result = json.loads(result)
        verification_url = (control.lang(32513) % result['verification_url']).encode('utf-8')
        user_code = (control.lang(32514) % result['user_code']).encode('utf-8')
        expires_in = int(result['expires_in'])
        device_code = result['device_code']
        interval = result['interval']

        progressDialog = control.progressDialog
        progressDialog.create('Trakt', verification_url, user_code)

        for i in range(0, expires_in):
            try:
                if progressDialog.iscanceled(): break
                time.sleep(1)
                if not float(i) % interval == 0: raise Exception()
                r = getTrakt('/oauth/device/token', {'client_id': 'c029c80fd3d3a5284ee820ba1cf7f0221da8976b8ee5e6c4af714c22fc4f46fa', 'client_secret': '90a1840447a1e39d350023263902fe7010338d19789e6260f18df56a8b07a68a', 'code': device_code})
                r = json.loads(r)
                if 'access_token' in r: break
            except:
                pass

        try: progressDialog.close()
        except: pass

        token, refresh = r['access_token'], r['refresh_token']

        headers = {'Content-Type': 'application/json', 'trakt-api-key': 'c029c80fd3d3a5284ee820ba1cf7f0221da8976b8ee5e6c4af714c22fc4f46fa', 'trakt-api-version': '2', 'Authorization': 'Bearer %s' % token}

        result = client.request('http://api-v2launch.trakt.tv/users/me', headers=headers)
        result = json.loads(result)

        user = result['username']

        control.setSetting(id='trakt.user', value=user)
        control.setSetting(id='trakt.token', value=token)
        control.setSetting(id='trakt.refresh', value=refresh)
        raise Exception()
    except:
        control.openSettings('3.1')
コード例 #44
0
ファイル: trakt.py プロジェクト: JACKEVOLVE/Kodi_Repo
def authTrakt():
    try:
        if getTraktCredentialsInfo() == True:
            if control.yesnoDialog(
                    control.lang(32511).encode('utf-8'),
                    control.lang(32512).encode('utf-8'), '', 'Trakt'):
                control.setSetting(id='trakt.user', value='')
                control.setSetting(id='trakt.token', value='')
                control.setSetting(id='trakt.refresh', value='')
            raise Exception()

        result = getTraktAsJson('/oauth/device/code',
                                {'client_id': V2_API_KEY})
        verification_url = (control.lang(32513) %
                            result['verification_url']).encode('utf-8')
        user_code = (control.lang(32514) % result['user_code']).encode('utf-8')
        expires_in = int(result['expires_in'])
        device_code = result['device_code']
        interval = result['interval']

        progressDialog = control.progressDialog
        progressDialog.create('Trakt', verification_url, user_code)

        for i in range(0, expires_in):
            try:
                if progressDialog.iscanceled(): break
                time.sleep(1)
                if not float(i) % interval == 0: raise Exception()
                r = getTraktAsJson(
                    '/oauth/device/token', {
                        'client_id': V2_API_KEY,
                        'client_secret': CLIENT_SECRET,
                        'code': device_code
                    })
                if 'access_token' in r: break
            except:
                pass

        try:
            progressDialog.close()
        except:
            pass

        token, refresh = r['access_token'], r['refresh_token']

        headers = {
            'Content-Type': 'application/json',
            'trakt-api-key': V2_API_KEY,
            'trakt-api-version': 2,
            'Authorization': 'Bearer %s' % token
        }

        result = client.request(urlparse.urljoin(BASE_URL, '/users/me'),
                                headers=headers)
        result = utils.json_loads_as_str(result)

        user = result['username']

        control.setSetting(id='trakt.user', value=user)
        control.setSetting(id='trakt.token', value=token)
        control.setSetting(id='trakt.refresh', value=refresh)
        raise Exception()
    except:
        control.openSettings('3.1')
コード例 #45
0
ファイル: trakt.py プロジェクト: c0ns0le/YCBuilds
def authTrakt():
    try:
        if getTraktCredentialsInfo() == True:
            if control.yesnoDialog(control.lang(30479).encode('utf-8'), control.lang(30481).encode('utf-8'), '', 'Trakt', control.lang(30483).encode('utf-8'), control.lang(30482).encode('utf-8')):
                control.setSetting(id='trakt.user', value='')
                control.setSetting(id='trakt.token', value='')
                control.setSetting(id='trakt.refresh', value='')
            raise Exception()

        if control.yesnoDialog(control.lang(30484).encode('utf-8') + '[COLOR skyblue]http://trakt.tv/pin/7920[/COLOR]', control.lang(30485).encode('utf-8'), control.lang(30486).encode('utf-8'), 'Trakt', control.lang(30487).encode('utf-8'), control.lang(30488).encode('utf-8')): raise Exception()

        k = control.keyboard('', control.lang(30487).encode('utf-8'))
        k.doModal() ; pin = k.getText() if k.isConfirmed() else None
        if pin == '' or pin == None: raise Exception()

        trakt_base = 'http://api-v2launch.trakt.tv'

        headers = {'Content-Type': 'application/json', 'trakt-api-key': 'c029c80fd3d3a5284ee820ba1cf7f0221da8976b8ee5e6c4af714c22fc4f46fa', 'trakt-api-version': '2'}

        post = {'client_id': 'c029c80fd3d3a5284ee820ba1cf7f0221da8976b8ee5e6c4af714c22fc4f46fa', 'client_secret': '90a1840447a1e39d350023263902fe7010338d19789e6260f18df56a8b07a68a', 'redirect_uri': 'urn:ietf:wg:oauth:2.0:oob', 'grant_type': 'authorization_code', 'code': pin}

        result = client.request(urlparse.urljoin(trakt_base, '/oauth/token'), post=json.dumps(post), headers=headers)
        result = json.loads(result)

        token, refresh = result['access_token'], result['refresh_token']

        headers['Authorization'] = 'Bearer %s' % token

        result = client.request(urlparse.urljoin(trakt_base, '/users/me'), headers=headers)
        result = json.loads(result)

        user = result['username']

        control.setSetting(id='trakt.user', value=user)
        control.setSetting(id='trakt.token', value=token)
        control.setSetting(id='trakt.refresh', value=refresh)
        raise Exception()
    except:
        control.openSettings('3.1')
コード例 #46
0
ファイル: trakt.py プロジェクト: JACKEVOLVE/Kodi_Repo
def __getTrakt(url, post=None):
    try:
        url = urlparse.urljoin(BASE_URL, url)
        post = json.dumps(post) if post else None
        headers = {
            'Content-Type': 'application/json',
            'trakt-api-key': V2_API_KEY,
            'trakt-api-version': 2
        }

        if getTraktCredentialsInfo():
            headers.update({
                'Authorization':
                'Bearer %s' % control.setting('trakt.token')
            })

        result = client.request(url,
                                post=post,
                                headers=headers,
                                output='extended',
                                error=True)

        resp_code = result[1]
        resp_header = result[2]
        result = result[0]

        if resp_code in [
                '500', '502', '503', '504', '520', '521', '522', '524'
        ]:
            log_utils.log('Temporary Trakt Error: %s' % resp_code,
                          log_utils.LOGWARNING)
            return
        elif resp_code in ['404']:
            log_utils.log('Object Not Found : %s' % resp_code,
                          log_utils.LOGWARNING)
            return

        if resp_code not in ['401', '405']:
            return result, resp_header

        oauth = urlparse.urljoin(BASE_URL, '/oauth/token')
        opost = {
            'client_id': V2_API_KEY,
            'client_secret': CLIENT_SECRET,
            'redirect_uri': REDIRECT_URI,
            'grant_type': 'refresh_token',
            'refresh_token': control.setting('trakt.refresh')
        }

        result = client.request(oauth, post=json.dumps(opost), headers=headers)
        result = utils.json_loads_as_str(result)

        token, refresh = result['access_token'], result['refresh_token']

        control.setSetting(id='trakt.token', value=token)
        control.setSetting(id='trakt.refresh', value=refresh)

        headers['Authorization'] = 'Bearer %s' % token

        result = client.request(url,
                                post=post,
                                headers=headers,
                                output='extended',
                                error=True)
        return result[0], result[2]
    except Exception as e:
        log_utils.log('Unknown Trakt Error: %s' % e, log_utils.LOGWARNING)
        pass
コード例 #47
0
ファイル: debrid.py プロジェクト: freeworldxbmc/maximumTv
def rdAuthorize():
    try:
        CLIENT_ID = 'X245A4XAIBGVM'
        USER_AGENT = 'Kodi Exodus/3.0'

        if not '' in credentials()['realdebrid'].values():
            if control.yesnoDialog(control.lang(30411).encode('utf-8'), control.lang(30413).encode('utf-8'), '', 'RealDebrid', control.lang(30415).encode('utf-8'), control.lang(30414).encode('utf-8')):
                control.setSetting(id='realdebrid.id', value='')
                control.setSetting(id='realdebrid.secret', value='')
                control.setSetting(id='realdebrid.token', value='')
                control.setSetting(id='realdebrid.refresh', value='')
                control.setSetting(id='realdebrid.auth', value='')
            raise Exception()

        headers = {'User-Agent': USER_AGENT}
        url = 'https://api.real-debrid.com/oauth/v2/device/code?client_id=%s&new_credentials=yes' % (CLIENT_ID)
        result = client.request(url, headers=headers)
        result = json.loads(result)
        verification_url = (control.lang(30416) + '[COLOR skyblue]%s[/COLOR]' % result['verification_url']).encode('utf-8')
        user_code = (control.lang(30417) + '[COLOR skyblue]%s[/COLOR]' % result['user_code']).encode('utf-8')
        device_code = result['device_code']
        interval = result['interval']

        progressDialog = control.progressDialog
        progressDialog.create('RealDebrid', verification_url, user_code)

        for i in range(0, 3600):
            try:
                if progressDialog.iscanceled(): break
                time.sleep(1)
                if not float(i) % interval == 0: raise Exception()
                url = 'https://api.real-debrid.com/oauth/v2/device/credentials?client_id=%s&code=%s' % (CLIENT_ID, device_code)
                result = client.request(url, headers=headers, error=True)
                result = json.loads(result)
                if 'client_secret' in result: break
            except:
                pass

        try: progressDialog.close()
        except: pass

        id, secret = result['client_id'], result['client_secret'] 

        url = 'https://api.real-debrid.com/oauth/v2/token'
        post = urllib.urlencode({'client_id': id, 'client_secret': secret, 'code': device_code, 'grant_type': 'http://oauth.net/grant_type/device/1.0'})

        result = client.request(url, post=post, headers=headers)
        result = json.loads(result)

        token, refresh = result['access_token'], result['refresh_token']

        control.setSetting(id='realdebrid.id', value=id)
        control.setSetting(id='realdebrid.secret', value=secret)
        control.setSetting(id='realdebrid.token', value=token)
        control.setSetting(id='realdebrid.refresh', value=refresh)
        control.setSetting(id='realdebrid.auth', value='*************')
        raise Exception()
    except:
        control.openSettings('3.13')
コード例 #48
0
 def clearCacheSearch(self):
     control.idle()
     if control.yesnoDialog(control.lang(32056).encode('utf-8'), '', ''):
         control.setSetting('tvsearch', '')
         control.setSetting('moviesearch', '')
         control.refresh()
コード例 #49
0
ファイル: trakt.py プロジェクト: sokam/kodiprofile
def authTrakt():
    try:
        if getTraktCredentialsInfo() == True:
            if control.yesnoDialog(control.lang(30479).encode('utf-8'), control.lang(30481).encode('utf-8'), '', 'Trakt', control.lang(30483).encode('utf-8'), control.lang(30482).encode('utf-8')):
                control.setSetting(id='trakt.user', value='')
                control.setSetting(id='trakt.token', value='')
                control.setSetting(id='trakt.refresh', value='')
            raise Exception()

        result = getTrakt('/oauth/device/code', {'client_id': 'c029c80fd3d3a5284ee820ba1cf7f0221da8976b8ee5e6c4af714c22fc4f46fa'})
        result = json.loads(result)
        verification_url = (control.lang(30416) + '[COLOR skyblue]%s[/COLOR]' % result['verification_url']).encode('utf-8')
        user_code = (control.lang(30417) + '[COLOR skyblue]%s[/COLOR]' % result['user_code']).encode('utf-8')
        expires_in = int(result['expires_in'])
        device_code = result['device_code']
        interval = result['interval']

        progressDialog = control.progressDialog
        progressDialog.create('Trakt', verification_url, user_code)

        for i in range(0, expires_in):
            try:
                if progressDialog.iscanceled(): break
                time.sleep(1)
                if not float(i) % interval == 0: raise Exception()
                r = getTrakt('/oauth/device/token', {'client_id': 'c029c80fd3d3a5284ee820ba1cf7f0221da8976b8ee5e6c4af714c22fc4f46fa', 'client_secret': '90a1840447a1e39d350023263902fe7010338d19789e6260f18df56a8b07a68a', 'code': device_code})
                r = json.loads(r)
                if 'access_token' in r: break
            except:
                pass

        try: progressDialog.close()
        except: pass

        token, refresh = r['access_token'], r['refresh_token']

        headers = {'Content-Type': 'application/json', 'trakt-api-key': 'c029c80fd3d3a5284ee820ba1cf7f0221da8976b8ee5e6c4af714c22fc4f46fa', 'trakt-api-version': '2', 'Authorization': 'Bearer %s' % token}

        result = client.request('http://api-v2launch.trakt.tv/users/me', headers=headers)
        result = json.loads(result)

        user = result['username']

        control.setSetting(id='trakt.user', value=user)
        control.setSetting(id='trakt.token', value=token)
        control.setSetting(id='trakt.refresh', value=refresh)
        raise Exception()
    except:
        control.openSettings('3.1')
コード例 #50
0
def authTrakt():
    try:

        check = checkCredentials()
        if check == 'true':
            yes = control.yesnoDialog(
                control.lang(32511).encode('utf-8'),
                control.lang(32512).encode('utf-8'), '', 'Trakt')
            if yes:
                control.setSetting(id='trakt.user', value='')
                control.setSetting(id='trakt.token', value='')
                control.setSetting(id='trakt.refresh', value='')
                control.infoDialog('Trakt Account Reset: DONE',
                                   sound=True,
                                   icon='INFO')
            raise Exception()

        result = getTraktAsJson('/oauth/device/code', {'client_id': CLIENT_ID})
        verification_url = (control.lang(32513) %
                            result['verification_url']).encode('utf-8')
        user_code = (control.lang(32514) % result['user_code']).encode('utf-8')
        expires_in = int(result['expires_in'])
        device_code = result['device_code']
        interval = result['interval']

        # print ("TRAKT DEVICE CODE", device_code)
        # print ("TRAKT interval CODE", interval)
        # print ("TRAKT expires_in CODE", expires_in)
        progressDialog = control.progressDialog
        progressDialog.create('Trakt', verification_url, user_code)

        for i in range(0, expires_in):
            try:
                if progressDialog.iscanceled(): break
                time.sleep(1)
                if not float(i) % interval == 0: raise Exception()
                r = getTraktAsJson(
                    '/oauth/device/token', {
                        'client_id': CLIENT_ID,
                        'client_secret': CLIENT_SECRET,
                        'code': device_code
                    })
                if 'access_token' in r: break
            except:
                pass

        try:
            progressDialog.close()
        except:
            pass

        token, refresh = r['access_token'], r['refresh_token']

        headers = {
            'Content-Type': 'application/json',
            'trakt-api-key': CLIENT_ID,
            'trakt-api-version': '2',
            'Authorization': 'Bearer %s' % token
        }

        result = requests.get(urlparse.urljoin(BASE_URL, '/users/me'),
                              headers=headers).content
        result = utils.json_loads_as_str(result)

        user = result['username']
        control.infoDialog('Trakt Account Verified', sound=True, icon='INFO')
        control.setSetting(id='trakt.user', value=user)
        control.setSetting(id='trakt.token', value=token)
        control.setSetting(id='trakt.refresh', value=refresh)
        control.setSetting(id='indicators.alt', value='1')
        control.setSetting(id='trakt.scrobblePlayback', value='true')
        raise Exception()
    except:
        control.openSettings('3.1')