def fillServerApiData(self): printDBG('EuroSportPlayer.fillServerApiData') if self.serverApiData != {}: return serverApiData = {} sts, data = self.getPage(self.getMainUrl()) if not sts: return False jscode = ['var window={};function getStartupDeviceTypeString(){return "desktop";}\nwindow.requirejs_data={};requirejs=function(){if (2 == arguments.length) {window.requirejs_data.siteScripts=arguments[0];arguments[1]()} else {window.requirejs_data.scripts=arguments[0];}};requirejs.config=function(){window.requirejs_data.config=arguments[0];};'] markers = ['window.server_path','window.i18n_dictionary','window.locale','window.SPORTS_BY_ID','window.bamTrackingConfig','window.specialEvents','requirejs'] data = self.cm.ph.getAllItemsBeetwenNodes(data, ('<script', '>'), ('</script', '>'), False) for item in data: for m in markers: if m in item: jscode.append(item) break jscode.append('\nprint(JSON.stringify(window));') ret = iptv_js_execute( '\n'.join(jscode) ) if ret['sts'] and 0 == ret['code']: data = ret['data'].strip() try: serverApiData = byteify(json.loads(data)) clientId = serverApiData['server_path']['sdk']['clientId'] env = serverApiData['server_path']['sdk']['environment'] url = 'https://bam-sdk-configs.mlbam.net/v0.1/%s/browser/v2.1/windows/chrome/%s.json' % (clientId, env) sts, data = self.getPage(url) if not sts: return False serverApiData['prod'] = byteify(json.loads(data)) except Exception: printExc() return self.serverApiData = serverApiData
def getLinksForVideo(self, cItem): printDBG("BBCSport.getLinksForVideo [%s]" % cItem) self.tryTologin() urlTab = [] if '/vpid/' in cItem['url']: urlTab.append({ 'name': cItem['title'], 'url': cItem['url'], 'need_resolve': 1 }) else: sts, data = self.getPage(cItem['url']) if not sts: return urlTab mediaData = self.cm.ph.getDataBeetwenMarkers( data, '.setPayload(', '</script>', False)[1] mediaData = self.cm.ph.getDataBeetwenMarkers( mediaData, '"body":{', '});', False)[1].strip()[:-1] if mediaData != '': try: mediaData = byteify(json.loads('{%s}' % mediaData), '', True) if mediaData[ 'media'] and mediaData['media']['mediaType'].lower( ) == 'video' and '' != mediaData['media']['pid']: url = self.getFullUrl('/iplayer/vpid/%s/' % mediaData['media']['pid']) urlTab.append({ 'name': mediaData['media']['entityType'], 'url': url, 'need_resolve': 1 }) except Exception: printExc() mediaData = self.cm.ph.getDataBeetwenMarkers( data, '"allAvailableVersions"', '"holdingImage"', False)[1].strip()[1:-1].strip() if mediaData != '': try: uniqueTab = [] mediaData = byteify(json.loads(mediaData), '', True) for tmp in mediaData: title = self.cleanHtmlStr(tmp['smpConfig']['title']) for item in tmp['smpConfig']['items']: url = self.getFullUrl('/iplayer/vpid/%s/' % item['vpid']) if url in uniqueTab: continue uniqueTab.append(url) name = item['kind'].title() urlTab.append({ 'name': '[%s] %s' % (name, title), 'url': url, 'need_resolve': 1 }) except Exception: printExc() return urlTab
def getVideoLinks(self, videoUrl): printDBG("HDStreams.getVideoLinks [%s]" % videoUrl) meta = strwithmeta(videoUrl).meta linksKey = meta.get('links_key', '') post_data = meta.get('post_data', {}) for idx in range(len(self.cacheLinks[linksKey])): if self.cacheLinks[linksKey][idx]['url'].meta[ 'links_key'] == linksKey: tmp_post = self.cacheLinks[linksKey][idx]['url'].meta.get( 'post_data', {}) if tmp_post == post_data: if not self.cacheLinks[linksKey][idx]['name'].startswith( '*'): self.cacheLinks[linksKey][idx][ 'name'] = '*' + self.cacheLinks[linksKey][idx][ 'name'] break sts, data = self.getPage(videoUrl) if not sts: return [] urlParams = dict(self.defaultParams) urlParams['header'] = dict(self.AJAX_HEADER) urlParams['header']['Referer'] = videoUrl urlParams['header']['x-csrf-token'] = self.cm.ph.getSearchGroups( data, '''<[^>]+?csrf-token[^>]+?content=['"]([^'^"]+?)['"]''')[0] urlParams['header']['x-xsrf-token'] = self.cm.getCookieItem( self.COOKIE_FILE, 'XSRF-TOKEN') urlParams['header']['x-requested-with'] = 'XMLHttpRequest' urlParams['ignore_http_code_ranges'] = [(401, 401)] sts, data = self.getPage(videoUrl + '/stream', urlParams, post_data) if not sts: return [] if 'captcha' in data.lower(): SetIPTVPlayerLastHostError( _('Link protected with google recaptcha v2.')) try: printDBG(data) tmp = byteify(json.loads(data))['s'] if '{' not in tmp: tmp = base64.b64decode(tmp) tmp = byteify(json.loads(tmp)) printDBG(tmp) ciphertext = base64.b64decode(tmp['ct'][::-1]) iv = unhexlify(tmp['iv']) salt = unhexlify(tmp['s']) b = urlParams['header'][ 'x-csrf-token'] #urlParams['header']['User-Agent'] tmp = self.cryptoJS_AES_decrypt(ciphertext, base64.b64encode(b), salt) printDBG(tmp) tmp = byteify(json.loads(tmp)) videoUrl = tmp except Exception: printExc() return self.up.getVideoLinkExt(videoUrl)
def getList(self, cItem): printDBG("LivetvhdNetApi.getChannelsList") channelsTab = [] try: initList = cItem.get('init_list', True) if initList: rm(self.COOKIE_FILE) params = dict(cItem) params.update({ 'init_list': False, 'url': 'https://livetvhd.net/api/videos', 'title': _('--All--') }) channelsTab.append(params) sts, data = self.cm.getPage( 'https://livetvhd.net/api/categories') if not sts: return [] data = byteify(json.loads(data)) for item in data: params = dict(cItem) params.update({ 'init_list': False, 'url': 'https://livetvhd.net/api/videos/category/' + item['seo_name'], 'title': self.cleanHtmlStr(item['name']) }) channelsTab.append(params) else: sts, data = self.cm.getPage(cItem['url']) if not sts: return [] data = byteify(json.loads(data)) if 'videos' in data: data = data['videos'] for item in data: url = item['url'] icon = item['thumbnail'] title = self.cleanHtmlStr(item['title']) desc = _('Views: ') + str(item.get('views', '')) params = dict(cItem) params.update({ 'type': 'video', 'title': title, 'url': url, 'desc': desc, 'icon': self.getFullIconUrl(icon) }) channelsTab.append(params) except Exception: printExc() return channelsTab
def listSeasons(self, cItem, nextCategory): printDBG("GamatoMovies.listSeasons") sts, data = self.cm.getPage(cItem['url']) if not sts: return data = self.cm.ph.getDataBeetwenMarkers(data, 'vars.title =', '};', False)[1].strip() + '}' try: trailerUrl = self.cm.ph.getSearchGroups( data, '''"trailer"\s*:\s*(['"]http[^'^"]+?['"])''')[0] trailerUrl = byteify(json.loads(trailerUrl)) if self.cm.isValidUrl(trailerUrl): params = dict(cItem) params.update({ 'good_for_fav': True, 'title': cItem['title'] + ' - ' + _('trailer'), 'priv_type': 'trailer', 'url': trailerUrl }) self.addVideo(params) except Exception: printExc() try: data = byteify(json.loads(data)) for item in data['season']: title = self.getStr(item, 'title') if '' == title: title = _('Season {0}'.format(item['number'])) url = self.getFullUrl(cItem['url'] + '/seasons/' + str(item['number'])) overview = self.getStr(item, 'overview') if overview == '': desc = cItem['desc'] else: desc = '{0}[/br]{1}'.format( self.getStr(item, 'release_date'), overview) params = { 'good_for_fav': True, 'category': nextCategory, 'priv_type': cItem['priv_type'], 'title': title, 'url': url, 'priv_stitle': cItem['title'], 'priv_snum': self.getStr(item, 'number'), 'priv_id': self.getStr(item, 'id'), 'icon': self.getStr(item, 'poster'), 'desc': desc } self.addDir(params) except Exception: printExc()
def Lastfmlist_track(self, artist): playlist_id = "lastfm://playlist/" + artist url = 'http://ws.audioscrobbler.com/2.0/?method=playlist.fetch&playlistURL=' + playlist_id + '&api_key=' + audioscrobbler_api_key + '&format=json' print url sts, data = self.cm.getPage(url, {'header': HEADER}) if not sts: return try: data = byteify(json.loads(data))['playlist']['trackList']['track'] print data for x in range(len(data)): item = data[x] artist = item['creator'] track_name = item['title'] try: iconimage = item['image'] except Exception: iconimage = '' search_string = urllib.quote(artist + ' ' + track_name + ' music video') params = { 'title': track_name + ' - ' + artist, 'page': search_string, 'icon': iconimage, 'plot': '' } self.addVideo(params) except Exception: printExc() # wypisz co poszło nie tak
def getLinksForVideo(self, cItem): printDBG("BBCiPlayer.getLinksForVideo [%s]" % cItem) retTab = [] sts, data = self.cm.getPage(cItem['url'], self.defaultParams) if not sts: return retTab tmp = self.cm.ph.getSearchGroups( data, r'mediator\.bind\(({.+?})\s*,\s*document\.getElementById')[0] if tmp == '': tmp = self.cm.ph.getDataBeetwenReMarkers( data, re.compile('window\.mediatorDefer\s*=\s*[^,]*?\,'), re.compile('\);'), False)[1] try: uniqueTab = [] data = byteify(json.loads(tmp)) for item in data['episode']['versions']: url = self.getFullUrl('/iplayer/vpid/%s/' % item['id']) if url in uniqueTab: continue uniqueTab.append(url) name = item['kind'].title() retTab.append({'name': name, 'url': url, 'need_resolve': 1}) except Exception: printExc() if len(retTab): return retTab else: retTab.append({'name': '', 'url': cItem['url'], 'need_resolve': 1}) return retTab
def listArtistVideos(self, cItem): printDBG("VevoCom.listArtistVideos [%s]" % cItem) artistId = cItem['url'].split('/')[-1].split('?', 1)[0] if artistId == '': return page = cItem.get('page', 0) post_data = '{"query":"query ArtistVideos($ids: [String]!, $page: Int, $apiCall: String) {\\n artists(ids: $ids) {\\n id\\n videoData(size: 30, page: $page, sort: \\"MostRecent\\", apiCall: $apiCall) {\\n videos {\\n data {\\n id\\n basicMetaV3 {\\n artists {\\n basicMeta {\\n name\\n role\\n urlSafeName\\n thumbnailUrl\\n __typename\\n }\\n __typename\\n }\\n monetizable\\n isrc\\n title\\n urlSafeTitle\\n releaseDate\\n copyright\\n shortUrl\\n thumbnailUrl\\n duration\\n hasLyrics\\n explicit\\n allowEmbed\\n allowMobile\\n unlisted\\n live\\n certified\\n originalContent\\n releaseDate\\n categories\\n __typename\\n }\\n likes\\n liked\\n views {\\n viewsTotal\\n __typename\\n }\\n __typename\\n }\\n paging {\\n total\\n size\\n pages\\n next\\n page\\n __typename\\n }\\n __typename\\n }\\n __typename\\n }\\n __typename\\n }\\n}\\n","variables":{"ids":["%s"],"page":%s,"apiCall":"all"},"operationName":"ArtistVideos"}' post_data = post_data % (artistId, page + 1) params = self._getApiHeaders(cItem) sts, data = self.getPage(self.API_URL, params, post_data) if not sts: return try: data = byteify(json.loads(data), '')['data']['artists'][0] self._listJsonVideos(cItem, data['videoData']['videos']['data']) if data['videoData']['videos']['paging']['page'] < data[ 'videoData']['videos']['paging']['pages']: params = dict(cItem) params.pop('page', 0) params.update({ 'good_for_fav': False, 'title': _('Next page'), 'page': page + 1 }) self.addDir(params) except Exception: printExc()
def _unshorten_viidme(self, uri): try: sts, html = self.cm.getPage(uri, {'header': HTTP_HEADER}) session_id = re.findall(r'sessionId\:(.*?)\"\,', html) if len(session_id) > 0: session_id = re.sub(r'\s\"', '', session_id[0]) http_header = copy.copy(HTTP_HEADER) http_header[ "Content-Type"] = "application/x-www-form-urlencoded" http_header["Host"] = "viid.me" http_header["Referer"] = uri http_header["Origin"] = "http://viid.me" http_header["X-Requested-With"] = "XMLHttpRequest" GetIPTVSleep().Sleep(5) payload = {'adSessionId': session_id, 'callback': 'c'} sts, response = self.cm.getPage( 'http://viid.me/shortest-url/end-adsession', {'header': http_header}, payload) resp_uri = byteify(json.loads( response[6:-2]))['destinationUrl'] if resp_uri is not None: uri = resp_uri return uri, 'OK' except Exception as e: printExc() return uri, str(e)
def listSchedule(self, cItem): printDBG("EuroSportPlayer.listSchedule [%s]" % cItem) def _dateStr(d): return d.strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z' try: cItem = dict(cItem) sData = cItem.pop('f_sdate') eData = cItem.pop('f_edate') variables = {"startDate":_dateStr(sData - self.OFFSET),"endDate":_dateStr(eData - self.OFFSET),"uiLang":self.serverApiData['locale']['language'],"mediaRights":["GeoMediaRight"],"preferredLanguages":self.serverApiData['locale']['languageOrder']} url = self.serverApiData['server_path']['search'] + '/persisted/query/eurosport/web/Airings/DateRange?variables=' + urllib.quote(json.dumps(variables, separators=(',', ':'))) sts, data = self.getJSPage(url) if not sts: return data = byteify(json.loads(data)) data['data']['Airings'].sort(key=lambda item: item['startDate']) #, reverse=True) NOW = datetime.now() for item in data['data']['Airings']: if item.get('playbackUrls', []) in (None, []): continue self._addItem(cItem, item, NOW, sData+self.OFFSET-timedelta(days=1), eData+self.OFFSET+timedelta(days=1)) except Exception: printExc()
def getUrlImpl(self, url): urlsList = [] sts, data = self.cm.getPage(url) if sts: try: data = byteify(json.loads(data)) #printDBG(data) seekable = data['seekable'] for stream in data['streams']: name = stream.get('name', '') if name == '': name = stream['quality'] try: if int(stream['watch-timeout']) < 1000: name += ' ' + _('PAY') else: name += ' ' + _('FREE') except Exception: pass url = stream['url'] if url.startswith('rtmp'): flashplayer = 'http://www.filmon.com/tv/modules/FilmOnTV/files/flashapp/filmon/FilmonPlayer.swf?v=55' pageUrl = 'http://www.filmon.com/tv/channel/export?channel_id=' + str(channelID) url = url + '/' + stream['name'] + ' swfUrl=' + flashplayer + ' pageUrl=' + url url = urlparser.decorateUrl( url ) url.meta.update({'iptv_urlwithlimit' : False, 'iptv_livestream' : not seekable}) urlsList.append({'name':name, 'url':url}) except Exception: printExc() return urlsList
def addSubAtom(self, inAtom): try: inAtom = byteify(inAtom) textTab = inAtom['text'].split('\n') for text in textTab: text = self._srtClearText(text).strip() if text != '': idx = len(self.subAtoms) self.subAtoms.append({ 'start': inAtom['start'], 'end': inAtom['end'], 'text': text }) tmp = self.subAtoms[idx]['start'] / self.CAPACITY if tmp not in self.pailsOfAtoms: self.pailsOfAtoms[tmp] = [idx] elif idx not in self.pailsOfAtoms[tmp]: self.pailsOfAtoms[tmp].append(idx) tmp = self.subAtoms[idx]['end'] / self.CAPACITY if tmp not in self.pailsOfAtoms: self.pailsOfAtoms[tmp] = [idx] elif idx not in self.pailsOfAtoms[tmp]: self.pailsOfAtoms[tmp].append(idx) except Exception: pass
def listVodTypesFilters(self, cItem, nextCategory): printDBG("EuroSportPlayer.listVodTypesFilters [%s]" % cItem) try: sportId = cItem['f_sport_id'] variables = {"must":[{"attributeName":"category","values":["%s" % sportId]}],"uiLang":self.serverApiData['locale']['language'],"mediaRights":["GeoMediaRight"],"preferredLanguages":self.serverApiData['locale']['languageOrder']} url = self.serverApiData['server_path']['search'] + '/persisted/query/eurosport/web/ondemand/counts/bycategory?variables=' + urllib.quote(json.dumps(variables, separators=(',', ':'))) sts, data = self.getJSPage(url) if not sts: return totall = 0 data = byteify(json.loads(data)) for item in [('replays', 'Ondemand_Subnav_Replay'), ('highlights', 'Ondemand_Subnav_Highlights'), ('news', 'Ondemand_Subnav_News')]: try: vodType = item[0] count = int(data['data'][vodType]['meta']['hits']) if count <= 0: continue totall += count title = '%s (%s)' % (self.serverApiData['i18n_dictionary'][item[1]], count) params = dict(cItem) params.update({'good_for_fav':False, 'category':nextCategory, 'title':title, 'f_vod_type':vodType}) self.addDir(params) except Exception: printExc() if totall > 0 and len(self.currList) > 1: title = '%s (%s)' % (self.serverApiData['i18n_dictionary']['Ondemand_Subnav_All'], totall) params = dict(cItem) params.update({'good_for_fav':False, 'category':nextCategory, 'title':title}) self.currList.insert(0, params) except Exception: printExc()
def listAZItems(self, cItem, nextCategory): printDBG("C3player.listAZItems cItem[%s]" % (cItem)) sts, data = self.cm.getPage(cItem['url']) if not sts: return try: data = byteify(json.loads(data))['content'] data = self.cm.ph.getDataBeetwenNodes(data, ('<section', '>', 'az_list'), ('</section', '>'))[1] data = re.sub("<!--[\s\S]*?-->", "", data) data = self.cm.ph.getAllItemsBeetwenMarkers(data, '<li', '</li>') for item in data: url = self.getFullUrl( self.cm.ph.getSearchGroups( item, '''href=['"]([^'^"]+?)['"]''')[0]) item = item.split('</a>', 1) title = self.cleanHtmlStr(item[0]) desc = self.cleanHtmlStr(item[-1]) params = dict(cItem) params.update({ 'good_for_fav': True, 'title': title, 'category': nextCategory, 'url': url, 'desc': desc }) self.addDir(params) except Exception: printExc()
def listItems(self, cItem, nextCategory, data=None): try: if data == None: url = self.tmpUrl % cItem['url'] sts, data = self.getPage(url) if not sts: return data = byteify(json.loads(data), '', True) for item in data: if item == '': continue descTab = [] icon = item.get('image', '') house = item.get('top_house_number', '') title = self.cleanHtmlStr(item.get('title', '')) if icon == '': icon = item['brand_image'] if house == '': house = item['house_num'] if title == '': title = self.cleanHtmlStr(item['brand_name']) pg = [] if '' != item.get('guidance_age', ''): pg.append(item['guidance_age']) if '' != item.get('guidance_text', ''): pg.append(item['guidance_text']) if len(pg): descTab.append(' '.join(pg)) if '' != item.get('channel', ''): descTab.append(_('Channel: %s') % item['channel'].title()) if '' != item.get('video_count', ''): descTab.append(_('Videos count: %s') % item['video_count']) desc = '[/br]'.join(descTab) params = {'good_for_fav':True, 'category':nextCategory, 'title':title, 'icon':icon, 'desc':desc, 'f_house':house} self.addDir(params) except Exception: printExc()
def getVideosApiPlayList(self, url, category, page, cItem): printDBG('YouTubeParser.getVideosApiPlayList url[%s]' % url) playlistID = self.cm.ph.getSearchGroups(url + '&', 'list=([^&]+?)&')[0] baseUrl = 'https://www.youtube.com/list_ajax?style=json&action_get_list=1&list=%s' % playlistID currList = [] if baseUrl != '': sts, data = self.cm.getPage(baseUrl, {'host': self.HOST}) try: data = byteify(json.loads(data))['video'] for item in data: url = 'http://www.youtube.com/watch?v=' + item[ 'encrypted_id'] title = item['title'] img = item['thumbnail'] time = item['length_seconds'] if '' != time: time = str(timedelta(seconds=int(time))) if time.startswith("0:"): time = time[2:] desc = item['description'] params = { 'type': 'video', 'category': 'video', 'title': title, 'url': url, 'icon': img, 'time': time, 'desc': desc } currList.append(params) except Exception: printExc() return currList
def _loadGroups(self): printDBG("IPTVHostsGroups._loadGroups") self.LOADED_GROUPS = [] self.LOADED_DISABLED_GROUPS = [] self.LOADED_GROUPS_TITLES = {} groups = [] titles = {} disabledGroups = [] ret = True if os_path.isfile(self.GROUPS_FILE): try: data = self._loadFromFile(self.GROUPS_FILE) data = byteify(json.loads(data)) for item in data.get('disabled_groups', []): # we need only information about predefined groups which were disabled if item in self.PREDEFINED_GROUPS: disabledGroups.append(str(item)) for item in data.get('groups', []): name = str(item['name']) groups.append(name) if 'title' in item: titles[name] = str(item['title']) except Exception: printExc() self.LOADED_GROUPS = groups self.LOADED_DISABLED_GROUPS = disabledGroups self.LOADED_GROUPS_TITLES = titles
def _loadHosts(self, groupFile, groupName, hostListFromFolder, hostListFromList): printDBG("IPTVHostsGroups._loadHosts groupName[%s]" % groupName) predefinedHosts = self.PREDEFINED_HOSTS.get(groupName, []) hosts = [] disabledHosts = [] ret = True if os_path.isfile(groupFile): try: data = self._loadFromFile(groupFile) data = byteify(json.loads(data)) for item in data.get('disabled_hosts', []): # we need only information about predefined hosts which were disabled if item in predefinedHosts and item in hostListFromList: disabledHosts.append(str(item)) for item in data.get('hosts', []): if item in hostListFromFolder: hosts.append(item) except Exception: printExc() self.LOADED_HOSTS[groupName] = hosts self.LOADED_DISABLED_HOSTS[groupName] = disabledHosts
def getChannelsList(self, cItem): printDBG("WkylinewebcamsCom.getChannelsList") list = [] sts, data = self.cm.getPage('http://livespotting.tv/api/api.json') if not sts: return list try: data = byteify(json.loads(data)) for item in data['streams']: if 'stream' not in item: continue try: item = item['stream']['data'] title = item['content']['title'] icon = item['images'].get('snapshot-343x192', '') desc = self.cleanHtmlStr(item['content'].get( 'longtext', '')) camId = item['camID']['camid'] if camId.startswith('LS_'): camId = camId[3:] url = 'rtmp://stream.livespotting.tv/windit-edge/%s.stream live=1' % camId list.append({ 'title': title, 'url': url, 'icon': icon, 'desc': desc }) except Exception: printExc() except Exception: printExc() return list
def listLangVersions(self, cItem, nextCategory): printDBG("KinomanCO.listLangVersions") try: imdbID = cItem['imdb_id'] sts, data = self.getPage(self.getFullUrl('/request'), post_data={'mID':imdbID}) if not sts: return # type: 0 == cinema, 2 == series, 1 == movies data = byteify(json.loads(data))[0] for item in data['languages']: icon = cItem.get('icon', '') cover = self._getStr(data, 'cover') if '/' in cover and not cover.endswith('/'): icon = self.getFullIconUrl(cover) title = self.cleanHtmlStr('%s (%s)' % (data['name'], item['text'])) desc = [] desc.append(self._getStr(data, 'year')) desc.append('~%s %s' % (self._getStr(data, 'duration'), _('min'))) desc.append('%s/10' % (self._getStr(data, 'rating'))) desc.append(', '.join(data.get('genres', []))) desc.append(', '.join(data.get('actors', []))[:3]) desc.append(', '.join(data.get('directors', [])[:3])) desc = ' | '.join(desc) + '[/br]' + self.cleanHtmlStr(str(data['plot'])) params = dict(cItem) params.update({'good_for_fav':True, 'category':nextCategory, 'icon':icon, 'desc':desc, 'title':title, 'item_type_id':data['type'], 'f_lang':item['symbol'].lower(), 'lang':{'id':item['ID'], 'symbol':item['symbol']}}) self.addDir(params) except Exception: printExc()
def getToken(self, grantType): printDBG('EuroSportPlayer.getToken start') bRet = False try: getParams = dict(self.defaultParams) getParams['header'] = dict(self.AJAX_HEADER) clientData = self.serverApiData['prod']['authorization']['client'] url = clientData['links'][0]['href'] getParams['header'].update(clientData['links'][0]['headers']) getParams['header']['Authorization'] = getParams['header']['Authorization'].replace('{encodedApiToken}', self.serverApiData['server_path']['sdk']['clientApiKey']) post_data = None if grantType == 'init': import uuid post_data = {'grant_type':'client_credentials', 'latitude':0, 'longitude':0, 'platform':clientData['platformId'], 'token':str(uuid.uuid4())} elif grantType == 'refresh': post_data = {'grant_type':'refresh_token', 'latitude':0, 'longitude':0, 'platform':clientData['platformId'], 'token':self.tokenData['refresh_token']} elif grantType == 'code': post_data = {'grant_type':'urn:mlbam:params:oauth:grant_type:token', 'latitude':0, 'longitude':0, 'platform':clientData['platformId'], 'token':self.tokenData['access_code']} sts, data = self.getPage(url, getParams, post_data) printDBG("++++++++++++++++++++++++++++++++++++++++++++++++++++++++") printDBG(data) printDBG("++++++++++++++++++++++++++++++++++++++++++++++++++++++++") self.tokenData.update(byteify(json.loads(data))) self.tokenData['timeout'] = time.time() + self.tokenData['expires_in'] # expires_in - in seconds bRet = True except Exception: printExc() printDBG('EuroSportPlayer.getToken end bRet[%s]' % bRet) return bRet
def Itunes_track_charts(self, url): country = url sts, data = self.cm.getPage( 'https://itunes.apple.com/%s/rss/topsongs/limit=100/explicit=true/json' % country, {'header': HEADER}) if not sts: return try: data = byteify(json.loads(data))['feed']['entry'] for x in range(len(data)): item = data[x] artist = item['im:artist']['label'] track_name = item['im:name']['label'] try: iconimage = item['im:image'][2]['label'] except Exception: iconimage = '' plot = '' search_string = urllib.quote(artist + ' ' + track_name + ' music video') params = { 'title': str(x + 1) + '. ' + artist + '- ' + track_name, 'page': search_string, 'icon': iconimage, 'plot': plot } self.addVideo(params) except Exception: printExc() # wypisz co poszło nie tak
def listEventsCategories(self, cItem, nextCategory): printDBG("EuroSportPlayer.listEventsCategories [%s]" % cItem) def _str2dateShort(txt): date = self._str2date(txt) month = self.ABBREVIATED_MONTH_NAME_TAB[date.month-1] return ' %s %s, %s' % (date.day, self.serverApiData['i18n_dictionary'].get(month, month), date.year) try: if cItem['f_type'] == 'nonolympics': type = 'Non' else: type = '' variables = {"include_images":True,"uiLang":self.serverApiData['locale']['language'],"mediaRights":["GeoMediaRight"],"preferredLanguages":self.serverApiData['locale']['languageOrder']} url = self.serverApiData['server_path']['search'] + '/persisted/query/eurosport/%sOlympicsEventPageAll?variables=%s' % (type, urllib.quote(json.dumps(variables, separators=(',', ':')))) sts, data = self.getJSPage(url) if not sts: return data = byteify(json.loads(data)) data['data']['EventPageAll'].sort(key=lambda item: item['eventDetails'][0]['title']) for item in data['data']['EventPageAll']: title = self.cleanHtmlStr(item['eventDetails'][0]['title']) desc = '%s - %s' % (_str2dateShort(item['startDate']), _str2dateShort(item['endDate'])) icon = item['heroImage'][0]['photos'][0]['imageLocation'] params = dict(cItem) params.update({'good_for_fav':False, 'category':nextCategory, 'title':title, 'desc':desc, 'icon':icon, 'f_content_id':item['contentId']}) self.addDir(params) except Exception: printExc()
def listSort(self, cItem, nextCategory): printDBG("VimeoCom.listSort [%s]" % cItem) sts, data = self.getPage(cItem['url']) if not sts: return self._fillApiData(data) data = self.cm.ph.getSearchGroups( data, '''"%s"\:\{"identifier"[^;]+?"sorts"\:\{([^;]+?\})\},''' % cItem.get('f_type', ''))[0] data = self.cm.ph.getAllItemsBeetwenMarkers(data, '{', '}') try: data = byteify(json.loads('[%s]' % ','.join(data))) for item in data: title = self.cleanHtmlStr(item['label']) params = dict(cItem) params.update({ 'good_for_fav': False, 'category': nextCategory, 'title': title, 'f_sort': item['identifier'] }) self.addDir(params) except Exception: printExc()
def getLinksForVideo(self, cItem): printDBG("EuroSportPlayer.getLinksForVideo [%s]" % cItem) self.fillServerApiData() self.tryTologin() linksTab = [] try: privItem = cItem['priv_item'] if 'playbackUrls' in privItem: playbackUrls = privItem['playbackUrls'] else: playbackUrls = privItem['media'][0]['playbackUrls'] for urlItem in playbackUrls: url = urlItem['href'].replace('{scenario}', 'browser~unlimited') sts, data = self.getJSPage(url) data = byteify(json.loads(data))['stream'] printDBG("+++++++++++++++++++++++++++++++++++++++++++++++++") printDBG(data) for item in [('slide', 'slide'), ('complete', 'complete')]: if item[0] not in data: continue linksTab.append({'url':data[item[0]], 'name':'%s - %s' % (urlItem['rel'], item[1]), 'need_resolve':1}) except Exception: printExc() return linksTab
def Itunes_list_album_tracks(self, url, album, country): sts, data = self.cm.getPage( 'https://itunes.apple.com/lookup?id=' + url + '&country=' + country + '&entity=song&limit=200', {'header': HEADER}) if not sts: return try: data = byteify(json.loads(data))['results'] for x in range(1, len(data)): item = data[x] artist = item['artistName'] track_name = item['trackName'] try: iconimage = item['artworkUrl100'] except Exception: iconimage = '' plot = '' search_string = urllib.quote(artist + ' ' + track_name + ' music video') params = { 'title': artist + '- ' + track_name, 'page': search_string, 'icon': iconimage, 'plot': plot } self.addVideo(params) except Exception: printExc()
def listPlaylistItems(self, cItem): printDBG("VevoCom.listPlaylistItems [%s]" % cItem) playlistId = cItem['url'].split('/')[-1].split('?', 1)[0] if playlistId == '': return page = cItem.get('page', 0) if page == 0: mode = 'Playlist' else: mode = 'MorePlaylistVideos' post_data = '{"query":"query %s($ids: [String]!, $offset: Int, $limit: Int) {\\n playlists(ids: $ids) {\\n id\\n playlistId\\n basicMeta {\\n title\\n description\\n curated\\n admin_id\\n user_id\\n user {\\n id\\n basicMeta {\\n username\\n vevo_user_id\\n __typename\\n }\\n __typename\\n }\\n public\\n image_url\\n videoCount\\n errorCode\\n __typename\\n }\\n likes\\n liked\\n videos(limit: $limit, offset: $offset) {\\n items {\\n id\\n index\\n isrc\\n videoData {\\n id\\n likes\\n liked\\n basicMetaV3 {\\n youTubeId\\n monetizable\\n isrc\\n title\\n urlSafeTitle\\n startDate\\n endDate\\n releaseDate\\n copyright\\n copyrightYear\\n genres\\n contentProviders\\n shortUrl\\n thumbnailUrl\\n duration\\n hasLyrics\\n explicit\\n allowEmbed\\n allowMobile\\n categories\\n credits {\\n role\\n name\\n __typename\\n }\\n artists {\\n id\\n basicMeta {\\n urlSafeName\\n role\\n name\\n thumbnailUrl\\n __typename\\n }\\n __typename\\n }\\n errorCode\\n __typename\\n }\\n __typename\\n }\\n __typename\\n }\\n offset\\n limit\\n __typename\\n }\\n __typename\\n }\\n}\\n","variables":{"ids":["%s"],"limit":%s,"offset":%s},"operationName":"%s"}' post_data = post_data % (mode, playlistId, 20, page * 20, mode) params = self._getApiHeaders(cItem) sts, data = self.getPage(self.API_URL, params, post_data) if not sts: return try: data = byteify(json.loads(data), '')['data']['playlists'][0] self._listJsonVideos(cItem, data['videos']['items']) if data['basicMeta']['videoCount'] > (page + 1) * 20: params = dict(cItem) params.pop('page', 0) params.update({ 'good_for_fav': False, 'title': _('Next page'), 'page': page + 1 }) self.addDir(params) except Exception: printExc()
def Lastfmlist(self): if False == self.usePremiumAccount: self.sessionEx.waitForFinishOpen(MessageBox, 'Wpisz login do last.fm.', type=MessageBox.TYPE_INFO, timeout=10) else: url = 'http://ws.audioscrobbler.com/2.0/?method=user.getPlaylists&user='******'&api_key=' + audioscrobbler_api_key + '&format=json' sts, data = self.cm.getPage(url, {'header': HEADER}) if not sts: return try: data = byteify(json.loads(data))['playlists']['playlist'] for x in range(len(data)): item = data[x] playlist_name = item['title'] playlist_id = item['id'] params = { 'name': 'Lastfmlist_track', 'title': playlist_name, 'artist': playlist_id } self.addDir(params) except Exception: printExc() # wypisz co poszło nie tak
def Itunes_album_charts(self, url): country = url sts, data = self.cm.getPage( 'https://itunes.apple.com/%s/rss/topalbums/limit=100/explicit=true/json' % country, {'header': HEADER}) if not sts: return try: data = byteify(json.loads(data))['feed']['entry'] for x in range(len(data)): item = data[x] artist = item['im:artist']['label'] album_name = item['im:name']['label'] idx = item['id']['attributes']['im:id'] try: iconimage = item['im:image'][2]['label'] except Exception: iconimage = '' plot = '' params = { 'name': 'Itunes_list_album_tracks', 'title': str(x + 1) + '. ' + artist + '- ' + album_name, 'page': idx, 'album': album_name, 'country': country, 'icon': iconimage, 'plot': plot } self.addDir(params) except Exception: printExc() # wypisz co poszło nie tak
def exploreItem(self, cItem, nextCategory): printDBG("KinomanCO.exploreItem") try: type = cItem.get('f_type', '') printDBG('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> type[%s]' % type) url = self.getFullUrl('/api/media?slug=%s&cache=3600' % cItem['url'], 'api_cache') sts, data = self.getPage(url) if not sts: return data = byteify(json.loads(data), '', True) if "youtube" == data.get("trailer", {}).get("host", ""): url = 'https://www.youtube.com/watch?v=' + data['trailer']['host_code'] title = self.cleanHtmlStr(data['trailer']['name']) if type == 'episode': title = '%s (%s)' % (self.cleanHtmlStr(data['series']['name']), title) params = dict(cItem) params.pop('f_type') params.update({'good_for_fav':False, 'title':title, 'url':url, 'desc':_('Trailer')}) self.addVideo(params) if type in ['movie']: params = dict(cItem) if data['is_vip'] == 'True': params.update({'with_vip_link':True}) self.addVideo(params) elif type == 'series': for item in data['series']['seasons']: params = dict(cItem) title = '%s %s (%s)' % (_('Season'), item['season'], self.cleanHtmlStr(item['episode_cnt'])) params.update({'good_for_fav':False, 'category':nextCategory, 'title':title, 's_num':item['season']}) self.addDir(params) except Exception: printExc()