Exemple #1
0
    def getVideoLink(self, baseUrl):
        printDBG("NettvPw.getVideoLink url[%s]" % baseUrl)
        urlsTab = []
        sts,data = self.cm.getPage(baseUrl)
        if not sts: return urlsTab
        
        data = self.cm.ph.getDataBeetwenMarkers(data, 'Oglądasz', '<div class="title-medium">', False)[1]
        tmp = self.cm.ph.getDataBeetwenMarkers(data, 'value="src=', '"', False)[1]
        if 'plugin_hls=http' in tmp:
            urlsTab = getDirectM3U8Playlist(tmp.split('&amp;')[0], checkExt=False)
        
        if '.setup(' in tmp:
            tmp = self.cm.ph.getSearchGroups(data, "file[^']*?:[^']*?'([^']+?'")[0]
            if '.m3u8' in tmp:
                urlsTab.extend(getDirectM3U8Playlist(tmp, checkExt=False))
                
        if 'type=rtmp' in data:
            video = self.cm.ph.getDataBeetwenMarkers(data, 'video=', '&#038;', False)[1]
            streamer = self.cm.ph.getDataBeetwenMarkers(data, 'streamer=', '&#038;', False)[1]
            urlsTab.append({'name':'rtmp', 'url':streamer + video})
        
        if 0 == len(urlsTab):
            tmp = self.up.getAutoDetectedStreamLink(baseUrl, data)
            urlsTab.extend(tmp)
            
        if 0 == len(urlsTab):
            tmp = self.cm.ph.getSearchGroups(data, 'SRC="([^"]+?)"', 1, True)[0]
            tmp = self.up.getAutoDetectedStreamLink(tmp)
            urlsTab.extend(tmp)
            
        if 0 == len(urlsTab):
            if 'Microsoft Silverlight' in data or 'x-silverlight' in data:
                SetIPTVPlayerLastHostError('Silverlight stream not supported.')

        return urlsTab
 def getResolvedURL(self, url):
     printDBG("LocalMedia.getResolvedURL [%s]" % url)
     videoUrls = []
     
     if url.startswith('/') and fileExists(url):
         url = 'file://'+url
     
     uri, params   = DMHelper.getDownloaderParamFromUrl(url)
     printDBG(params)
     uri = urlparser.decorateUrl(uri, params)
     
     if uri.meta.get('iptv_proto', '') in ['http', 'https']:
         urlSupport = self.up.checkHostSupport( uri )
     else:
         urlSupport = 0
     if 1 == urlSupport:
         retTab = self.up.getVideoLinkExt( uri )
         videoUrls.extend(retTab)
     elif 0 == urlSupport and self._uriIsValid(uri):
         if uri.split('?')[0].endswith('.m3u8'):
             retTab = getDirectM3U8Playlist(uri)
             videoUrls.extend(retTab)
         elif uri.split('?')[0].endswith('.f4m'):
             retTab = getF4MLinksWithMeta(uri)
             videoUrls.extend(retTab)
         else:
             videoUrls.append({'name':'direct link', 'url':uri})
     return videoUrls
Exemple #3
0
 def _extract_m3u8_formats(self, m3u8_url, video_id, entry_protocol='m3u8_native', ext='mp4', preference=0):
     formats = []
     tmpTab = getDirectM3U8Playlist(m3u8_url, False)
     for tmp in tmpTab:
         tmp['format_id'] = tmp['name']
         formats.append(tmp)
     return formats
 def _getVideoLink(data, FORMATS):
     videoTab = []
     for item in data['formats']:
         if item['mimeType'] in FORMATS.keys():
             formatType = FORMATS[item['mimeType']].encode('utf-8')
             format = self.REAL_FORMATS.get(formatType, '')
             name = self.getFormatFromBitrate( str(item['totalBitrate']) ) + '\t ' + formatType
             url = item['url'].encode('utf-8')
             if 'm3u8' == formatType:
                 videoTab.extend( getDirectM3U8Playlist(url) )
             else:
                 meta = {'iptv_format':format}
                 if config.plugins.iptvplayer.tvpVodProxyEnable.value:
                     meta['http_proxy'] = config.plugins.iptvplayer.proxyurl.value
                 videoTab.append( {'name' : name, 'bitrate': str(item['totalBitrate']), 'url' : self.up.decorateUrl(url, meta) })
     if 1 < len(videoTab):
         max_bitrate = int(config.plugins.iptvplayer.tvpVodDefaultformat.value)
         def __getLinkQuality( itemLink ):
             return int(itemLink['bitrate'])
         oneLink = CSelOneLink(videoTab, __getLinkQuality, max_bitrate)
         if config.plugins.iptvplayer.tvpVodUseDF.value:
             videoTab = oneLink.getOneLink()
         else:
             videoTab = oneLink.getSortedLinks()
     return videoTab
    def getLinksForVideo(self, cItem):
        printDBG("Laola1TV.getLinksForVideo [%s]" % cItem)
        urlTab = []
        
        sts, data = self.getPage(cItem['url'])
        if not sts: return urlTab
        error = self.cleanHtmlStr( self.cm.ph.getDataBeetwenMarkers(data, '<div class="notready">', '<div', False)[1] )
        if '' != error: SetIPTVPlayerLastHostError(error)
        
        data = self.cm.ph.getSearchGroups(data, 'class="main_tv_player"[^>]+?src="([^"]+?)"')[0]
        vidUrl = self._getFullUrl( data )
        
        sts, data = self.getPage(vidUrl)
        if not sts: return urlTab
        
        label        = self.cm.ph.getSearchGroups(data, 'var label = "([^"]+?)";')[0]
        vidUrl       = self.cm.ph.getSearchGroups(data, 'url: "([^"]+?)" \+ label \+ "([^"]+?)"', 2)
        vidUrl       = self._getFullUrl( vidUrl[0] + label + vidUrl[1] )
        playeSource  = self.cm.ph.getSearchGroups(data, "playeSource =[^;]*?'([^']+?)'[^;]*?;")[0]
        
        for myip in ['', config.plugins.iptvplayer.laola1tv_myip1.value, config.plugins.iptvplayer.laola1tv_myip2.value]:
            if '' != myip: header = {'X-Forwarded-For':myip}
            else: header = {}

            sts, data = self.getPage(vidUrl, {'header':header})
            if not sts: return urlTab
            data = self.cm.ph.getDataBeetwenMarkers(data, '<data>', '</data>', False)[1]
            printDBG(data)
            comment = self.cm.ph.getSearchGroups(data, 'comment="([^"]+?)"')[0]
            auth = self.cm.ph.getSearchGroups(data, 'auth="([^"]+?)"')[0]
            if auth == 'restricted': continue
            url  = self.cm.ph.getSearchGroups(data, 'url="([^"]+?)"')[0]
            url = url + playeSource + auth
            
            tmp = getDirectM3U8Playlist(url, checkExt=False)
            for item in tmp:
                item['need_resolve'] = 0
                urlTab.append(item)
            break
            
        if 0 < len(urlTab):
            max_bitrate = int(config.plugins.iptvplayer.laola1tv_defquality.value)
            def __getLinkQuality( itemLink ):
                try:
                    value = itemLink['bitrate']
                    return int(value)
                except:
                    printExc()
                    return 0
            urlTab = CSelOneLink(urlTab, __getLinkQuality, max_bitrate).getSortedLinks()
            if config.plugins.iptvplayer.laola1tv_onelink.value:
                urlTab = [urlTab[0]] 
        else:
            SetIPTVPlayerLastHostError(comment)
                
        return urlTab
 def getVideoLinks(self, baseUrl):
     printDBG("Movie4kTO.getVideoLinks [%s]" % baseUrl)
     urlTab = []
     iptvProto = baseUrl.meta['iptv_proto']
     if iptvProto == 'm3u8':
         urlTab = getDirectM3U8Playlist(baseUrl)
     elif iptvProto == 'f4m':
         urlTab = getF4MLinksWithMeta(baseUrl)
     else:
         urlTab = [{'name':'direct', 'url':baseUrl}]
     return urlTab
 def getLinksForVideo(self, cItem):
     printDBG("SportDeutschland.getLinksForVideo [%s]" % cItem)
     HTTP_HEADER= { 'User-Agent':'Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:21.0) Gecko/20100101 Firefox/21.0',
                    'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' }
     videoUrls =[]
     videoUrl = ''
     if '' != cItem['video']:
         videoUrl = cItem['video']
     else:        
         if '' != cItem['url']:
             sts,data = self.cm.getPage(cItem['url'])
             if sts:
                 try:
                     data = json.loads(data)
                     #printDBG("[%s]" % data)
                     videoUrl = self._getJItemStr(data['asset'], 'video')
                     if '' == videoUrl:
                         assets_info = self._getJItemStr(data['asset'], 'url')
                         if len(assets_info):
                             sts,assets_info = self.cm.getPage(assets_info, {'header' : HTTP_HEADER})
                             if sts:
                                 try:
                                     assets_info = json.loads(assets_info)
                                     videoUrl = self._getJItemStr(assets_info, 'video')
                                     printDBG('SportDeutschland.getLinksForVideo "video" from "assets_info" |%s|' % videoUrl)
                                 except: printExc()
                     if '' == videoUrl:  
                         player = self._getJItemStr(data['asset'], 'player')
                         if '' != player:
                             sts,data = self.cm.getPage(player, {'header' : HTTP_HEADER})
                             if sts: videoUrl = self.cm.ph.getSearchGroups(data, '<a class="asset"[^>]+?href="([^"]+?)"')[0]
                 except:
                     printExc()
     
     if '.smil?' in videoUrl:
         if 'rtmp' == config.plugins.iptvplayer.sportdeutschland_streamprotocol.value:
             sts,data = self.cm.getPage(videoUrl)
             if sts:
                 #printDBG("+++++++++++++++++++++++++++++++++\n%s\n+++++++++++++++++++++++++++++++++" % data)
                 videoUrl = self.cm.ph.getSearchGroups(data, 'meta base="(rtmp[^"]+?)"')[0]
                 if '' != videoUrl and not videoUrl.startswith('/'):
                     videoUrl += '/'
                 videoUrl += self.cm.ph.getSearchGroups(data, 'video src="([^"]+?)"')[0]
                 if videoUrl.startswith('rtmp'):
                     videoUrls.append({'name':'SportDeutschland rtmp', 'url':videoUrl.replace('&amp;', '&')})
         else:
             videoUrl = videoUrl.replace('.smil?', '.m3u8?')
             videoUrls = getDirectM3U8Playlist(videoUrl, checkExt=False)
     elif videoUrl.split('?')[0].endswith('mp4'):
         videoUrl = self.up.decorateUrl(videoUrl, {"iptv_buffering":"forbidden"})
         videoUrls.append({'name':'SportDeutschland mp4', 'url':videoUrl})
     return videoUrls
 def getVideostarLink(self, channelID):
     urlsTab = self.videoStarApi.getVideoLink(channelID)
     if 0 < len(urlsTab):
         if 'hls' == urlsTab[0]['type']:
             tmpList = getDirectM3U8Playlist(urlsTab[0]['url'], checkExt=False)
         else:
             tmpList = urlsTab
             
         for item in tmpList:
             if self.videoStarApi.getDefaultQuality() == item['bitrate']:
                 return [dict(item)]
         return [dict(tmpList[0])]
     return urlsTab
    def getLinksForVideo(self, cItem):
        printDBG("EskaGo.getLinksForVideo [%s]" % cItem)
        urlTab = []
        for urlItem in cItem.get("urls", []):
            url = urlItem["url"]
            if url.split("?")[0].endswith("m3u8"):
                data = getDirectM3U8Playlist(url, checkExt=False)
                for item in data:
                    item["url"] = urlparser.decorateUrl(item["url"], {"iptv_proto": "m3u8", "iptv_livestream": True})
                    urlTab.append(item)
            else:
                urlTab.append(urlItem)

        return urlTab
 def getResolvedURL(self, url):
     printDBG("WrestlingNet.getResolvedURL [%s]" % url)
     urlTab = []
     sts, data = self.cm.getPage(url)
     if not sts: return urlTab
     
     videoUrl = self.cm.ph.getSearchGroups(data, '<iframe[^>]+?src="([^"]+?)"')[0]
     if not videoUrl:
         videoUrl = self.cm.ph.getSearchGroups(data, "file: '([^']+?)'")[0]
         if '.m3u8' in videoUrl:
             urlTab = getDirectM3U8Playlist(videoUrl, checkExt=True)
         
     urlTab = self.up.getVideoLinkExt( videoUrl )
     return urlTab
 def getDirectLinks(self, url):
     printDBG('MoonwalkParser.getDirectLinks')
     linksTab = []
     try:
         self._setBaseUrl(url)
         params = copy.deepcopy(self.defaultParams)
         params['header']['Referer'] = url
         sts, data = self.cm.getPage( url, params)
         if not sts: return []
         
         sec_header, post_data = self._getSecurityData(data)
         params['header'].update(sec_header)
         
         sts, data = self.cm.getPage( '%s/sessions/create_session' % self.baseUrl, params, post_data)
         if not sts: return []
         
         data = byteify( json.loads(data) )
         if 'm3u8' == config.plugins.iptvplayer.moonwalk_format.value:
             tmpTab = getDirectM3U8Playlist(data["manifest_m3u8"])
             def __getLinkQuality( itemLink ):
                 return itemLink['heigth']
             if config.plugins.iptvplayer.moonwalk_use_df.value:
                 maxRes = config.plugins.iptvplayer.moonwalk_df_format.value
                 tmpTab = CSelOneLink(tmpTab, __getLinkQuality, maxRes).getSortedLinks()
                 tmpTab = [tmpTab[0]]
             for item in tmpTab:
                 linksTab.append({'name':'[hls/m3u8] %sp' % __getLinkQuality(item), 'url':item['url']})
         else:
             tmpTab = getF4MLinksWithMeta(data["manifest_f4m"])
             def __getLinkQuality( itemLink ):
                 printDBG(itemLink)
                 bitrate = int(self.cm.ph.getDataBeetwenMarkers(itemLink['name'], 'bitrate[', ']', False)[1])
                 if bitrate < 400:
                     return 360
                 elif bitrate < 700:
                     return 480
                 elif bitrate < 1200:
                     return 720
                 return 1080
             if config.plugins.iptvplayer.moonwalk_use_df.value:
                 maxRes = config.plugins.iptvplayer.moonwalk_df_format.value
                 tmpTab = CSelOneLink(tmpTab, __getLinkQuality, maxRes).getSortedLinks()
                 tmpTab = [tmpTab[0]]
             for item in tmpTab:
                 linksTab.append({'name':'[f4m/hds] %sp' % __getLinkQuality(item), 'url':item['url']})
     except:
         printExc()
     return linksTab
 def getVideoLink(self, cItem):
     printDBG("TelewizjadaNetApi.getVideoLink")
     
     url = self.MAIN_URL + 'live.php?cid=%s' % cItem['cid']
     sts, data = self.cm.getPage(url, self.http_params)
     if not sts: return []
     
     http_params = dict(self.http_params)
     HTTP_HEADER= { 'User-Agent':'Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:21.0) Gecko/20100101 Firefox/21.0'}
     http_params.update({'header':HTTP_HEADER})
     http_params['header']['Referer'] = url
     
     url = self.MAIN_URL + 'get_mainchannel.php'
     sts, data = self.cm.getPage(url, http_params, {'cid':cItem['cid']})
     if not sts: return []
     try:
         data = byteify(json.loads(data))
         vid_url = data['url']
     except:
         printExc()
         return []
     
     url = self.MAIN_URL + 'set_cookie.php'
     sts, data = self.cm.getPage(url, http_params, {'url':vid_url})
     if not sts: return []
     
     url = self.MAIN_URL + 'get_channel_url.php'
     sts, data = self.cm.getPage(url, http_params, {'cid':cItem['cid']})
     if not sts: return []
     
     try:
         vid_url = byteify(json.loads(data))
         vid_url = vid_url['url']
     except:
         vid_url = data
     
     urlsTab = []
     vid_url = vid_url.strip()
     if vid_url.startswith('http://') and 'm3u8' in vid_url:
         try:
             sessid = self.cm.getCookieItem(self.COOKIE_FILE, 'sessid')
             msec   = self.cm.getCookieItem(self.COOKIE_FILE, 'msec')
             statid = self.cm.getCookieItem(self.COOKIE_FILE, 'statid')
             url = strwithmeta(vid_url, {'Cookie':'sessid=%s; msec=%s; statid=%s;' % (sessid, msec, statid)})
             urlsTab = getDirectM3U8Playlist(url)
         except:
             SetIPTVPlayerLastHostError("Problem z dostępem do pliku \"%\".\nSprawdź, czy masz wolne miejsce na pliki cookies." % self.COOKIE_FILE)
     return urlsTab
 def getVideoUrl(self, url):
     printDBG("getVideoUrl url[%s]" % url)
     linksTab = []
     sts, data = self.cm.getPage(url)
     if not sts:
         printDBG("getVideoUrl except")
         return linksTab
     
     match = re.search( '{"file":"([^"]+?.mp4)"}', data )
     if match: 
         linksTab.append( {'name': 'mp4', 'url': match.group(1)} )
     match = re.search( '{"file":"([^"]+?.m3u8)"}', data )
     if match: 
         m3u8Tab = getDirectM3U8Playlist( match.group(1))
         linksTab.extend(m3u8Tab)
     return linksTab
    def getVideoLink(self, cItem):
        printDBG("EdemTvApi.getVideoLink")
        
        sts, data = self.cm.getPage(cItem['url'], self.http_params)
        if not sts: return []
        
        data =  self.cm.ph.getDataBeetwenMarkers(data, 'playlist:', ']', False)[1]
        
        hlsUrl = self.cm.ph.getSearchGroups(data, '''['"](http[^'^"]+?)['"]''')[0]
        rmpUrl = self.cm.ph.getSearchGroups(data, '''['"](rtmp[^'^"]+?)['"]''')[0]

        urlsTab = []
        if hlsUrl.startswith('http://') and 'm3u8' in hlsUrl:
            urlsTab = getDirectM3U8Playlist(hlsUrl)
        if rmpUrl.startswith('rtmp'):
            urlsTab.append({'name':'rtmp', 'url':rmpUrl + ' live=1'})
        return urlsTab
 def getLinksForVideo(self, cItem):
     printDBG("Hitbox.getLinksForVideo [%s]" % cItem)
     urls = []
     if 'channel_link' in cItem:
         live = True
         urls.append( { 'name':'hls', 'type':'hls', 'url':Hitbox.MAIN_URL + 'player/hls/%s.m3u8' % cItem['channel_link'].split('/')[-1] } )
     elif 'media_id' in cItem:
         live = False
         sts, data = self.cm.getPage( Hitbox.MAIN_URL + 'api/player/config/video/%s?redis=true&embed=false&qos=false&redis=true&showHidden=true' % cItem['media_id'] )
         if sts:
             try:
                 data = byteify( json.loads(data) )
                 baseUrl = data['clip']['baseUrl']
                 if None == baseUrl: baseUrl = ''
                 for item in data['clip']['bitrates']:
                     url = item['url']
                     if url.split('?')[0].endswith('m3u8'):
                         type = 'hls'
                     else: type = 'vod'
                             
                     if not url.startswith('http'):
                         if 'vod' == type:
                             url = baseUrl + '/' + url
                         else: url = Hitbox.MAIN_URL + '/' + url
                         
                     if url.startswith('http'):
                         urls.append( {'name':item.get('label', 'vod'), 'type':type, 'url':url} )
                         if 'vod' == type: break
             except: printExc()
             
     urlTab = []
     for urlItem in urls:
         if 'hls' == urlItem['type']:
             url = urlItem['url']
             data = getDirectM3U8Playlist(url, checkExt=False)
             if 1 == len(data):
                 urlItem['url'] = urlparser.decorateUrl(urlItem['url'], {'iptv_proto':'m3u8', 'iptv_livestream':live})
                 urlTab.append(urlItem)
             else:
                 for item in data:
                     item['url'] = urlparser.decorateUrl(item['url'], {'iptv_proto':'m3u8', 'iptv_livestream':live})
                     urlTab.append(item)
         else:
             urlTab.append(urlItem)
     return urlTab
 def getVideoLink(self, cItem):
     printDBG("WkylinewebcamsCom.getVideoLink")
     urlsTab = []
     sts, data = self.cm.getPage(cItem['url'])
     if not sts: return urlsTab
     url = self.cm.ph.getSearchGroups(data, '''['"](http[^"^']+?m3u8[^"^']*?)["']''', 1, True)[0]
     if url.startswith('http'):
         urlsTab = getDirectM3U8Playlist(url)
     data = self.cm.ph.getSearchGroups(data, '''href=['"]([^"^']+?/timelapse\.php[^"^']*?)['"][^>]+?title=['"]([^'^"]+?)['"]''', 2, True)
     name = data[1]
     url  = self.getFullUrl(data[0].replace('&amp;', '&'))
     if not url.startswith('http'): return urlsTab
     sts, data = self.cm.getPage(url)
     if not sts: return urlsTab
     url = self.cm.ph.getSearchGroups(data, '''url:['"]([^"^']+?)["']''', 1, True)[0]
     if '://' in url:
         urlsTab.append({'name':name, 'url':url})
     return urlsTab
 def getVideoUrl(self, url):
     videoUrl = ''
     videosTab = []
     vid = re.compile("kreskowka/(.+?)/").findall(url)
     
     if 0 == len(vid): return []
     
     HEADER = {'Referer' : url}
     query_data = {'url': 'http://www.kreskoweczki.pl/fullscreen/', 'header': HEADER, 'return_data': True}
     postdata = {'v_id' : vid[0]}
     try:
         data = self.cm.getURLRequestData(query_data, postdata)
     except:
         printDBG('getVideoUrl EXCEPTION')
         return videosTab
     matchAll = re.compile("Loader.skipBanners(.+?)Loader.skipBanners", re.DOTALL).findall(data)
     printDBG(str(matchAll))
     if len(matchAll) > 0:
         match = re.compile('Loader.loadFlashFile."(.+?)"').findall(matchAll[0])
         if len(match) > 0:
             videoUrl = match[0]
         else:
             match = re.compile('src="(.+?)"').findall(matchAll[0])
             if len(match) > 0:
                 videoUrl = match[0]
                 
     match = re.search('src="(http[^"]+?)"', videoUrl )
     if match:
         videoUrl = match.group(1)
         
     match = re.search("/embed/proxy[^.]+?.php", videoUrl)
     if match:
         sts,data = self.cm.getPage(videoUrl)
         if sts:
             match = re.search('url: "[^?^"]+?\?url=([^"]+?)"', data)
             if match:
                 url = match.group(1)
                 if url.endswith('.m3u8'):
                     return getDirectM3U8Playlist(url)
     else: 
         if videoUrl.startswith('//'):
             videoUrl = 'http:' + videoUrl
         return self.up.getVideoLinkExt(videoUrl)
     return []
 def getLinksForVideo(self, cItem):
     printDBG("Twitch.getLinksForVideo [%s]" % cItem)
     urlTab = []
     if 'channel' in cItem:
         url = Twitch.CHANNEL_TOKEN_URL % cItem['channel']
         sts, data = self.cm.getPage(url)
         if sts:
             try:
                 data = json.loads(data)
                 url = Twitch.LIVE_URL % (cItem['channel'], urllib.quote(self._getStr(data['token'])), self._getStr(data['sig']))
                 data = getDirectM3U8Playlist(url, checkExt=False)
                 for item in data:
                     item['url'] = urlparser.decorateUrl(item['url'], {'iptv_block_exteplayer':True, 'iptv_proto':'m3u8', 'iptv_livestream':True})
                     urlTab.append(item)
             except: printExc()
     elif '' != cItem['url']:
         urlTab.append({'name':cItem['title'], 'url':cItem['url']})
 
     return urlTab
 def getLinksForVideo(self, cItem):
     printDBG("Urllist.getLinksForVideo url[%s]" % cItem['url'])
     videoUrls = []
     uri, params   = DMHelper.getDownloaderParamFromUrl(cItem['url'])
     printDBG(params)
     uri = urlparser.decorateUrl(uri, params)
     
     urlSupport = self.up.checkHostSupport( uri )
     if 1 == urlSupport:
         retTab = self.up.getVideoLinkExt( uri )
         videoUrls.extend(retTab)
     elif 0 == urlSupport and self._uriIsValid(uri):
         if uri.split('?')[0].endswith('.m3u8'):
             retTab = getDirectM3U8Playlist(uri)
             videoUrls.extend(retTab)
         elif uri.split('?')[0].endswith('.f4m'):
             retTab = getF4MLinksWithMeta(uri)
             videoUrls.extend(retTab)
         else:
             videoUrls.append({'name':'direct link', 'url':uri})
     return videoUrls
 def getLinksForVideo(self, cItem):
     printDBG("Escreen.getLinksForVideo")
     urlsTab = []
     urls = cItem.get('urls', [])
     if 0 == len(urls): 
         url = cItem.get('url', '')
         type = cItem.get('link_type', '')
         if type in ['cartoon', 'movie']: 
             url += str(self.getPosterID()).strip()
             urls = [{'name':'e-screener.tv', 'url':url}]
         elif type == 'channel':
             serwers = self.selectServers( self.getServers(), cItem.get('rtmpserver', '') )
             for serv in serwers: urlsTab.append({'name':serv['name'], 'url':url % serv['url']})
         else: urls = [{'url':url}]
     else: urls = self.selectServers(urls)
     for item in urls:
         url = item.get('url', '')
         name = item.get('name', 'e-screener.tv')
         if '' == url: continue
         if '.m3u8' in url: urlsTab.extend( getDirectM3U8Playlist(url) )
         else: urlsTab.append({'name':name, 'url':url})
     return urlsTab
Exemple #21
0
 def getVideoLink(self, cItem):
     printDBG("UstvnowApi.getVideoLink")
     
     sts, data = self.cm.getPage(cItem['priv_url'], self.defParams)
     if not sts: return []
     
     url = self.cm.ph.getSearchGroups(data, 'for="popup-%s"[^>]*?href="([^"]+?)"[^>]*?>' % cItem['ui_page'])[0]
     url = self._getFullUrl(url)
     
     sts, data = self.cm.getPage(url, self.defParams)
     if not sts: return []
     
     url = self.cm.ph.getSearchGroups(data, 'src="([^"]+?)"')[0]
     urlsTab = []
     tmp = getDirectM3U8Playlist(strwithmeta(url, {'User-Agent':self.HTTP_HEADER['User-Agent']}), cookieParams = {'cookiefile': self.cookiePath, 'use_cookie': True, 'load_cookie':True, 'save_cookie':True})
     hdntl = self.cm.getCookieItem(self.cookiePath, 'hdntl')
     
     for item in tmp:
         item['url'] = urlparser.decorateUrl(item['url'], {'User-Agent':self.HTTP_HEADER['User-Agent'], 'Cookie':"hdntl=%s" % urllib.unquote(hdntl)})
         urlsTab.append(item)
     
     return urlsTab
 def getLinksForVideo(self, cItem):
     printDBG("Hitbox.getLinksForVideo [%s]" % cItem)
     urlTab = []
     url = ''
     if 'channel_link' in cItem:
         url = Hitbox.MAIN_URL + 'player/hls/%s.m3u8' % cItem['channel_link'].split('/')[-1]
         '''
         url = Hitbox.MAIN_URL + 'api/media/live/%s?showHidden=true' % cItem['channel_link'].split('/')[-1]
         sts, data = self.cm.getPage(url)
         if not sts: return urlTab
         try:
             data = byteify( json.loads(data) )
             channelData = data['livestream'][0]
             url = Hitbox.MAIN_URL +  'api/player/config/live/%s?embed=false&showHidden=true' % 
             
             
             url = Hitbox.LIVE_URL % (cItem['channel'], urllib.quote(self._getStr(data['token'])), self._getStr(data['sig']))
             data = getDirectM3U8Playlist(url, checkExt=False)
             for item in data:
                 item['url'] = urlparser.decorateUrl(item['url'], {'iptv_block_exteplayer':True, 'iptv_proto':'m3u8', 'iptv_livestream':True})
                 urlTab.append(item)
         except: printExc()
         '''
     elif 'media_id' in cItem:
         sts, data = self.cm.getPage( Hitbox.MAIN_URL + 'api/player/config/video/%s?redis=true&embed=false&qos=false&redis=true&showHidden=true' % cItem['media_id'] )
         if sts:
             try:
                 data = byteify( json.loads(data) )
                 if data['clip']['url'].startswith('http'):
                     url = data['clip']['url']
             except: printExc()
     if '' != url:
         data = getDirectM3U8Playlist(url, checkExt=False)
         for item in data:
             item['url'] = urlparser.decorateUrl(item['url'], {'iptv_proto':'m3u8', 'iptv_livestream':True})
             urlTab.append(item)
 
     return urlTab
Exemple #23
0
    def getLinksForVideo(self, cItem):
        printDBG("TED.getLinksForVideo [%s]" % cItem)
        subTracks = []
        urlTab = []

        #cItem['url'] = 'https://www.ted.com/talks/douglas_adams_parrots_the_universe_and_everything'

        sts, data = self.getPage(cItem['url'])
        if not sts:
            return []

        def _addLinkItem(urlTab, item, url, namePrefix=''):
            try:
                if not self.cm.isValidUrl(url) and not url.startswith(
                        'merge://'):
                    return
                if 'width' in item and 'height' in item:
                    name = '%sx%s (%s)' % (item['width'], item['height'],
                                           item['bitrate'])
                else:
                    name = item.get('name', str(item['bitrate']))
                bitrate = item['bitrate']
                urlTab.append({
                    'name': namePrefix + name,
                    'url': url,
                    'bitrate': bitrate,
                    'need_resolve': 0
                })
            except Exception:
                printExc()

        tmp = self.cm.ph.getDataBeetwenMarkers(data, 'talkPage.init",', ')<',
                                               False)[1]
        try:
            playerData = json_loads(tmp)['__INITIAL_DATA__']
            tmp = playerData.get('media', {}).get('internal', {})
            for key in tmp:
                bitrate = self.cm.ph.getSearchGroups(key, '([0-9]+)k')[0]
                if bitrate == '':
                    continue
                item = tmp[key]
                item['bitrate'] = int(bitrate)
                if '/mp4' not in item.get('mime_type', ''):
                    continue
                _addLinkItem(urlTab, item, item.get('uri', ''))

            tmp = playerData['talks'][0]['player_talks'][0]
            rtmpTab = tmp['resources'].get('rtmp', [])
            if rtmpTab == None:
                rtmpTab = []
            for item in rtmpTab:
                url = item.get('file', '')
                if not url.startswith('mp4:'):
                    continue
                url = 'https://pc.tedcdn.com/' + url[4:]
                _addLinkItem(urlTab, item, url)

            h264Tab = tmp['resources'].get('h264', [])
            if h264Tab == None:
                h264Tab = []
            for item in h264Tab:
                _addLinkItem(urlTab, item, item['file'])

            if len(h264Tab) == 1:
                reObj = re.compile('[/\-\.]([0-9]+k)\.')
                baseMp4Url = urlTab[-1]['url']
                baseBitrate = ph.search(baseMp4Url, reObj)[0]
                hlsItem = tmp['resources'].get('hls', {})
                if hlsItem == None:
                    hlsItem = {}
                url = hlsItem.get('stream', '')
                if url == None:
                    url = ''

                tmp = getDirectM3U8Playlist(self.cm.getFullUrl(
                    url, self.cm.meta['url']),
                                            checkExt=False)
                for item in tmp:
                    url = item['url']
                    if url.startswith('merge://'):
                        url = url.meta.get('video_url', '')
                    bitrate = ph.search(url, reObj)[0]
                    url = baseMp4Url.replace(baseBitrate, bitrate)
                    printDBG(">> %s %s %s" % (url, baseMp4Url, url))
                    _addLinkItem(urlTab, item, url, '[MP4] ')
                #for item in tmp:
                #    _addLinkItem(urlTab, item, item['url'], '[HLS] ')

            def __getLinkQuality(itemLink):
                try:
                    return int(itemLink['bitrate'])
                except Exception:
                    return 0

            urlTab = CSelOneLink(urlTab, __getLinkQuality,
                                 99999999).getSortedLinks()

            if 0 == len(urlTab):
                if self.cm.isValidUrl(tmp['external']['uri']):
                    urlTab.append({
                        'name': tmp['external']['service'],
                        'url': tmp['external']['uri'],
                        'need_resolve': 1
                    })

            userLang = GetDefaultLang()
            promotItem = None
            format = 'srt'
            for item in tmp.get('languages', []):
                subUrl = 'http://www.ted.com/talks/subtitles/id/%s/lang/%s/format/%s' % (
                    tmp['id'], item['languageCode'], format)
                params = {
                    'title':
                    "%s (%s)" % (item['languageName'], item['endonym']),
                    'url': subUrl,
                    'lang': item['languageCode'],
                    'format': format
                }
                if item['languageCode'] == userLang:
                    promotItem = params
                else:
                    subTracks.append(params)

            if promotItem != None:
                subTracks.insert(0, promotItem)

            if len(subTracks):
                for idx in range(len(urlTab)):
                    urlTab[idx]['url'] = strwithmeta(
                        urlTab[idx]['url'], {'external_sub_tracks': subTracks})

        except Exception:
            printExc()

        return urlTab
Exemple #24
0
    def getLinksForVideo(self, cItem):
        printDBG("SpiegelTv.getLinksForVideo [%s]" % cItem)
        
        cacheKey = cItem['url']
        cacheTab = self.cacheLinks.get(cacheKey, [])
        if len(cacheTab): return cacheTab
        
        self.cacheLinks = {}
        retTab = []
        
        sts, data = self.getPage(cItem['url'])
        if not sts: return
        
        self._fillOneConfig(cItem, data)
        self._initiSession(cItem)
        
        videoId = self.cm.ph.getDataBeetwenMarkers(data, 'video.start(', ')', False)[1].split(',')[0].strip()
        if videoId == '': videoId = cItem['url'].split('/videos/', 1)[-1].split('-')[0]
        
        try:
            cid = self.oneconfig['session_data']['general']['cid']
            clientToken = self.oneconfig['session_data']['device']['clienttoken']
            clientId = self.oneconfig['session_data']['general']['clid']
            deviceId = self.oneconfig['session_data']['device_id']
            
            secret = clientToken[int(deviceId[0]):]
            secret = secret[0:len(secret) - int(deviceId[-1])]
            op = 'byid'
            requestToken = hashlib.md5(''.join((op, clientId, secret))).hexdigest()
            
            urlParams = dict(self.defaultParams)
            urlParams['header'] = dict(self.AJAX_HEADER)
            urlParams['header'].update({'Referer':cItem['url'], 'X-Request-Enable-Auth-Fallback':'1', 'X-Request-CID':cid, 'X-Request-Token':requestToken})
            post_data = {'additionalfields': 'language,channel,actors,studio,licenseby,slug,subtitle,teaser,description',
                         'addInteractionOptions': '1',
                         'addStatusDetails': '1',
                         'addStreamDetails': '1',
                         'addCaptions': '1',
                         'addScenes': '1',
                         'addHotSpots': '1',
                         'addBumpers': '1',
                         'captionFormat': 'data',}
            
            url = 'https://api.nexx.cloud/v3/%s/videos/%s/%s' % (clientId, op, videoId)
            sts, data = self.getPage(url, urlParams, post_data)
            if not sts: return
            
            data = byteify(json.loads(data), '', True)['result']
            try: protectionToken = data['protectiondata']['token']
            except Exception: protectionToken = None
            language = data['general'].get('language_raw') or ''
            data = data['streamdata']
            printDBG(data)
            
            cdn = data['cdnType']
            azureLocator = data['azureLocator']
            AZURE_URL = 'http://nx%s%02d.akamaized.net/'
            def getCdnShieldBase(shieldType='', prefix='-p'):
                for secure in ('', 's'):
                    cdnShield = data.get('cdnShield%sHTTP%s' % (shieldType, secure.upper()))
                    if cdnShield:
                        return 'http%s://%s' % (secure, cdnShield)
                else:
                    return AZURE_URL % (prefix, int(data['azureAccount'].replace('nexxplayplus', '')))
            azureStreamBase = getCdnShieldBase()
            isML = ',' in language
            azureManifestUrl = '%s%s/%s_src%s.ism/Manifest' % (azureStreamBase, azureLocator, videoId, ('_manifest' if isML else '')) + '%s'

            if protectionToken:
                azureManifestUrl += '?hdnts=%s' % protectionToken
            
            try:
                azureProgressiveBase = getCdnShieldBase('Prog', '-d')
                azureFileDistribution = data.get('azureFileDistribution')
                if azureFileDistribution:
                    fds = azureFileDistribution.split(',')
                    if fds:
                        for fd in fds:
                            ss = fd.split(':')
                            if len(ss) != 2: continue
                            tbr = int(ss[0] or 0)
                            if not tbr: continue
                            retTab.append({'name':'[%s] %s' % (tbr, ss[1]), 'tbr':tbr, 'url': '%s%s/%s_src_%s_%d.mp4' % (azureProgressiveBase, azureLocator, videoId, ss[1], tbr)})
            except Exception:
                printExc()
            retTab.sort(key=lambda item: item['tbr'], reverse=True)
            if len(retTab) == 0: 
                retTab = getMPDLinksWithMeta(azureManifestUrl % '(format=mpd-time-csf)', checkExt=False, sortWithMaxBandwidth=999999999)
            if len(retTab) == 0: 
                retTab = getDirectM3U8Playlist(azureManifestUrl % '(format=m3u8-aapl)', checkExt=False, checkContent=True, sortWithMaxBitrate=999999999)
        except Exception:
            printExc()
        if len(retTab):
            self.cacheLinks[cacheKey] = retTab
        for idx in range(len(retTab)):
            retTab[idx]['need_resolve'] = 1
        return retTab
 def getLinksForVideo(self, cItem):
     printDBG("TVPlayer.getLinksForVideo [%s]" % cItem)
     self.tryTologin()
     
     def _SetIPTVPlayerLastHostError(msg):
         if not cItem.get('next_try', False):
             SetIPTVPlayerLastHostError(msg)
     
     retTab = []
     
     sts, data = self.getPage(cItem['url'])
     if not sts: return []
     
     checkUrl = self.cm.ph.getSearchGroups(data, '''<[^>]+?id="check"[^>]+?src=['"]([^'^"]+?)['"]''')[0]
     
     playerData = self.cm.ph.getSearchGroups(data, '''<div([^"^']+?class=['"]video-js[^>]+?)>''')[0]
     printDBG(playerData)
     
     playerData = dict(re.findall('''\sdata\-(\w+?)\s*=\s*['"]([^'^"]+?)['"]''', playerData))
     printDBG(playerData)
     
     if 'resource' not in playerData or 'token' not in playerData: 
         msg = self.cleanHtmlStr(self.cm.ph.getDataBeetwenMarkers(data, '<div class="centered-content">', '</h', False)[1])
         _SetIPTVPlayerLastHostError(msg)
         return []
     
     url = self.getFullUrl('/watch/context?resource={0}&gen={1}'.format(playerData.get('resource'), playerData.get('token')))
     sts, data = self.getPage(url)
     if not sts: return []
     printDBG("response: [%s]" % data)
     
     try:
         data = byteify(json.loads(data))
         url = 'https://api.tvplayer.com/api/v2/stream/live'
         ''' id: e.resource,
             service: 1,
             platform: e.platform.key,
             validate: e.validate
         '''
         post_data = {'id':data['resource'], 'service':1, 'platform':data['platform']['key'], 'validate':data['validate']}
         if 'token' in data: post_data['token'] = data['token']
             
         sts, data = self.getPage(url, {}, post_data)
         if not sts:
             try: _SetIPTVPlayerLastHostError(str(data))
             except Exception: pass
             return []
         printDBG("response: [%s]" % data)
         
         data = byteify(json.loads(data))['tvplayer']['response']
         if 'error' in data: 
             _SetIPTVPlayerLastHostError(data['error'])
             if not config.plugins.iptvplayer.tvplayercom_drmbypass.value or cItem.get('next_try', False):
                 return []
             self.getLinksForVideo({'next_try':True, 'url':self.defUrl})
             streamUrl = 'https://live.tvplayer.com/stream.m3u8?id=%s' % post_data['id']
         else:
             if None != data.get('drmToken'):
                 _SetIPTVPlayerLastHostError(_('DRM protected streams are not supported.'))
                 if not config.plugins.iptvplayer.tvplayercom_drmbypass.value or cItem.get('next_try', False):
                     return []
                 self.getLinksForVideo({'next_try':True, 'url':self.defUrl})
                 streamUrl = 'https://live.tvplayer.com/stream.m3u8?id=%s' % post_data['id']
             else:
                 streamUrl = data.get('stream', '')
                 if not self.cm.isValidUrl(streamUrl):
                     _SetIPTVPlayerLastHostError(_('No playable sources found.'))
                     return []
         
         retTab = getDirectM3U8Playlist(streamUrl, checkExt=True, variantCheck=True, cookieParams=self.defaultParams, checkContent=True)
         if len(retTab):
             cookieHeader = self.cm.getCookieHeader(self.COOKIE_FILE)
             for idx in range(len(retTab)):
                 retTab[idx]['url'] =  strwithmeta(retTab[idx]['url'], {'iptv_proto':'m3u8', 'Cookie':cookieHeader, 'User-Agent': self.defaultParams['header']['User-Agent']})
                 
             def __getLinkQuality( itemLink ):
                 try: 
                     return int(itemLink['bitrate'])
                 except Exception:
                     printExc()
                     return 0
             
             retTab = CSelOneLink(retTab, __getLinkQuality, int(int(config.plugins.iptvplayer.tvplayercom_preferredbitrate.value)*1.2)).getSortedLinks()
             if len(retTab) and config.plugins.iptvplayer.tvplayercom_usepreferredbitrate.value:
                 retTab = [retTab[0]] 
             printDBG(retTab)
         elif self.cm.isValidUrl(checkUrl):
             sts, data = self.getPage(checkUrl)
             if not sts: _SetIPTVPlayerLastHostError(_("Sorry. TVPlayer is currently only available in the United Kingdom"))
     except Exception:
         printExc()
     
     return retTab
Exemple #26
0
    def getLinksForVideo(self, cItem):
        printDBG("ForjaTN.getLinksForVideo [%s]" % cItem)

        if 1 == self.up.checkHostSupport(cItem.get('url', '')):
            videoUrl = cItem['url'].replace('youtu.be/',
                                            'youtube.com/watch?v=')
            return self.up.getVideoLinkExt(videoUrl)

        retTab = []
        subTracksTab = []

        sts, data = self.getPage(cItem['url'])
        if not sts: return []

        cUrl = data.meta['url']

        if cItem.get('f_type', '') == 'episode':
            episodeId = cItem['url']
            if episodeId.endswith('/'): episodeId = episodeId[-1]
            episodeId = '/'.join(episodeId.split('/')[-2:])

            data = self.cm.ph.getDataBeetwenReMarkers(
                data, re.compile('''episodes\s*='''), re.compile('''];'''),
                False)[1]
            data = data.strip() + ']'
            ret = iptv_js_execute('print(JSON.stringify(%s));' % data)
            if ret['sts'] and 0 == ret['code']:
                try:
                    data = byteify(json.loads(ret['data']), '', True)
                    for eItem in data:
                        if episodeId not in eItem.get('poster', ''): continue
                        for item in eItem['sources']:
                            vidType = item['type'].lower()
                            vidUrl = self.getFullUrl(item['src'],
                                                     cUrl).replace(' ', '%20')
                            name = self.cleanHtmlStr(item['label'])
                            tmpTab = []
                            if 'x-mpegurl' in vidType:
                                tmpTab = getDirectM3U8Playlist(
                                    vidUrl,
                                    checkExt=False,
                                    checkContent=True,
                                    cookieParams=self.defaultParams)
                            elif 'mp4' in vidType:
                                tmpTab.append({'name': 'mp4', 'url': vidUrl})

                            for idx in range(len(tmpTab)):
                                tmpTab[idx]['name'] = '[%s] %s' % (
                                    name, tmpTab[idx]['name'])
                            retTab.extend(tmpTab)

                        for item in eItem['textTracks']:
                            if item.get('kind', '') != 'captions': continue
                            subTracksTab.append({
                                'title':
                                item['label'],
                                'url':
                                self.getFullUrl(item['src']),
                                'lang':
                                item['language'],
                                'format':
                                'vtt'
                            })

                        break
                except Exception:
                    printExc()
        else:
            tmp = self.cm.ph.getDataBeetwenMarkers(data, 'player.src(', ')')[1]
            if tmp == '':
                tmp = self.cm.ph.getDataBeetwenNodes(data, ('[', ']', '.m3u8'),
                                                     (';', ' '))[1]
            tmpTab = tmp.split('},')
            for tmp in tmpTab:
                vidType = self.cm.ph.getSearchGroups(
                    tmp, '''type['"]?\s*:\s*['"]([^'^"]+?)['"]''')[0].lower()
                vidLabel = self.cm.ph.getSearchGroups(
                    tmp, '''label['"]?\s*:\s*['"]([^'^"]+?)['"]''')[0]
                vidUrl = self.getFullUrl(
                    self.cm.ph.getSearchGroups(
                        tmp, '''src['"]?\s*:\s*['"]([^'^"]+?)['"]''')[0], cUrl)

                if not self.cm.isValidUrl(vidUrl): return []

                if 'x-mpegurl' in vidType:
                    retTab = getDirectM3U8Playlist(
                        vidUrl,
                        checkExt=False,
                        checkContent=True,
                        cookieParams=self.defaultParams)
                elif 'mp4' in vidType:
                    retTab.append({'name': 'mp4 %s' % vidLabel, 'url': vidUrl})

            data = self.cm.ph.getAllItemsBeetwenMarkers(
                data, '<video', '</video>')
            for tmp in data:
                tmp = self.cm.ph.getAllItemsBeetwenMarkers(tmp, '<track', '>')
                for item in tmp:
                    if 'caption' not in item: continue
                    url = self.getFullUrl(
                        self.cm.ph.getSearchGroups(
                            item, '''src=['"]([^'^"]+?)['"]''')[0])
                    if not self.cm.isValidUrl(url): continue
                    lang = self.cm.ph.getSearchGroups(
                        item, '''srclang=['"]([^'^"]+?)['"]''')[0]
                    title = self.cm.ph.getSearchGroups(
                        item, '''label=['"]([^'^"]+?)['"]''')[0]
                    subTracksTab.append({
                        'title': title,
                        'url': url,
                        'lang': lang,
                        'format': 'vtt'
                    })

        cookieHeader = self.cm.getCookieHeader(self.COOKIE_FILE)
        for idx in range(len(retTab)):
            retTab[idx]['url'] = strwithmeta(
                retTab[idx]['url'], {
                    'User-Agent': self.USER_AGENT,
                    'Referer': cItem['url'],
                    'Cookie': cookieHeader,
                    'external_sub_tracks': subTracksTab
                })
        return retTab
 def getResolvedURL(self, url):
     linkTab = getDirectM3U8Playlist(url, False)
     for idx in range(len(linkTab)):
         linkTab[idx]['url'] = urlparser.decorateUrl(linkTab[idx]['url'], {'iptv_proto':'m3u8'})
     return linkTab
Exemple #28
0
    def getLinksForVideo(self, cItem):
        printDBG("PLWWECOM.getLinksForVideo [%s]" % cItem)
        urlTab = []

        if '' == self.countryCode:
            self.countryCode = self.cm.getCountryCode()

        HTTP_HEADER = dict(self.HTTP_HEADER)
        if 'pl' != self.countryCode:
            HTTP_HEADER['Referer'] = self.proxy_gateway
            params = {
                'header': HTTP_HEADER,
                'proxy_gateway': self.proxy_gateway
            }
        else:
            params = {}

        sts, data = self.cm.getPage(cItem['url'], params)
        if not sts: return urlTab

        hlsUrl = self.cm.ph.getSearchGroups(
            data,
            '''['"]([^'^"]*?\.m3u8[^'^"]*?)['"]''')[0].replace('\\/', '/')
        if hlsUrl.startswith('//'):
            hlsUrl = 'http:' + hlsUrl
        if self.cm.isValidUrl(hlsUrl):
            return getDirectM3U8Playlist(hlsUrl,
                                         checkExt=False,
                                         variantCheck=False)

        baseUrl = 'http://c.brightcove.com/services/viewer/htmlFederated?playerID={0}&playerKey={1}&purl={2}&%40videoPlayer={3}&flashID={4}'
        data = self.cm.ph.getDataBeetwenMarkers(data, '<object id=',
                                                '</object>', True)[1]
        playerID = self.cm.ph.getSearchGroups(
            data, ' name="playerID"[^>]+?value="([^"]+?)"')[0]
        playerKey = self.cm.ph.getSearchGroups(
            data, ' name="playerKey"[^>]+?value="([^"]+?)"')[0]
        videoPlayer = self.cm.ph.getSearchGroups(
            data, ' name="@videoPlayer"[^>]+?value="([^"]+?)"')[0]
        flashID = self.cm.ph.getSearchGroups(data, ' id="([^"]+?)"')[0]
        url = baseUrl.format(playerID, playerKey, urllib.quote(cItem['url']),
                             videoPlayer, flashID)

        HTTP_HEADER = dict(self.HTTP_HEADER)
        if 'pl' != self.countryCode:
            HTTP_HEADER['Referer'] = self.proxy_gateway
            params = {
                'header': HTTP_HEADER,
                'proxy_gateway': self.proxy_gateway
            }
        else:
            params = {}

        sts, data = self.cm.getPage(url, params)
        if not sts: return urlTab
        data = self.cm.ph.getDataBeetwenMarkers(data, 'var experienceJSON = {',
                                                '};', False)[1]
        data = '{%s}' % data
        try:
            data = byteify(json.loads(data))
            if data['success']:
                for item in data['data']['programmedContent']['videoPlayer'][
                        'mediaDTO']['renditions']:
                    item['need_resolve'] = 0
                    item['name'] = '%sx%s' % (item['frameWidth'],
                                              item['frameHeight'])
                    item['url'] = item['defaultURL']
                    urlTab.append(item)
        except Exception:
            printExc()

        return urlTab
    def getLinksForVideo(self, cItem):
        printDBG("SportDeutschland.getLinksForVideo [%s]" % cItem)
        HTTP_HEADER = {
            'User-Agent':
            'Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:21.0) Gecko/20100101 Firefox/21.0',
            'Accept':
            'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
        }
        videoUrls = []
        videoUrl = ''
        if '' != cItem['video']:
            videoUrl = cItem['video']
        else:
            if '' != cItem['url']:
                sts, data = self.cm.getPage(cItem['url'])
                if sts:
                    try:
                        data = json.loads(data)
                        #printDBG("[%s]" % data)
                        videoUrl = self._getJItemStr(data['asset'], 'video')
                        if '' == videoUrl:
                            assets_info = self._getJItemStr(
                                data['asset'], 'url')
                            if len(assets_info):
                                sts, assets_info = self.cm.getPage(
                                    assets_info, {'header': HTTP_HEADER})
                                if sts:
                                    try:
                                        assets_info = json.loads(assets_info)
                                        videoUrl = self._getJItemStr(
                                            assets_info, 'video')
                                        printDBG(
                                            'SportDeutschland.getLinksForVideo "video" from "assets_info" |%s|'
                                            % videoUrl)
                                    except:
                                        printExc()
                        if '' == videoUrl:
                            player = self._getJItemStr(data['asset'], 'player')
                            if '' != player:
                                sts, data = self.cm.getPage(
                                    player, {'header': HTTP_HEADER})
                                if sts:
                                    videoUrl = self.cm.ph.getSearchGroups(
                                        data,
                                        '<a class="asset"[^>]+?href="([^"]+?)"'
                                    )[0]
                    except:
                        printExc()

        if '.smil?' in videoUrl:
            if 'rtmp' == config.plugins.iptvplayer.sportdeutschland_streamprotocol.value:
                sts, data = self.cm.getPage(videoUrl)
                if sts:
                    #printDBG("+++++++++++++++++++++++++++++++++\n%s\n+++++++++++++++++++++++++++++++++" % data)
                    videoUrl = self.cm.ph.getSearchGroups(
                        data, 'meta base="(rtmp[^"]+?)"')[0]
                    videoUrl += '/' + self.cm.ph.getSearchGroups(
                        data, 'video src="([^"]+?)"')[0]
                    if videoUrl.startswith('rtmp'):
                        videoUrls.append({
                            'name': 'SportDeutschland rtmp',
                            'url': videoUrl.replace('&amp;', '&')
                        })
            else:
                videoUrl = videoUrl.replace('.smil?', '.m3u8?')
                videoUrls = getDirectM3U8Playlist(videoUrl, checkExt=False)
        elif videoUrl.split('?')[0].endswith('mp4'):
            videoUrl = self.up.decorateUrl(videoUrl,
                                           {"iptv_buffering": "forbidden"})
            videoUrls.append({'name': 'SportDeutschland mp4', 'url': videoUrl})
        return videoUrls
    def getLinksForVideo(self, cItem):
        printDBG("Laola1TV.getLinksForVideo [%s]" % cItem)
        urlTab = []
        baseUrl = cItem['url']
        try:
            sts, response = self.cm.getPage(baseUrl, {'return_data':False})
            baseUrl = response.geturl()
            data = response.read().strip()
            response.close()
        except:
            printExc()
            return []
        
        vidUrl = self.cm.ph.getSearchGroups(data, '<iframe[^>]+?src="([^"]+?)"')[0]
        
        if '' == vidUrl:
            error = self.cleanHtmlStr( self.cm.ph.getDataBeetwenMarkers(data, '<div class="videoplayer-overlay">', '</p>', False)[1] )
            if '' != error: SetIPTVPlayerLastHostError(error)
            return []
        
        baseUrl = baseUrl[baseUrl.find('://')+3:]
        baseUrl = 'http://' + baseUrl[0:baseUrl.find('/')] + '/'
        
        
        vidUrl = self._getFullUrl( vidUrl, baseUrl )
        
        sts, data = self.getPage(vidUrl)
        if not sts: return []
        
        mainAuth = self.cm.ph.getSearchGroups(data, '[ .]auth = "([^"]+?)"')[0]
        mainTimestamp = self.cm.ph.getSearchGroups(data, '[ .]timestamp = "([^"]+?)"')[0]
        vs_target = self.cm.ph.getSearchGroups(data, 'var vs_target = ([0-9]+?);')[0]
        data = self.cleanHtmlStr( self.cm.ph.getDataBeetwenMarkers(data, 'var flashvars', '};', False)[1] )
        def _getParamValue(paramName, data):
            return self.cm.ph.getSearchGroups(data, '%s: "([^"]+?)"' % paramName)[0]
            
        streamid  = _getParamValue('streamid', data)
        partnerid = _getParamValue('partnerid', data)
        portalid  = _getParamValue('portalid', data)
        sprache   = _getParamValue('sprache', data)
        vidUrl = "http://www.laola1.tv/server/hd_video.php?play=%s&partner=%s&portal=%s&v5ident&lang=%s&v=1" % (streamid, partnerid, portalid, sprache)
        
        sts, data = self.getPage(vidUrl)
        if not sts: return []
        
        vidUrl = self.cm.ph.getDataBeetwenMarkers(data, '<url>', '</url>', False)[1].replace('&amp;', '&')
        fallbackVidUrl = self.cm.ph.getDataBeetwenMarkers(data, '<fallbackurl>', '</fallbackurl>', False)[1].replace('&amp;', '&')
        id      = self.cm.ph.getDataBeetwenMarkers(data, '<id>', '</id>', False)[1]
        area    = self.cm.ph.getDataBeetwenMarkers(data, '<area>', '</area>', False)[1]
        label   = self.cm.ph.getDataBeetwenMarkers(data, '<label>', '</label>', False)[1]
        req_abo = self.cm.ph.getDataBeetwenMarkers(data, '<req_liga_abos>', '</req_liga_abos>', False)[1].split(',')
        live    = self.cm.ph.getDataBeetwenMarkers(data, '<live>', '</live>', False)[1]
        if live == 'false': isLive = False
        else: isLive = True

        ######################################################
        streamaccessTab = []
        url = 'https://club.laola1.tv/sp/laola1/api/v3/user/session/premium/player/stream-access?videoId=' + id + '&target=' + vs_target + '&label=' + label + '&area=' + area + '&format=iphone'
        post_data = {}
        for idx in range(len(req_abo)):
            post_data[idx] = req_abo[idx]
        sts, data = self.getPage(url, {}, post_data)
        try:
            data = byteify(json.loads(data))
            for item in data['data']['stream-access']:
                streamaccessTab.append(item)
        except:
            printExc()
        
        if 0 == len(streamaccessTab):
            def addZ(n):
                if n < 10: return '0%d' % n
                return str(n)
            
            def getTimestamp():
                date = datetime.datetime.now()
                year  = date.year
                month = date.month
                datum = date.day
                hour  = date.hour
                min   = date.minute
                sec   = date.second
                timestamp = addZ(year) + addZ(month) + addZ(datum) + addZ(hour) + addZ(min) + addZ(sec)
                return timestamp

            randomNumber = str(random.randint(10000000, 99999999))
            htmlTimestamp = str(time.time()).split('.')[0]
            ident = randomNumber + htmlTimestamp
            timestamp = mainTimestamp
            if '' == timestamp:
                timestamp = getTimestamp()
            
            for baseUrl in [vidUrl, fallbackVidUrl]:
                streamaccessTab.append(baseUrl + '&ident=' + ident + '&klub=0&unikey=0&timestamp=' + timestamp + '&auth=' + mainAuth + '&format=iphone');
        
        for streamaccess in streamaccessTab:
            for myip in ['', config.plugins.iptvplayer.laola1tv_myip1.value, config.plugins.iptvplayer.laola1tv_myip2.value]:
                if '' != myip: header = {'X-Forwarded-For':myip}
                else: header = {}
                sts, data = self.getPage(streamaccess, {'header':header})
                if not sts: return urlTab
                data = self.cm.ph.getDataBeetwenMarkers(data, '<data>', '</data>', False)[1]
                printDBG(data)
                comment = self.cm.ph.getSearchGroups(data, 'comment="([^"]+?)"')[0]
                auth = self.cm.ph.getSearchGroups(data, 'auth="([^"]+?)"')[0]
                if auth in ['restricted', 'blocked']: continue
                url  = self.cm.ph.getSearchGroups(data, 'url="([^"]+?)"')[0]
                url = url + '?hdnea=' + auth
                
                tmp = getDirectM3U8Playlist(url, checkExt=False)
                for item in tmp:
                    item['need_resolve'] = 0
                    urlTab.append(item)
                break
            if 0 < len(urlTab):
                break
            
        if 0 < len(urlTab):
            max_bitrate = int(config.plugins.iptvplayer.laola1tv_defquality.value)
            def __getLinkQuality( itemLink ):
                try:
                    value = itemLink['bitrate']
                    return int(value)
                except:
                    printExc()
                    return 0
            urlTab = CSelOneLink(urlTab, __getLinkQuality, max_bitrate).getSortedLinks()
            if config.plugins.iptvplayer.laola1tv_onelink.value:
                urlTab = [urlTab[0]] 
        else:
            SetIPTVPlayerLastHostError(comment)
                
        return urlTab
Exemple #31
0
    def getVideoLink(self, cItem):
        printDBG("IKlubNetApi.getVideoLink")
        urlsTab = []

        if cItem.get('vlc', False):
            uri = cItem['url']
            if uri.startswith('http') and uri.split('?')[-1].endswith('.m3u8'):
                urlsTab.extend(getDirectM3U8Playlist(uri))
            elif uri.startswith('rtmp'):
                urlsTab.append({'name': '[rtmp]', 'url': uri + ' live=1 '})
            elif uri.startswith('http'):
                urlsTab.append({
                    'name':
                    '[rtmp]',
                    'url':
                    urlparser.decorateUrl(uri, {'iptv_livestream': True})
                })
            return urlsTab

        url = cItem['url']
        nextTitle = 'Podstawowy '
        for linkIdx in range(2):
            if '' == url: break
            title = nextTitle

            sts, data = self.cm.getPage(url)
            if not sts: return urlsTab

            if 'tvpstream.tvp.pl' in url:
                urlsTab.extend(self.getTvpStreamLink(data))
                if linkIdx > 0:
                    return urlsTab

            url = self.getFullUrl(
                self.cm.ph.getSearchGroups(
                    data,
                    '<a href="([^"]+?)"[^>]*?><img[^>]*?alt="Zapasowy Player"',
                    1, True)[0])
            if '' == url:
                url = self.getFullUrl(
                    self.cm.ph.getSearchGroups(
                        data,
                        '<a href="([^"]+?)"[^>]*?><img[^>]*?alt="[^"]*?vlc[^"]*?"',
                        1, True)[0])
            nextTitle = 'Zapasowy '

            printDBG(data)

            urlNext = self.cm.ph.getSearchGroups(
                data, '<iframe[^>]+?src="([^"]+?iklub[^"]+?)"', 1, True)[0]
            if '' == urlNext:
                urlNext = self.cm.ph.getSearchGroups(
                    data, '<iframe[^>]+?src="([^"]+?)"', 1, True)[0]
            if self.cm.isValidUrl(urlNext):
                sts, data = self.cm.getPage(urlNext)
                if not sts: continue

            data = self.cm.ph.getAllItemsBeetwenMarkers(
                data, 'eval(', ');', False)
            try:
                ddata = ''
                for idx in range(len(data)):
                    tmp = data[idx].split('+')
                    for item in tmp:
                        item = item.strip()
                        if item.startswith("'") or item.startswith('"'):
                            ddata += self.cm.ph.getSearchGroups(
                                item, '''['"]([^'^"]+?)['"]''')[0]
                        else:
                            tmp2 = re.compile(
                                '''unescape\(['"]([^"^']+?)['"]''').findall(
                                    item)
                            for item2 in tmp2:
                                ddata += urllib.unquote(item2)

                printDBG(
                    "++++++++++++++++++++++++++++++++++++++++++++++++++++")
                printDBG(ddata)
                printDBG(
                    "++++++++++++++++++++++++++++++++++++++++++++++++++++")

                funName = self.cm.ph.getSearchGroups(
                    ddata, '''function\s*([^\(]+?)''')[0].strip()
                sp = self.cm.ph.getSearchGroups(
                    ddata, '''split\(\s*['"]([^'^"]+?)['"]''')[0]
                modStr = self.cm.ph.getSearchGroups(
                    ddata, '''\+\s*['"]([^'^"]+?)['"]''')[0]
                modInt = int(
                    self.cm.ph.getSearchGroups(
                        ddata, '''\+\s*(-?[0-9]+?)[^0-9]''')[0])

                ddata = self.cm.ph.getSearchGroups(
                    ddata, '''document\.write[^'^"]+?['"]([^'^"]+?)['"]''')[0]
                data = ''
                tmp = ddata.split(sp)
                ddata = urllib.unquote(tmp[0])
                k = urllib.unquote(tmp[1] + modStr)
                for idx in range(len(ddata)):
                    data += chr((int(k[idx % len(k)]) ^ ord(ddata[idx])) +
                                modInt)

                printDBG(
                    "++++++++++++++++++++++++++++++++++++++++++++++++++++")
                printDBG(data)
                printDBG(
                    "++++++++++++++++++++++++++++++++++++++++++++++++++++")

                if 'rtmp://' in data:
                    rtmpUrl = self.cm.ph.getDataBeetwenMarkers(
                        data, '&source=', '&', False)[1]
                    if rtmpUrl == '':
                        rtmpUrl = self.cm.ph.getSearchGroups(
                            data, r'''['"](rtmp[^"^']+?)['"]''')[0]
                    urlsTab.append({
                        'name': title + ' [rtmp]',
                        'url': rtmpUrl + ' live=1 '
                    })
                elif '.m3u8' in data:
                    file = self.cm.ph.getSearchGroups(
                        data, r'''['"](http[^"^']+?\.m3u8[^"^']*?)['"]''')[0]
                    if file == '':
                        file = self.cm.ph.getDataBeetwenMarkers(
                            data, 'src=', '&amp;', False)[1]
                    urlsTab.extend(getDirectM3U8Playlist(file))
                elif 'tvp.info' in data:
                    vidUrl = self.getFullUrl(
                        self.cm.ph.getSearchGroups(
                            data,
                            '''['"](http[^'^"]+?tvp.info[^'^"]+?)['"]''')[0])
                    sts, data = self.cm.getPage(vidUrl)
                    if not sts: return []
                    urlsTab.extend(self.getTvpStreamLink(data))
                elif 'mrl=' in data:
                    file = self.cm.ph.getSearchGroups(
                        data, '''mrl=['"](http[^'^"]+?)['"]''')[0]
                    urlsTab.append({'name': title + ' [mrl]', 'url': file})
                elif '<source ' in data:
                    file = self.cm.ph.getSearchGroups(
                        data, '''<source[^>]+?src=['"](http[^'^"]+?)['"]''')[0]
                    urlsTab.append({'name': title + ' [src]', 'url': file})
                else:
                    urlsTab.extend(self.up.getAutoDetectedStreamLink(
                        url, data))

                if 'content.jwplatform.com' in data:
                    vidUrl = self.getFullUrl(
                        self.cm.ph.getSearchGroups(
                            data,
                            '''['"]([^'^"]+?content.jwplatform.com[^'^"]+?)['"]'''
                        )[0])

                    sts, data = self.cm.getPage(vidUrl)
                    if not sts: continue

                    if '/players/' not in vidUrl:
                        vidUrl = self.cm.ph.getSearchGroups(
                            data,
                            '''['"](https?[^'^"]+?/players/[^'^"]+?\.js)['"]'''
                        )[0]
                        HEADER = dict(self.HEADER)
                        HEADER['Referer'] = vidUrl
                        sts, data = self.cm.getPage(vidUrl, {'header': HEADER})
                        if not sts: continue

                    data = self.cm.ph.getDataBeetwenMarkers(
                        data, '"sources":', ']', False)[1]
                    file = self.cm.ph.getSearchGroups(
                        data,
                        r'''['"]?file['"]?\s*:\s*['"]([^"^']+)['"],''')[0]
                    printDBG(">>>>>>>>>>>>>>>>>>>>>>>> FILE[%s]" % file)
                    if file.startswith('http') and file.split(
                            '?')[-1].endswith('.m3u8'):
                        urlsTab.extend(getDirectM3U8Playlist(file))
                    elif file.startswith('rtmp'):
                        urlsTab.append({
                            'name': title + ' [rtmp]',
                            'url': file + ' live=1 '
                        })
            except Exception:
                printExc()
                continue

        return urlsTab
Exemple #32
0
    def getLinksForVideo(self, cItem):
        printDBG("Dmdamedia.getLinksForVideo")
        sts, data = self.getPage(cItem['url'])
        if not sts:
            return
        share = self.cm.ph.getDataBeetwenMarkers(data,
                                                 '<div class="beagyazas">',
                                                 '" FRAMEBORDER', False)[1]
        share = share.replace('<iframe src="', '')
        if share != '':
            if 'https:' not in share:
                share = 'https:' + share
        else:
            share = self.cm.ph.getDataBeetwenMarkers(
                data, '<div class="beagyazas">', '" allowfullscreen', False)[1]
            if '<iframe width="640" height="360" frameborder="0" src="' in share:
                share = share.replace(
                    '<iframe width="640" height="360" frameborder="0" src="',
                    '')
            share = share.replace('<iframe width="640" height="360" src="', '')
            if share != '':
                if 'https:' not in share:
                    share = 'https:' + share
            else:
                share = self.cm.ph.getDataBeetwenMarkers(
                    data, '<div class="beagyazas">', '" scrolling=', False)[1]
                share = share.replace('<iframe src="', '')
                if share != '':
                    if 'https:' not in share:
                        share = 'https:' + share
                else:
                    share = self.cm.ph.getDataBeetwenMarkers(
                        data, '<div class="filmbeagyazas">', '" FRAMEBORDER',
                        False)[1]
                    share = share.replace('<iframe src="', '')
                    if share != '':
                        if 'https:' not in share:
                            share = 'https:' + share
                    else:
                        share = self.cm.ph.getDataBeetwenMarkers(
                            data, '<div class="filmbeagyazas">',
                            '" allowfullscreen', False)[1]
                        share = share.replace(
                            '<iframe width="640" height="360" src="', '')
                        if share != '':
                            if 'https:' not in share:
                                share = 'https:' + share
                        else:
                            share = self.cm.ph.getDataBeetwenMarkers(
                                data, '<div class="filmbeagyazas">',
                                '" scrolling=', False)[1]
                            share = share.replace('<iframe src="', '')
                            if 'https:' not in share:
                                share = 'https:' + share
        share = " ".join(share.split())
        printDBG(share)
        share = share.replace(' ', '')

        printDBG("Dmdamedia.getLinksForVideo url[%s]" % share)
        videoUrls = []
        uri = urlparser.decorateParamsFromUrl(share)
        protocol = uri.meta.get('iptv_proto', '')

        printDBG("PROTOCOL [%s] " % protocol)

        urlSupport = self.up.checkHostSupport(uri)
        if 1 == urlSupport:
            retTab = self.up.getVideoLinkExt(uri)
            videoUrls.extend(retTab)
        elif 0 == urlSupport and self._uriIsValid(uri):
            if protocol == 'm3u8':
                retTab = getDirectM3U8Playlist(uri,
                                               checkExt=False,
                                               checkContent=True)
                videoUrls.extend(retTab)
            elif protocol == 'f4m':
                retTab = getF4MLinksWithMeta(uri)
                videoUrls.extend(retTab)
            elif protocol == 'mpd':
                retTab = getMPDLinksWithMeta(uri, False)
                videoUrls.extend(retTab)
            else:
                videoUrls.append({'name': 'direct link', 'url': uri})
        return videoUrls
    def getVideoLinks(self, videoUrl):
        printDBG("YesMovies.getVideoLinks [%s]" % videoUrl)
        urlTab = []

        # mark requested link as used one
        if len(self.cacheLinks.keys()):
            for key in self.cacheLinks:
                for idx in range(len(self.cacheLinks[key])):
                    if videoUrl in self.cacheLinks[key][idx]['url']:
                        if not self.cacheLinks[key][idx]['name'].startswith(
                                '*'):
                            self.cacheLinks[key][idx][
                                'name'] = '*' + self.cacheLinks[key][idx][
                                    'name']
                        break

        if self.cm.isValidUrl(videoUrl):
            return self.up.getVideoLinkExt(videoUrl)

        tmp = videoUrl.split('|')
        if len(tmp) != 3:
            return []
        serverId = tmp[0]
        episodeId = tmp[1]
        referer = tmp[2]

        if referer.endswith('/'):
            referer += 'watching.html'

        sts, data = self.getPage(referer, self.defaultParams)
        if not sts:
            return []

        #rm(self.COOKIE_FILE)
        #cookie = self.cm.getCookieHeader(self.COOKIE_FILE)
        printDBG(
            '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> $$$$$$$$$$$$$$$$$$$$$$ '
            + serverId)
        if serverId in ['12', '13', '14', '15', '16']:
            url = 'ajax/movie_embed/' + episodeId
            url = self.getFullUrl(url)
            sts, data = self.getPage(url)
            if not sts:
                return []
            try:
                data = byteify(json.loads(data), '', True)
                if data['status']:
                    urlTab = self.up.getVideoLinkExt(data['src'])
            except Exception:
                printExc()
                return []
        else:
            try:
                mid = urlparse(referer).path.split('/')[2].split(
                    '-')[-1].split('.', 1)[0]
            except Exception:
                mid = ''
                printExc()
            url = self.getFullUrl('/ajax/movie_token?eid=%s&mid=%s&_=%s' %
                                  (episodeId, mid, int(time.time() * 10000)))
            if not self.cm.isValidUrl(url):
                return []

            params = dict(self.defaultParams)
            params['header'] = dict(self.HEADER)
            params['header']['Referer'] = referer

            sts, data = self.getPage(url, params)
            if not sts:
                return []

            xx = self.cm.ph.getSearchGroups(data,
                                            '''x=['"]([^'^"]+?)['"]''')[0]
            xy = self.cm.ph.getSearchGroups(data,
                                            '''y=['"]([^'^"]+?)['"]''')[0]

            url = 'ajax/movie_sources/%s?x=%s&y=%s' % (episodeId, xx, xy)
            url = self.getFullUrl(url)

            params = {}
            params['header'] = dict(self.AJAX_HEADER)
            sts, data = self.getPage(url, params)
            if not sts:
                return []

            subTracks = []
            if False:
                tmp = self.cm.ph.getAllItemsBeetwenMarkers(data,
                                                           '<jwplayer',
                                                           '>',
                                                           withMarkers=True)
                printDBG(
                    "------------------------------------------------\n%s+++++++++++++++++++++++++++++++++++++++++++++\n"
                    % tmp)
                for item in tmp:
                    url = self.cm.ph.getSearchGroups(
                        item, 'file="(http[^"]+?)"')[0].replace('&amp;', '&')
                    name = self.cm.ph.getSearchGroups(item,
                                                      'label="([^"]+?)"')[0]
                    if 'type="mp4"' in item:
                        urlTab.append({'name': name, 'url': url})
                    elif 'type="m3u8"' in item:
                        url = strwithmeta(
                            url, {
                                'Referer': referer,
                                'User-Agent': params['header']['User-Agent']
                            })
                        urlTab.extend(
                            getDirectM3U8Playlist(
                                url,
                                checkContent=True,
                                sortWithMaxBitrate=999999999))
                    elif 'kind="captions"' in item:
                        format = url[-3:]
                        if format in ['srt', 'vtt']:
                            subTracks.append({
                                'title': name,
                                'url': self.getFullIconUrl(url),
                                'lang': name,
                                'format': format
                            })
            else:
                try:
                    tmp = byteify(json.loads(data))
                    printDBG(
                        "------------------------------------------------\n%s+++++++++++++++++++++++++++++++++++++++++++++\n"
                        % tmp)
                    if isinstance(tmp['playlist'][0]['sources'], dict):
                        tmp['playlist'][0]['sources'] = [
                            tmp['playlist'][0]['sources']
                        ]
                    for item in tmp['playlist'][0]['sources']:
                        if "mp4" == item['type']:
                            urlTab.append({
                                'name':
                                str(item.get('label', 'default')),
                                'url':
                                item['file']
                            })
                        elif "m3u8" == item['type']:
                            url = strwithmeta(
                                item['file'], {
                                    'Referer': referer,
                                    'User-Agent':
                                    params['header']['User-Agent']
                                })
                            urlTab.extend(
                                getDirectM3U8Playlist(
                                    url,
                                    checkContent=True,
                                    sortWithMaxBitrate=999999999))
                    if isinstance(tmp['playlist'][0]['tracks'], dict):
                        tmp['playlist'][0]['tracks'] = [
                            tmp['playlist'][0]['tracks']
                        ]
                    for item in tmp['playlist'][0]['tracks']:
                        format = item['file'][-3:]
                        if format in ['srt', 'vtt'
                                      ] and "captions" == item['kind']:
                            subTracks.append({
                                'title':
                                str(item['label']),
                                'url':
                                self.getFullIconUrl(item['file']),
                                'lang':
                                item['label'],
                                'format':
                                format
                            })
                except Exception:
                    printExc()
            printDBG(subTracks)
            urlParams = {
                'Referer': referer,
                'User-Agent': params['header']['User-Agent']
            }
            if len(subTracks):
                urlParams.update({'external_sub_tracks': subTracks})

            for idx in range(len(urlTab)):
                urlTab[idx]['url'] = strwithmeta(urlTab[idx]['url'], urlParams)

        return urlTab
    def getDirectLinks(self,
                       url,
                       formats='flv, mp4',
                       dash=True,
                       dashSepareteList=False,
                       allowVP9=None,
                       allowAgeGate=None):
        printDBG('YouTubeParser.getDirectLinks')
        list = []
        try:
            if self.cm.isValidUrl(url) and '/channel/' in url and url.endswith(
                    '/live'):
                sts, data = self.cm.getPage(url)
                if sts:
                    videoId = self.cm.ph.getSearchGroups(
                        data,
                        '''<meta[^>]+?itemprop=['"]videoId['"][^>]+?content=['"]([^'^"]+?)['"]'''
                    )[0]
                    if videoId == '':
                        videoId = self.cm.ph.getSearchGroups(
                            data,
                            '''['"]REDIRECT_TO_VIDEO['"]\s*\,\s*['"]([^'^"]+?)['"]'''
                        )[0]
                    if videoId != '':
                        url = 'https://www.youtube.com/watch?v=' + videoId
            list = YoutubeIE()._real_extract(url,
                                             allowVP9=allowVP9,
                                             allowAgeGate=allowAgeGate)
        except Exception:
            printExc()
            if dashSepareteList:
                return [], []
            else:
                return []

        reNum = re.compile('([0-9]+)')
        retHLSList = []
        retList = []
        dashList = []
        # filter dash
        dashAudioLists = []
        dashVideoLists = []
        if dash:
            # separete audio and video links
            for item in list:
                if 'mp4a' == item['ext']:
                    dashAudioLists.append(item)
                elif item['ext'] in ('mp4v', 'webmv'):
                    dashVideoLists.append(item)
                elif 'mpd' == item['ext']:
                    tmpList = getMPDLinksWithMeta(item['url'], checkExt=False)
                    printDBG(tmpList)
                    for idx in range(len(tmpList)):
                        tmpList[idx]['format'] = "%sx%s" % (tmpList[idx].get(
                            'height', 0), tmpList[idx].get('width', 0))
                        tmpList[idx]['ext'] = "mpd"
                        tmpList[idx]['dash'] = True
                    dashList.extend(tmpList)
            # sort by quality -> format

            def _key(x):
                if x['format'].startswith('>'):
                    int(x['format'][1:-1])
                else:
                    int(ph.search(x['format'], reNum)[0])

            dashAudioLists = sorted(dashAudioLists, key=_key, reverse=True)
            dashVideoLists = sorted(dashVideoLists, key=_key, reverse=True)

        for item in list:
            printDBG(">>>>>>>>>>>>>>>>>>>>>")
            printDBG(str(item))
            printDBG("<<<<<<<<<<<<<<<<<<<<<")
            if -1 < formats.find(item['ext']):
                if 'yes' == item['m3u8']:
                    format = re.search('([0-9]+?)p$', item['format'])
                    if format != None:
                        item['format'] = format.group(1) + "x"
                        item['ext'] = item['ext'] + "_M3U8"
                        item['url'] = decorateUrl(item['url'],
                                                  {"iptv_proto": "m3u8"})
                        retHLSList.append(item)
                else:
                    format = re.search('([0-9]+?x[0-9]+?$)', item['format'])
                    if format != None:
                        item['format'] = format.group(1)
                        item['url'] = decorateUrl(item['url'])
                        retList.append(item)

        if len(dashAudioLists):
            # use best audio
            for item in dashVideoLists:
                item = dict(item)
                item["url"] = decorateUrl(
                    "merge://audio_url|video_url", {
                        'audio_url': dashAudioLists[0]['url'],
                        'video_url': item['url']
                    })
                dashList.append(item)

        # try to get hls format with alternative method
        if 0 == len(retList):
            try:
                video_id = YoutubeIE()._extract_id(url)
                url = 'http://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1' % video_id
                sts, data = self.cm.getPage(
                    url, {
                        'header': {
                            'User-agent':
                            'Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10'
                        }
                    })
                if sts:
                    data = data.replace('\\"', '"').replace('\\\\\\/', '/')
                    hlsUrl = self.cm.ph.getSearchGroups(
                        data, '''"hlsvp"\s*:\s*"(https?://[^"]+?)"''')[0]
                    hlsUrl = json_loads('"%s"' % hlsUrl)
                    if self.cm.isValidUrl(hlsUrl):
                        hlsList = getDirectM3U8Playlist(hlsUrl)
                        if len(hlsList):
                            dashList = []
                            for item in hlsList:
                                item['format'] = "%sx%s" % (item.get(
                                    'with', 0), item.get('heigth', 0))
                                item['ext'] = "m3u8"
                                item['m3u8'] = True
                                retList.append(item)
            except Exception:
                printExc()
            if 0 == len(retList):
                retList = retHLSList

            if dash:
                try:
                    sts, data = self.cm.getPage(
                        url, {
                            'header': {
                                'User-agent':
                                'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'
                            }
                        })
                    data = data.replace('\\"',
                                        '"').replace('\\\\\\/',
                                                     '/').replace('\\/', '/')
                    dashUrl = self.cm.ph.getSearchGroups(
                        data, '''"dashmpd"\s*:\s*"(https?://[^"]+?)"''')[0]
                    dashUrl = json_loads('"%s"' % dashUrl)
                    if '?' not in dashUrl:
                        dashUrl += '?mpd_version=5'
                    else:
                        dashUrl += '&mpd_version=5'
                    printDBG("DASH URL >> [%s]" % dashUrl)
                    if self.cm.isValidUrl(dashUrl):
                        dashList = getMPDLinksWithMeta(dashUrl, checkExt=False)
                        printDBG(dashList)
                        for idx in range(len(dashList)):
                            dashList[idx]['format'] = "%sx%s" % (
                                dashList[idx].get('height', 0),
                                dashList[idx].get('width', 0))
                            dashList[idx]['ext'] = "mpd"
                            dashList[idx]['dash'] = True
                except Exception:
                    printExc()

        for idx in range(len(retList)):
            if retList[idx].get('m3u8', False):
                retList[idx]['url'] = strwithmeta(
                    retList[idx]['url'], {'iptv_m3u8_live_start_index': -30})

        if dashSepareteList:
            return retList, dashList
        else:
            retList.extend(dashList)
            return retList
Exemple #35
0
    def getLinksForVideo(self, cItem):
        printDBG("ITV.getLinksForVideo [%s]" % cItem)

        retTab = []
        forwardedIP = self.getRandomGBIP()
        if cItem.get('is_live', False):
            if self.cacheLive == {}:
                sts, data = self.getPage('http://textuploader.com/dlr3q')
                if not sts: return []
                data = self.cleanHtmlStr(
                    self.cm.ph.getDataBeetwenNodes(data, ('<code', '>'),
                                                   ('</code', '>'), False)[1])
                try:
                    data = base64.b64decode(data)
                    printDBG(data)
                    self.cacheLive = byteify(json.loads(data), '', True)
                except Exception:
                    printExc()
            videoUrl = self.cacheLive.get(cItem['url'].split('/')[-1], '')
            if forwardedIP != '':
                videoUrl = strwithmeta(videoUrl,
                                       {'X-Forwarded-For': forwardedIP})
            retTab = getDirectM3U8Playlist(videoUrl, checkContent=True)
        else:
            params = dict(self.defaultParams)
            params['header'] = dict(params['header'])
            params['header']['User-Agent'] = self.MOBILE_USER_AGENT
            if forwardedIP != '':
                params['header']['X-Forwarded-For'] = forwardedIP

            sts, data = self.getPage(cItem['url'], params)
            if not sts: return []

            url = self.cm.ph.getSearchGroups(
                data, '''data\-video\-id=['"]([^'^"]+?)['"]''')[0]
            hmac = self.cm.ph.getSearchGroups(
                data, '''data\-video\-hmac=['"]([^'^"]+?)['"]''')[0]

            params['header'].update({
                'Content-Type': 'application/json',
                'Accept': 'application/vnd.itv.vod.playlist.v2+json',
                'Origin': self.getMainUrl(),
                'Referer': cItem['url'],
                'hmac': hmac
            })
            params['raw_post_data'] = True
            post_data = {
                "user": {
                    "itvUserId": "",
                    "entitlements": [],
                    "token": ""
                },
                "device": {
                    "manufacturer": "Apple",
                    "model": "iPhone",
                    "os": {
                        "name": "iPad OS",
                        "version": "9.3",
                        "type": "ios"
                    }
                },
                "client": {
                    "version": "4.1",
                    "id": "browser"
                },
                "variantAvailability": {
                    "featureset": {
                        "min": ["hls", "aes"],
                        "max": ["hls", "aes"]
                    },
                    "platformTag": "mobile"
                }
            }
            try:
                sts, data = self.getPage(url, params, json.dumps(post_data))
                if not sts: return []
                data = byteify(json.loads(data), '', True)['Playlist']['Video']
                videoUrl = data['Base'] + data['MediaFiles'][-1]['Href']
                retTab = getDirectM3U8Playlist(videoUrl, checkContent=True)
            except Exception:
                printExc()

        def __getLinkQuality(itemLink):
            try:
                return int(itemLink['bitrate'])
            except Exception:
                return 0

        retTab = CSelOneLink(retTab, __getLinkQuality,
                             99999999).getSortedLinks()
        return retTab
Exemple #36
0
    def getLinksForVideo(self, cItem):
        printDBG("Hitbox.getLinksForVideo [%s]" % cItem)
        urls = []
        if 'channel_link' in cItem:
            live = True
            urls.append({
                'name':
                'hls',
                'type':
                'hls',
                'url':
                Hitbox.MAIN_URL +
                'player/hls/%s.m3u8' % cItem['channel_link'].split('/')[-1]
            })
        elif 'media_id' in cItem:
            live = False
            sts, data = self.cm.getPage(
                Hitbox.MAIN_URL +
                'api/player/config/video/%s?redis=true&embed=false&qos=false&redis=true&showHidden=true'
                % cItem['media_id'])
            if sts:
                try:
                    data = byteify(json.loads(data))
                    baseUrl = data['clip']['baseUrl']
                    if None == baseUrl: baseUrl = ''
                    for item in data['clip']['bitrates']:
                        url = item['url']
                        if url.split('?')[0].endswith('m3u8'):
                            type = 'hls'
                        else:
                            type = 'vod'

                        if not url.startswith('http'):
                            if 'vod' == type:
                                url = baseUrl + '/' + url
                            else:
                                url = Hitbox.MAIN_URL + '/' + url

                        if url.startswith('http'):
                            urls.append({
                                'name': item.get('label', 'vod'),
                                'type': type,
                                'url': url
                            })
                            if 'vod' == type: break
                except Exception:
                    printExc()

        urlTab = []
        for urlItem in urls:
            if 'hls' == urlItem['type']:
                url = urlItem['url']
                data = getDirectM3U8Playlist(url, checkExt=False)
                if 1 == len(data):
                    urlItem['url'] = urlparser.decorateUrl(
                        urlItem['url'], {
                            'iptv_proto': 'm3u8',
                            'iptv_livestream': live
                        })
                    urlTab.append(urlItem)
                else:
                    for item in data:
                        item['url'] = urlparser.decorateUrl(
                            item['url'], {
                                'iptv_proto': 'm3u8',
                                'iptv_livestream': live
                            })
                        urlTab.append(item)
            else:
                urlTab.append(urlItem)
        return urlTab
Exemple #37
0
    def getLinksForVideo(self, cItem):
        printDBG("EuroSportPlayer.getLinksForVideo [%s]" % cItem)
        self.checkLogin()
        
        linksTab = []
        try:
            printDBG(str(cItem))
            video_id = cItem['video_id']
            # open video page
            video_page_url = cItem['url']
            sts, data = self.getPage( video_page_url, {'header' : {'User-Agent': self.USER_AGENT, 'Referer' : video_page_url}, 'use_cookie': True, 'load_cookie': True, 'save_cookie': True, 'cookiefile': self.COOKIE_FILE })
            
            if not sts:
                return []
            
            # open route json page
            route_id = cItem.get('route_id','')
            if route_id:
                route = self.espRoutes[route_id]
                printDBG(json_dumps(route))

                #{"attributes": {"url": "/videos/eurosport/world-championship-239400", "canonical": true}, "type": "route", "id": "292e72a63ebcccb480984a84f3497b7702623ab6fe6e7d7d29b1dce79ed3da35"}
                route_url = self.getFullPath(route['attributes']['url'],'route') + "?include=default"
                
                sts, data = self.getPage(route_url)
                
                #if sts:
                    #printDBG('--------------------------------')
                    #printDBG(data)
                
            
            # open video playback json page
            playback_info_url = self.PLAYBACK_URL.replace('{%video_id%}', video_id)
            
            sts, data = self.getPage(playback_info_url, {'header' : {'User-Agent': self.USER_AGENT, 'Referer' : video_page_url}, 'use_cookie': True, 'load_cookie': True, 'save_cookie': True, 'cookiefile': self.COOKIE_FILE })
            
            if not sts:
                return []
            
            printDBG('--------------------------------')
            printDBG(data)
            
            j = json_loads(data)
            
            s = j['data']['attributes']['streaming']
            
            if 'hls' in s:
                link_url = strwithmeta(s['hls']['url'], {'User-Agent': self.USER_AGENT, 'Referer' : video_page_url})
                linksTab.append({'name':'auto hls', 'url': link_url})
                linksTab.extend(getDirectM3U8Playlist(link_url, checkExt=False, variantCheck=True, checkContent=True, sortWithMaxBitrate=99999999)) 
            #if 'dash' in s:
            #    link_url = strwithmeta(s['dash']['url'], {'User-Agent': self.USER_AGENT, 'Referer' : video_page_url})
            #    linksTab.append({'name':'dash', 'url': link_url})
            #if 'mss' in s:
            #    link_url = strwithmeta(s['dash']['url'], {'User-Agent': self.USER_AGENT, 'Referer' : video_page_url})
            #    linksTab.append({'name':'mss', 'url': link_url})
           
        except Exception:
            printExc()
        
        return linksTab
    def getTeamCastLink(self, url):
        printDBG("getTeamCastLink url[%s]" % url)
        url = 'http://team-cast.pl.cp-21.webhostbox.net/' + url
        sts, data = self.cm.getPage(url)
        if not sts: return []
        url = self.cm.ph.getSearchGroups(
            data,
            """src=['"](http://team-cast.pl.cp-21.webhostbox.net[/]+?kanalyFlash/[^'^"]+?)['"]"""
        )[0]

        sts, data = self.cm.getPage(url)
        if sts:
            O1I = self.cm.ph.getSearchGroups(data, "='([^']+?)'")[0]
            if '' != O1I:
                try:
                    data2 = data
                    printDBG('-------------------------------------------')
                    printDBG('getTeamCastLink javascript pack detected')
                    printDBG('-------------------------------------------')
                    data = MYOBFUSCATECOM_OIO(MYOBFUSCATECOM_0ll(O1I))
                    data = data.strip()
                    data = data[data.find('}(') + 2:-2]
                    data = unpackJS(data, TEAMCASTPL_decryptPlayerParams)
                    data = data[data.find('}(') + 2:-2]
                    data = unpackJS(data, SAWLIVETV_decryptPlayerParams)
                    data = data[data.find('}(') + 2:-2]
                    data = unpackJS(data, TEAMCASTPL_decryptPlayerParams)
                    data = self.cm.ph.getSearchGroups(data,
                                                      "_escape='([^']+?)'")[0]
                    data = data.replace(
                        '%', '\\u00').decode('unicode-escape').encode("utf-8")
                    #printDBG("=======================================================================")
                    #printDBG(data)
                    #printDBG("=======================================================================")
                except:
                    printExc()
                    data = data2
                data2 = ''

            if "goodcast.co" in data:
                id = self.cm.ph.getSearchGroups(data, "id='([0-9]+?)';")[0]
                if '' != id:
                    videoUrl = 'http://goodcast.co/stream.php?id=' + id + '&width=640&height=480'
                    videoUrl = strwithmeta(videoUrl, {'Referer': url})
                    return self.up.getVideoLinkExt(videoUrl)
            elif "yukons.net" in data:
                channel = CParsingHelper.getDataBeetwenMarkers(
                    data, 'channel="', '"', False)[1]
                videoUrl = strwithmeta('http://yukons.net/watch/' + channel,
                                       {'Referer': url})
                return self.up.getVideoLinkExt(videoUrl)
            elif "privatestream.tv" in data:
                videoUrl = self.cm.ph.getSearchGroups(
                    data, '"(http://privatestream.tv/[^"]+?)"')[0]
                videoUrl = strwithmeta(videoUrl, {'Referer': url})
                return self.up.getVideoLinkExt(videoUrl)
            elif "ustream.tv" in data:
                videoUrl = self.cm.ph.getSearchGroups(
                    data, 'src="([^"]+?ustream.tv[^"]+?)"')[0]
                if videoUrl.startswith('//'):
                    videoUrl = 'http:' + videoUrl
                    videoUrl = strwithmeta(videoUrl, {'Referer': url})
                    return self.up.getVideoLinkExt(videoUrl)
            elif 'rtmp://' in data:
                tmp = self.cm.ph.getSearchGroups(
                    data, """(rtmp://[^'^"]+?)['"]""")[0]
                tmp = tmp.split('&amp;')
                r = tmp[0]
                if 1 < len(tmp) and tmp[1].startswith('c='):
                    playpath = tmp[1][2:]
                else:
                    playpath = self.cm.ph.getSearchGroups(
                        data,
                        """['"]*url['"]*[ ]*?:[ ]*?['"]([^'^"]+?)['"]""")[0]
                if '' != playpath:
                    r += ' playpath=%s' % playpath.strip()
                swfUrl = self.cm.ph.getSearchGroups(
                    data, """['"](http[^'^"]+?swf)['"]""")[0]
                r += ' swfUrl=%s pageUrl=%s' % (swfUrl, url)
                return [{'name': 'team-cast', 'url': r}]
            elif 'abcast.biz' in data:
                file = self.cm.ph.getSearchGroups(data, "file='([^']+?)'")[0]
                if '' != file:
                    videoUrl = 'http://abcast.biz/embed.php?file=' + file + '&width=640&height=480'
                    videoUrl = strwithmeta(videoUrl, {'Referer': url})
                    return self.up.getVideoLinkExt(videoUrl)
            elif 'shidurlive.com' in data:
                videoUrl = self.cm.ph.getSearchGroups(
                    data,
                    """src=['"](http[^'^"]+?shidurlive.com[^'^"]+?)['"]""")[0]
                if '' != videoUrl:
                    videoUrl = strwithmeta(videoUrl, {'Referer': url})
                    return self.up.getVideoLinkExt(videoUrl)
            elif 'sawlive.tv' in data:
                videoUrl = self.cm.ph.getSearchGroups(
                    data,
                    """src=['"](http[^'^"]+?sawlive.tv[^'^"]+?)['"]""")[0]
                if '' != videoUrl:
                    videoUrl = strwithmeta(videoUrl, {'Referer': url})
                    return self.up.getVideoLinkExt(videoUrl)
            elif "castalba.tv" in data:
                id = self.cm.ph.getSearchGroups(data,
                                                """id=['"]([0-9]+?)['"];""")[0]
                if '' != id:
                    videoUrl = 'http://castalba.tv/embed.php?cid=' + id + '&wh=640&ht=400&r=team-cast.pl.cp-21.webhostbox.net'
                    videoUrl = strwithmeta(videoUrl, {'Referer': url})
                    return self.up.getVideoLinkExt(videoUrl)
            elif "fxstream.biz" in data:
                file = self.cm.ph.getSearchGroups(
                    data, """file=['"]([^'^"]+?)['"];""")[0]
                if '' != file:
                    videoUrl = 'http://fxstream.biz/embed.php?file=' + file + '&width=640&height=400'
                    videoUrl = strwithmeta(videoUrl, {'Referer': url})
                    return self.up.getVideoLinkExt(videoUrl)
            else:
                file = self.cm.ph.getSearchGroups(
                    data, """['"]([^'^"]+?\.m3u8)['"]""")[0]
                if '' != file:
                    return getDirectM3U8Playlist(file, checkExt=False)
                printDBG(
                    "======================================================================="
                )
                printDBG(data)
                printDBG(
                    "======================================================================="
                )
        return []
Exemple #39
0
 def getTvpStreamLink(self, data):
     printDBG(data)
     file = self.cm.ph.getSearchGroups(
         data, '''['"](https?[^'^"]+?\.m3u8[^'^"]*?)['"]''')[0]
     return getDirectM3U8Playlist(file)
    def getLinksForVideo(self, Index=0, selItem=None):
        listLen = len(self.host.currList)
        if listLen < Index and listLen > 0:
            printDBG(
                "ERROR getLinksForVideo - current list is to short len: %d, Index: %d"
                % (listLen, Index))
            return RetHost(RetHost.ERROR, value=[])

        if self.host.currList[Index]["type"] != 'video':
            printDBG("ERROR getLinksForVideo - current item has wrong type")
            return RetHost(RetHost.ERROR, value=[])

        retlist = []
        url = self.host.currList[Index].get("url", '')
        name = self.host.currList[Index].get("name", '')

        printDBG(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> [%s] [%s]" %
                 (name, url))
        urlList = None

        if -1 != url.find('teledunet'):
            new_url = TeledunetParser().get_rtmp_params(url)
            if 0 < len(url): retlist.append(CUrlItem("Własny link", new_url))
        elif url.startswith('http://goldvod.tv/'):
            url = self.host.getGoldvodLink(url)
        elif 'web-live.tv' in url:
            url = self.host.getSatLiveLink(url)
        elif 'vidtv.pl' in url:
            url = self.host.getVidTvLink(url)
        elif 'looknij.tv' in url:
            url = self.host.getLooknijTvLink(url)
        elif 'tvisport.cba.pl' in url:
            urlList = self.host.getTvSportCdaLink(url)
        elif 'nettv.pw' in url:
            urlList = self.host.getNettvpwLink(url)
        elif 'weeb.tv' in name:
            url = self.host.getWeebTvLink(url)
        elif name == "team-cast.pl":
            urlList = self.host.getTeamCastLink(url)
        elif "filmon_channel" == name:
            urlList = self.host.getFilmOnLink(channelID=url)
        elif "videostar_channels" == name:
            urlList = self.host.getVideostarLink(channelID=url)
            #if 1 < len(tmpList):
            #    for item in tmpList:
            #        retlist.append(CUrlItem(item['name'], item['url']))
            #elif 1 == len(tmpList):
            #    url =  tmpList[0]['url']
        elif name == "webcamera.pl":
            urlList = self.host.getWebCameraLink(url)
        elif name == "prognoza.pogody.tv":
            urlList = self.host.prognozaPogodyLink(url)

        if isinstance(urlList, list):
            for item in urlList:
                retlist.append(CUrlItem(item['name'], item['url']))
        elif isinstance(url, basestring):
            if url.endswith('.m3u'):
                tmpList = self.host.getDirectVideoHasBahCa(name, url)
                for item in tmpList:
                    retlist.append(CUrlItem(item['name'], item['url']))
            else:
                iptv_proto = urlparser.decorateUrl(url).meta.get(
                    'iptv_proto', '')
                if 'm3u8' == iptv_proto:
                    tmpList = getDirectM3U8Playlist(url, checkExt=False)
                    for item in tmpList:
                        retlist.append(CUrlItem(item['name'], item['url']))
                elif 'f4m' == iptv_proto:
                    tmpList = getF4MLinksWithMeta(url, checkExt=False)
                    for item in tmpList:
                        retlist.append(CUrlItem(item['name'], item['url']))
                else:
                    if '://' in url:
                        retlist.append(CUrlItem("Link", url))

        return RetHost(RetHost.OK, value=retlist)
Exemple #41
0
    def getLinksForVideo(self, cItem):
        printDBG("Tata.getLinksForVideo [%s]" % cItem)
        linksTab = []

        sts, data = self.getPage(cItem['url'])
        if not sts: return []

        tmp = self.cm.ph.getSearchGroups(data,
                                         '''(<a[^>]+?show-trailer[^>]+>)''')[0]
        trailerUrl = self.cm.ph.getSearchGroups(
            tmp, '''href=['"](https?://[^'^"]+)['"]''')[0]

        data = self.cm.ph.getDataBeetwenMarkers(data, 'class="video-embed',
                                                '</div>')[1]
        videoUrl = self.cm.ph.getSearchGroups(
            data, '''data-src=['"](https?://[^'^"]+)['"]''')[0].strip()
        if '' == videoUrl:
            try:
                getParams = dict(self.defaultParams)
                getParams['header'] = dict(getParams['header'])
                getParams['header']['Referer'] = cItem['url']

                url = self.cm.ph.getSearchGroups(
                    data, '''data-url=['"](https?://[^'^"]+)['"]''')[0]
                sts, data = self.getPage(url, getParams)
                if not sts: return []
                printDBG("+++++++++++++++++++++++++++++++++++++++")
                printDBG(data)
                printDBG("+++++++++++++++++++++++++++++++++++++++")

                data = base64.b64decode(data)
                data = byteify(json.loads(data))
                videoUrl = data['playinfo'].replace('\\/', '/').strip()
            except Exception:
                printExc()

        if self.cm.isValidUrl(videoUrl):
            #videoUrl = videoUrl.replace('://s6.', '://s4.')
            getParams = dict(self.defaultParams)
            getParams['header'] = dict(getParams['header'])
            getParams['header']['Referer'] = cItem['url']

            sts, data = self.getPage(videoUrl, getParams)
            if not sts: return []

            printDBG("+++++++++++++++++++++++++++++++++++++++")
            printDBG(data)
            printDBG("+++++++++++++++++++++++++++++++++++++++")
            try:
                data = base64.b64decode(data)
                data = byteify(json.loads(data))
                videoUrl = data['playinfo'].replace('\\/', '/').strip()

                sts, data = self.getPage(videoUrl, getParams)
                if not sts: return []

                printDBG("+++++++++++++++++++++++++++++++++++++++")
                printDBG(data)
                printDBG("+++++++++++++++++++++++++++++++++++++++")
            except Exception:
                printExc()

            hlsUrl = videoUrl.replace('/embed.html', '/index.m3u8')
            hlsUrl = strwithmeta(hlsUrl, {
                'Referer': videoUrl,
                'User-Agent': self.USER_AGENT
            })

            linksTab = getDirectM3U8Playlist(hlsUrl, checkContent=True)
            #for idx in range(len(linksTab)):
            #    if linksTab[idx]['url'].startswith('https:'):
            #        linksTab[idx]['url'] = strwithmeta('http' + linksTab[idx]['url'][5:], linksTab[idx]['url'].meta)

        if len(linksTab) and self.cm.isValidUrl(trailerUrl):
            linksTab.append({
                'name': 'Trailer',
                'url': trailerUrl,
                'need_resolve': 1
            })

        return linksTab
Exemple #42
0
    def getLinksForVideo(self, cItem):
        printDBG("ZDFmediathek.getLinksForVideo [%s]" % cItem)

        if 'id' not in cItem and 'url' in cItem:
            sts, data = self.getPage(cItem['url'])
            if not sts: return []
            id = self.cm.ph.getSearchGroups(
                data, '''['"]?docId['"]?\s*:\s*['"]([^'^"]+?)['"]''')[0]
        else:
            id = cItem['id']

        sts, data = self.getPage(self.DOCUMENT_API_URL % id)
        if not sts: return []

        preferedQuality = int(
            config.plugins.iptvplayer.zdfmediathek_prefquality.value)
        preferedFormat = config.plugins.iptvplayer.zdfmediathek_prefformat.value
        tmp = preferedFormat.split(',')
        formatMap = {}
        for i in range(len(tmp)):
            formatMap[tmp[i]] = i

        try:
            subTracks = []
            urlTab = []
            tmpUrlTab = []
            data = json_loads(data)['document']
            try:
                for item in data['captions']:
                    if 'vtt' in item['format'] and self.cm.isValidUrl(
                            item['uri']):
                        subTracks.append({
                            'title': item['language'],
                            'url': item['uri'],
                            'lang': item['language'],
                            'format': 'vtt'
                        })
            except Exception:
                printExc()

            live = data['type']
            try:
                data = data['formitaeten']
                for item in data:
                    quality = item['quality']
                    url = item['url']
                    if url.startswith('https://'):
                        url = 'http' + url[5:]
                    for type in [{
                            'pattern': 'http_m3u8_http',
                            'name': 'm3u8'
                    }, {
                            'pattern': 'mp4_http',
                            'name': 'mp4'
                    }]:
                        if type['pattern'] not in item['type']: continue
                        if type['name'] == 'mp4':
                            if item['hd']:
                                quality = 'hd'
                            qualityVal = ZDFmediathek.QUALITY_MAP.get(
                                quality, 10)
                            qualityPref = abs(qualityVal - preferedQuality)
                            formatPref = formatMap.get(type['name'], 10)
                            tmpUrlTab.append({
                                'url': url,
                                'quality_name': quality,
                                'quality': qualityVal,
                                'quality_pref': qualityPref,
                                'format_name': type['name'],
                                'format_pref': formatPref
                            })
                        elif type['name'] == 'm3u8':
                            tmpList = getDirectM3U8Playlist(url,
                                                            checkExt=False)
                            for tmpItem in tmpList:
                                res = tmpItem['with']
                                if res == 0: continue
                                if res > 300: quality = 'low'
                                if res > 600: quality = 'med'
                                if res > 800: quality = 'high'
                                if res > 1000: quality = 'veryhigh'
                                if res > 1200: quality = 'hd'
                                qualityVal = ZDFmediathek.QUALITY_MAP.get(
                                    quality, 10)
                                qualityPref = abs(qualityVal - preferedQuality)
                                formatPref = formatMap.get(type['name'], 10)
                                tmpUrlTab.append({
                                    'url': tmpItem['url'],
                                    'quality_name': quality,
                                    'quality': qualityVal,
                                    'quality_pref': qualityPref,
                                    'format_name': type['name'],
                                    'format_pref': formatPref
                                })
            except Exception:
                printExc()

            def _cmpLinks(it1, it2):
                prefmoreimportantly = config.plugins.iptvplayer.zdfmediathek_prefmoreimportant.value
                if 'quality' == prefmoreimportantly:
                    if it1['quality_pref'] < it2['quality_pref']: return -1
                    elif it1['quality_pref'] > it2['quality_pref']: return 1
                    else:
                        if it1['quality'] < it2['quality']: return -1
                        elif it1['quality'] > it2['quality']: return 1
                        else:
                            if it1['format_pref'] < it2['format_pref']:
                                return -1
                            elif it1['format_pref'] > it2['format_pref']:
                                return 1
                            else:
                                return 0
                else:
                    if it1['format_pref'] < it2['format_pref']: return -1
                    elif it1['format_pref'] > it2['format_pref']: return 1
                    else:
                        if it1['quality_pref'] < it2['quality_pref']: return -1
                        elif it1['quality_pref'] > it2['quality_pref']:
                            return 1
                        else:
                            if it1['quality'] < it2['quality']: return -1
                            elif it1['quality'] > it2['quality']: return 1
                            else: return 0

            tmpUrlTab.sort(_cmpLinks)
            onelinkmode = config.plugins.iptvplayer.zdfmediathek_onelinkmode.value
            for item in tmpUrlTab:
                url = item['url']
                name = item['quality_name'] + ' ' + item['format_name']
                if '' != url:
                    if 'live' in str(live):
                        live = True
                    else:
                        live = False
                    urlTab.append({
                        'need_resolve':
                        0,
                        'name':
                        name,
                        'url':
                        self.up.decorateUrl(
                            url, {
                                'iptv_livestream': live,
                                'external_sub_tracks': subTracks
                            })
                    })
                    if onelinkmode: break
            printDBG(tmpUrlTab)
        except Exception:
            printExc()

        return urlTab
Exemple #43
0
    def getLinksForVideo(self, cItem):
        printDBG("ArconaitvME.getLinksForVideo [%s]" % cItem)
        urlsTab = []
        sts, data = self.getPage(cItem['url'])
        if not sts: return urlsTab

        playerUrl = self.cm.ph.getSearchGroups(
            data,
            '''<source[^>]*?src=['"](https?:[^"^']+?\.m3u8[^"^']*?)['"]''',
            1,
            ignoreCase=True)[0]
        try:
            playerUrl = byteify(json.loads('"%s"' % playerUrl))
        except Exception:
            printExc()
        if not self.cm.isValidUrl(playerUrl):
            playerUrl = self.cm.ph.getSearchGroups(
                data,
                '''"sources"\s*:\s*[^\]]*?"src"\s*:\s*"(https?:[^"]+?\.m3u8[^"]*?)"''',
                1,
                ignoreCase=True)[0]
        try:
            playerUrl = byteify(json.loads('"%s"' % playerUrl))
        except Exception:
            printExc()
        if not self.cm.isValidUrl(playerUrl):
            playerUrl = self.cm.ph.getSearchGroups(
                data, '''"(https?:[^"]+?\.m3u8[^"]*?)"''', 1,
                ignoreCase=True)[0]
        try:
            playerUrl = byteify(json.loads('"%s"' % playerUrl))
        except Exception:
            printExc()

        if not self.cm.isValidUrl(playerUrl):
            scripts = []
            tmp = self.cm.ph.getAllItemsBeetwenNodes(data, ('<script', '>'),
                                                     ('</script', '>'), False)
            for item in tmp:
                if 'eval(' not in item and '゚ω゚ノ=' not in item: continue
                scripts.append(item.strip())
            try:
                jscode = base64.b64decode(
                    '''dmFyIGRvY3VtZW50PXt9LHdpbmRvdz10aGlzLGVsZW1lbnQ9ZnVuY3Rpb24oZSl7dGhpcy5fbmFtZT1lLHRoaXMuc2V0QXR0cmlidXRlPWZ1bmN0aW9uKGUsdCl7InNyYyI9PWUmJih0aGlzLnNyYz10KX0sT2JqZWN0LmRlZmluZVByb3BlcnR5KHRoaXMsInNyYyIse2dldDpmdW5jdGlvbigpe3JldHVybiB0aGlzLl9zcmN9LHNldDpmdW5jdGlvbihlKXt0aGlzLl9zcmM9ZSxwcmludChlKX19KX0sJD1mdW5jdGlvbihlKXtyZXR1cm4gbmV3IGVsZW1lbnQoZSl9O2RvY3VtZW50LmdldEVsZW1lbnRCeUlkPWZ1bmN0aW9uKGUpe3JldHVybiBuZXcgZWxlbWVudChlKX0sZG9jdW1lbnQuZ2V0RWxlbWVudHNCeVRhZ05hbWU9ZnVuY3Rpb24oZSl7cmV0dXJuW25ldyBlbGVtZW50KGUpXX07'''
                )
                ret = iptv_js_execute(jscode + '\n'.join(scripts))
                if ret['sts'] and 0 == ret['code']:
                    decoded = ret['data'].strip()
                    if decoded.split('?', 1)[0].endswith('.m3u8'):
                        playerUrl = decoded
            except Exception:
                printExc()
        playerUrl = strwithmeta(
            playerUrl, {
                'User-Agent': self.HEADER['User-Agent'],
                'Referer': cItem['url'],
                'Origin': self.getMainUrl()
            })

        if self.cm.isValidUrl(playerUrl):
            tmp = getDirectM3U8Playlist(playerUrl, checkContent=True)
            for item in tmp:
                item['need_resolve'] = 0
                urlsTab.append(item)
        return urlsTab
Exemple #44
0
    def getLinksForVideo(self, cItem):
        printDBG("WRealu24TV.getLinksForVideo [%s]" % cItem)
        retTab = []
        hlsTab = []

        sts, data = self.getPage(cItem['url'])
        if not sts: return

        data = re.sub("<!--[\s\S]*?-->", "", data)
        cookieHeader = self.cm.getCookieHeader(self.COOKIE_FILE)

        data = self.cm.ph.getDataBeetwenMarkers(data, '<video', '</video>')[1]
        if 'document.write(' in data:
            jscode = [
                'var document = {};document.write=function(txt){print(txt);}'
            ]
            tmp = self.cm.ph.getAllItemsBeetwenNodes(data, ('<script', '>'),
                                                     ('</script', '>'), False)
            for item in tmp:
                jscode.append(item)
            jscode = '\n'.join(jscode)
            ret = js_execute(jscode)
            if ret['sts'] and 0 == ret['code']:
                data = ret['data'].strip()

        data = self.cm.ph.getAllItemsBeetwenMarkers(data, '<source', '>')
        printDBG(data)
        for item in data:
            url = self.getFullUrl(
                self.cm.ph.getSearchGroups(item,
                                           '''src=['"]([^'^"]+?)['"]''')[0])
            if not self.cm.isValidUrl(url): continue
            type = self.cm.ph.getSearchGroups(
                item, '''type=['"]([^'^"]+?)['"]''')[0].lower()
            label = self.cm.ph.getSearchGroups(
                item, '''label=['"]([^'^"]+?)['"]''')[0]
            res = self.cm.ph.getSearchGroups(item,
                                             '''res=['"]([^'^"]+?)['"]''')[0]
            if label == '': label = res

            if 'mp4' in type:
                url = self.up.decorateUrl(
                    url, {
                        'Cookie': cookieHeader,
                        'User-Agent': self.USER_AGENT,
                        'Referer': cItem['url']
                    })
                retTab.append({
                    'name': label,
                    'url': url,
                    'res': res,
                    'need_resolve': 0
                })
            elif 'mpegurl' in type:
                url = self.up.decorateUrl(
                    url, {
                        'iptv_proto': 'm3u8',
                        'Origin': self.up.getDomain(cItem['url'], False),
                        'Cookie': cookieHeader,
                        'User-Agent': self.USER_AGENT,
                        'Referer': cItem['url']
                    })
                hlsTab.extend(
                    getDirectM3U8Playlist(url,
                                          checkContent=True,
                                          sortWithMaxBitrate=999999999))
            else:
                printDBG("Unknown source: [%s]" % item)

        if 1 < len(retTab):

            def __getLinkQuality(itemLink):
                try:
                    return int(itemLink['res'])
                except Exception:
                    return 0

            oneLink = CSelOneLink(retTab, __getLinkQuality, 999999999)
            retTab = oneLink.getSortedLinks()

        retTab.extend(hlsTab)
        return retTab
    def getVideoLink(self, cItem):
        printDBG("CanlitvliveIoApi.getVideoLink")
        urlsTab = []

        sts, baseData = self.cm.getPage(cItem['url'], self.defaultParams)
        if not sts:
            return urlsTab

        if '/tele1.' in cItem['url']:
            data = ph.findall(baseData, '<iframe', '>', flags=ph.I)
            for item in data:
                printDBG(">>>>>>>>>>>>>>>>>>> " + item)
                url = self.cm.getFullUrl(ph.getattr(item, 'src'),
                                         self.cm.meta['url'])
                if 1 == self.up.checkHostSupport(url):
                    urlsTab = self.up.getVideoLinkExt(
                        strwithmeta(url, {'Referer': self.cm.meta['url']}))
                    if urlsTab:
                        return urlsTab

        hlsUrl = ph.search(
            baseData,
            '''["'](https?://[^'^"]+?\.m3u8(?:\?[^"^']+?)?)["']''',
            flags=ph.I)[0]
        printDBG("hlsUrl||||||||||||||||| " + hlsUrl)
        if hlsUrl:
            hlsUrl = strwithmeta(
                hlsUrl, {
                    'User-Agent': self.defaultParams['header']['User-Agent'],
                    'Referer': cItem['url']
                })
            urlsTab = getDirectM3U8Playlist(hlsUrl,
                                            checkContent=True,
                                            sortWithMaxBitrate=999999999)

        if 0 == len(urlsTab):
            data = ph.find(baseData, '.setup(', ')')[1]
            videoUrl = ph.search(
                data,
                '''['"]?file['"]?\s*:\s*['"](https?://[^'^"]+?)['"]''')[0]
            if self.cm.isValidUrl(videoUrl):
                videoUrl = strwithmeta(
                    videoUrl, {
                        'User-Agent':
                        self.defaultParams['header']['User-Agent'],
                        'Referer': cItem['url']
                    })
                urlsTab.append({'name': 'direct', 'url': videoUrl})

        if 0 == len(urlsTab):
            videoUrl = ph.search(
                baseData,
                '''['"]?streamurl['"]?\s*:\s*['"](https?://[^'^"]+?)['"]''',
                flags=ph.I)[0]
            if self.cm.isValidUrl(videoUrl):
                videoUrl = strwithmeta(
                    videoUrl, {
                        'User-Agent':
                        self.defaultParams['header']['User-Agent'],
                        'Referer': cItem['url']
                    })
                urlsTab.append({'name': 'direct', 'url': videoUrl})
        return urlsTab
Exemple #46
0
 def getLinksForVideo(self, cItem):
     printDBG("KijkNL.getLinksForVideo [%s]" % cItem)
     
     retTab = []
     videoUrl = ''
     embedVideoUrl = ''
     try:
         url = self.tmpUrl + 'v1/default/entitlement/' + cItem['f_id']
         
         sts, data = self.getPage(url)
         if not sts: return
         
         data = byteify(json.loads(data), '', True)
         if data['playerInfo']['hasDRM']: SetIPTVPlayerLastHostError(_('DRM protection detected.'))
         embedVideoUrl = self.getFullUrl(data['playerInfo'].get('embed_video_url', ''))
         url = data['playerInfo']['embed_api_url']
         if self.cm.isValidUrl(url):
             sts, data = self.getPage(url)
             if not sts: return
             data = byteify(json.loads(data), '', True)
             videoUrl = data['playlist']
             retTab = getDirectM3U8Playlist(videoUrl, checkContent=True)
         else:
             SetIPTVPlayerLastHostError(_('No valid entitlement found for asset.'))
     except Exception:
         SetIPTVPlayerLastHostError(_('Entitlement parsing error.'))
         printExc()
     
     printDBG(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> embedVideoUrl[%s]" % embedVideoUrl)
     if self.cm.isValidUrl(embedVideoUrl) and 0 == len(retTab):
         sts, data = self.getPage(embedVideoUrl)
         try:
             vidData = self.cm.ph.getDataBeetwenMarkers(data, '<video', '>')[1]
             account = self.cm.ph.getSearchGroups(vidData, '''data\-account=['"]([^'^"]+?)['"]''')[0]
             video   = self.cm.ph.getSearchGroups(vidData, '''data\-video\-id=['"]([^'^"]+?)['"]''')[0]
             
             if self.policyKeyCache == '':
                 data = re.compile('''<script[^>]+?src=['"]([^'^"]+?)['"]''').findall(data)
                 for item in data:
                     url = self.getFullUrl(item)
                     if not self.cm.isValidUrl(url): continue
                     sts, script = self.getPage(url)
                     if sts: self.policyKeyCache = self.cm.ph.getSearchGroups(script, '''policyKey\s*:\s*['"]([^'^"]+?)['"]''')[0]
                     if self.policyKeyCache != '': break
             
             urlParams = dict(self.defaultParams)
             urlParams['header'] = dict(urlParams['header'])
             urlParams['header']['Accept'] = "application/json;pk=" + self.policyKeyCache
             url = 'https://edge.api.brightcove.com/playback/v1/accounts/%s/videos/%s' % (account, video)
             sts, data = self.getPage(url, urlParams)
             if not sts: return
             data = byteify(json.loads(data), '', True)
             for item in data['sources']:
                 videoUrl = item.get('src', '')
                 if not self.cm.isValidUrl(videoUrl): continue
                 retTab = getDirectM3U8Playlist(videoUrl, checkContent=True)
                 if len(retTab): break
         except Exception:
             SetIPTVPlayerLastHostError(_('Player data parsing error.'))
             printExc()
     
     def __getLinkQuality( itemLink ):
         try: return int(itemLink['bitrate'])
         except Exception: return 0
     
     retTab = CSelOneLink(retTab, __getLinkQuality, 99999999).getSortedLinks()
     
     return retTab
Exemple #47
0
 def getVideoLinks(self, videoUrl):
     printDBG("getVideoLinks [%s]" % videoUrl)
     urlTab = []
     if videoUrl.startswith('hst'):
         _data = re.findall('hst#(.*?)#(.*?)#', videoUrl + '#', re.S)
         hst = _data[0][0]
         videoUrl = _data[0][1]
     else:
         hst = 'none'
     if hst == 'none':
         urlTab = self.TSgetVideoLinkExt(videoUrl)
     elif hst == 'host':
         import_str, videoUrl = videoUrl.split('||')
         exec(import_str + 'getVideos')
         urlTab1 = getVideos(videoUrl)
         for (url_, type_) in urlTab1:
             if type_ == '1':
                 urlTab = self.TSgetVideoLinkExt(url_)
             else:
                 urlTab.append({'name': 'Direct', 'url': url_})
     elif hst == 'tshost':
         urlTab1 = self.host_.getVideos(videoUrl)
         urlTab = []
         for (url_, type_) in urlTab1:
             if type_ == '1':
                 printDBG('type=1')
                 urlTab = self.TSgetVideoLinkExt(url_)
             elif type_ == '3':
                 urlTab = getDirectM3U8Playlist(
                     url_,
                     False,
                     checkContent=True,
                     sortWithMaxBitrate=999999999)
             elif type_ == '0':
                 urlTab.append({'name': 'Direct', 'url': url_})
             elif type_ == '4':
                 meta = ''
                 try:
                     meta = url_.meta
                 except:
                     pass
                 if meta != '':
                     urlTab.append({
                         'name':
                         url_.split('|')[0],
                         'url':
                         strwithmeta(url_.split('|')[1], meta)
                     })
                 else:
                     urlTab.append({
                         'name': url_.split('|')[0],
                         'url': url_.split('|')[1]
                     })
             elif type_ == '5':
                 name = url_.split('|')[0]
                 URL = url_.split('|')[1]
                 urltabout = self.TSgetVideoLinkExt(URL)
                 if urltabout != []:
                     for elm in urltabout:
                         elm['name'] = name + ' [' + elm['name'] + ']'
                         urlTab.append(elm)
             elif type_ == '6':
                 vtt, lng, URL = url_.split('|', 2)
                 subTrack = [{
                     'title': lng,
                     'url': vtt,
                     'lang': lng,
                     'format': 'vtt'
                 }]
                 URL = strwithmeta(URL, {'external_sub_tracks': subTrack})
                 urlTab = getDirectM3U8Playlist(
                     URL,
                     False,
                     checkContent=True,
                     sortWithMaxBitrate=999999999)
                 print
             else:
                 urlTab.append({'name': 'Direct', 'url': url_})
     else:
         exec('urlTab = self.' + hst + '_videos(videoUrl)')
     return urlTab
Exemple #48
0
    def getLinksForVideo(self, cItem):
        printDBG("TVRepublkaPL.getLinksForVideo [%s]" % cItem)
        urlTab = []

        sts, data = self.getPage(cItem['url'])
        if not sts: return

        tmp = self.cm.ph.getDataBeetwenNodes(data, ('<div', '>', 'video-play'),
                                             ('<script', '>'), False)[1]
        tmp = self.cm.ph.getDataBeetwenMarkers(tmp, '<video', '</video>',
                                               False)[1]
        tmp = self.cm.ph.getAllItemsBeetwenMarkers(tmp, '<source', '>')
        if len(tmp):
            for item in tmp:
                type = self.cm.ph.getSearchGroups(
                    item, '''type=['"]([^'^"]+?)['"]''')[0].lower()
                name = self.cm.ph.getSearchGroups(
                    item, '''label=['"]([^'^"]+?)['"]''')[0]
                url = self.cm.ph.getSearchGroups(
                    item, '''src=['"]([^'^"]+?)['"]''')[0]
                if name == '': name = '%s. %s' % (str(len(urlTab) + 1), type)

                if 'video/mp4' == type:
                    urlTab.append({
                        'name': name,
                        'url': self.getFullUrl(url),
                        'need_resolve': 0
                    })
                elif 'application/x-mpegurl' == type:
                    urlTab.extend(
                        getDirectM3U8Playlist(url,
                                              checkExt=False,
                                              checkContent=True,
                                              sortWithMaxBitrate=999999999))
        if 0 == len(urlTab):
            tmp = self.cm.ph.getAllItemsBeetwenNodes(data,
                                                     ('<div', '>', 'video-id'),
                                                     ('</div', '>'))
            for item in tmp:
                videoId = self.cm.ph.getSearchGroups(
                    item, '''\sdata\-video\-id=['"]([^'^"]+?)['"]''')[0]
                dataType = self.cm.ph.getSearchGroups(
                    item, '''\sdata\-type=['"]([^'^"]+?)['"]''')[0].lower()
                if dataType in 'youtube':
                    urlTab.append({
                        'name': dataType,
                        'url': 'https://www.youtube.com/watch?v=' + videoId,
                        'need_resolve': 1
                    })
                else:
                    printDBG("Unknown url type [%s] id[%s]" %
                             (dataType, videoId))
        if 0 == len(urlTab):
            tmp = self.cm.ph.getAllItemsBeetwenNodes(
                data, ('<iframe', '>', 'player'), ('</div', '>'))
            for item in tmp:
                url = self.getFullUrl(
                    self.cm.ph.getSearchGroups(
                        item, '''src=['"]([^'^"]+?)['"]''')[0])
                name = '%s. %s' % (str(len(urlTab) + 1),
                                   self.up.getHostName(url))
                urlTab.append({'name': name, 'url': url, 'need_resolve': 1})

        return urlTab
Exemple #49
0
    def getLinksForVideo(self, cItem):
        urlsTab = []

        rm(self.COOKIE_FILE)
        sts, data = self.getPage(cItem['url'])
        if not sts: return []

        tmp = ph.find(data, ('<glomex-player', '>'))[1]
        if tmp:
            player_id = ph.getattr(tmp, 'data-player-id')
            playlist_id = ph.getattr(tmp, 'data-playlist-id')
            url = 'https://integration-cloudfront-eu-west-1.mes.glomex.cloud/?integration_id=%s&playlist_id=%s&current_url=' % (
                player_id, playlist_id)
            sts, data = self.getPage(url)
            if not sts: return []
            try:
                data = json_loads(data)['videos'][0]['source']
                if data.get('hls'):
                    hlsUrl = self.cm.getFullUrl(data['hls'],
                                                self.cm.meta['url'])
                    urlsTab = getDirectM3U8Playlist(
                        hlsUrl,
                        checkContent=True,
                        sortWithMaxBitrate=999999999,
                        mergeAltAudio=True)
                    if len(urlsTab):
                        urlsTab.append({
                            'name': 'Variable M3U8/HLS',
                            'url': hlsUrl,
                            'need_resolve': 0
                        })

                # progressive links seem do not work why?
                if False and data.get('progressive'):
                    mp4Url = self.cm.getFullUrl(data['progressive'],
                                                self.cm.meta['url'])
                    urlsTab.append({
                        'name': 'progressive mp4',
                        'url': mp4Url,
                        'need_resolve': 0
                    })
            except Exception:
                printExc()
        else:
            urlParams = dict(self.defaultParams)
            urlParams['header'] = MergeDicts(urlParams['header'],
                                             {'Referer': self.cm.meta['url']})
            urlParams['raw_post_data'] = True
            urlParams['use_new_session'] = True

            playerData = ph.find(data, 'getPlayer(', ');',
                                 flags=0)[1].split(',')
            printDBG("playerData <<< %s" % playerData)
            if len(playerData) == 6:
                url = self.cm.getFullUrl(
                    '/videoplayer/playerhls.php?play=%s&key=%d&identifier=web&v5partner=%s&autoplay=true&event'
                    % (playerData[1].strip(), int(
                        time.time() * 1000), playerData[3].strip()),
                    self.cm.meta['url'])
                sts, data = self.getPage(url, urlParams)
                urlParams['header'] = MergeDicts(
                    urlParams['header'], {'Referer': self.cm.meta['url']})

                url = self.cm.getFullUrl(
                    '/server/videoConfig.php?videoid=%s&partnerid=%s&language=%s&format=iphone'
                    % (playerData[1].strip(), playerData[3].strip(),
                       playerData[5].strip()[1:-1]), self.cm.meta['url'])
                sts, data = self.getPage(url, urlParams)
                try:
                    url = json_loads(data)['video']['streamAccess']
                    url = self.cm.getFullUrl(url, self.cm.meta['url'])
                    sts, data = self.getPage(url, urlParams, '[""]')
                    try:
                        printDBG("++++")
                        printDBG(data)
                        printDBG("++++")
                        data = json_loads(data)['data']['stream-access']
                        for url in data:
                            sts, streamData = self.getPage(
                                self.cm.getFullUrl(url, self.cm.meta['url']),
                                urlParams)
                            if not sts: continue
                            printDBG("?----?")
                            printDBG(data)
                            printDBG("?----?")
                            token = ph.getattr(streamData, 'auth')
                            hlsUrl = self.cm.getFullUrl(
                                ph.getattr(streamData, 'url'),
                                self.cm.meta['url']) + '?hdnea=' + token
                            urlsTab = getDirectM3U8Playlist(
                                hlsUrl,
                                checkContent=True,
                                sortWithMaxBitrate=999999999,
                                mergeAltAudio=True)
                            break
                    except Exception:
                        printExc()
                except Exception:
                    printExc()
        return urlsTab
Exemple #50
0
 def getLinksForVideo(self, cItem):
     printDBG("Playpuls.getLinksForVideo [%s]" % cItem['url'])
     videoUrls = []
     header = dict(self.HEADER)
     header['Referer'] = cItem['url']
     sts, data = self.cm.getPage(cItem['url'], {'use_cookie': True, 'load_cookie': False, 'save_cookie': True, 'cookiefile': self.COOKIE_FILE, 'header':header})
     if not sts: return videoUrls
     sts, data = self.cm.getPage(cItem['url'], {'use_cookie': True, 'load_cookie': True, 'save_cookie': False, 'cookiefile': self.COOKIE_FILE, 'header':header, 'cookie_items':{'has_js':'1'}})
     if not sts: return videoUrls
     
     sts, data = self.cm.ph.getDataBeetwenMarkers(data, '<section id="section-player" ', '</section>', False)
     if not sts: return videoUrls
     
     printDBG(data)
     
     source1Data = self.cm.ph.getSearchGroups(data, "source = '([^']+?)'")[0]
     source2Data = re.compile("([MDmd][123]) = '([^']+?)'").findall(data)
     source3Data = self.cm.ph.getSearchGroups(data, "sources[ ]*=[ ]*(\{[^;]+?);")[0]
     source4Data = re.compile("([MDmd][123])\s*:\s*\{\s*source\s*\:\s*'([^']+?)'").findall(data)
     quality     = self.cm.ph.getSearchGroups(data, "quality = '([01])';")[0]
     
     if (source1Data + source3Data + quality) == '' and 0 == len(source2Data) and 0 == len(source4Data):
         url = 'http://playpuls.pl/sites/all/modules/vod/player.php'
         id  = self.cm.ph.getSearchGroups(data, 'id\s*=\s*([0-9]+?);')[0]
         post_data = None #{'id':id}
         url += '?id=%s' % id
         header['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
         sts, source3Data = self.cm.getPage(url, {'use_cookie': True, 'load_cookie': True, 'save_cookie': False, 'cookiefile': self.COOKIE_FILE, 'header':header, 'cookie_items':{'has_js':'1'}}, post_data=post_data)
         if not sts: return videoUrls
         printDBG(source3Data)
     
     sources = []
     proto = config.plugins.iptvplayer.playpuls_defaultproto.value
     printDBG("Playpuls.getLinksForVide proto[%s] source1Data[%s] source2Data[%s] source3Data[%s] source4Data[%s] quality[%s] " % (proto, source1Data, source2Data, quality, source3Data, source4Data))
     if '' != source1Data:
         if '' != quality:
             mobileSrc = ''
             urlBase = 'http://redir.atmcdn.pl/http/o2/pulstv/vod/' + source1Data
             if '1' == quality:
                 if 'hls' != proto:
                     mobileSrc = urlBase + '/mp4/864x486_800_bp.mp4'
                 desktopHtmlHdHighSrc   = urlBase + '/mp4/1280x720_2500_hp.mp4'
                 desktopHtmlHdMediumSrc = urlBase + '/mp4/864x486_1600_hp.mp4'
                 desktopHtmlHdLowSrc    = urlBase + '/mp4/864x486_800_bp.mp4'
                 videoUrls.append({'bitrate':'2500', 'name':'High - 2500',   'url':desktopHtmlHdHighSrc})
                 videoUrls.append({'bitrate':'1600', 'name':'Medium - 1600', 'url':desktopHtmlHdMediumSrc})
                 videoUrls.append({'bitrate':'800',  'name':'Low - 800',     'url':desktopHtmlHdLowSrc})
     
             elif '0' == quality:
                 if 'hls' != proto:
                     mobileSrc = urlBase + '/mp4/720x576_800_bp.mp4'
                 desktopHtmlSdHighSrc = urlBase + '/mp4/720x576_1600_hp.mp4'
                 desktopHtmlSdLowSrc  = urlBase + '/mp4/720x576_800_bp.mp4'
                 videoUrls.append({'bitrate':'1600', 'name':'Medium - 1600', 'url':desktopHtmlSdHighSrc})
                 videoUrls.append({'bitrate':'800',  'name':'Low - 800',     'url':desktopHtmlSdLowSrc})
             
             if '' != mobileSrc:
                 videoUrls.append({'bitrate':'800', 'name':'Mobile - 800', 'url':mobileSrc})
             else:
                 mobileSrc = 'http://redir.atmcdn.pl/hls/o2/pulstv/vod/' + source1Data + '/hls/playlist.hls/playlist.m3u8'
                 mobileSrc = getDirectM3U8Playlist(mobileSrc, checkExt=False)
                 for item in mobileSrc:
                     item['url'] = self.up.decorateUrl(item['url'], {'iptv_proto':'m3u8', 'iptv_livestream':False})
                     item['bitrate'] = str(int(item.get('bitrate', '800000'))/1000)
                     item['name'] = 'Mobile(hls) - %s' % item['bitrate']
                     videoUrls.append(item)
         else:
             sources.append({'quality':'M1', 'src': '/bucket/%s/m1.mp4' % source1Data })
             sources.append({'quality':'M2', 'src': '/bucket/%s/m2.mp4' % source1Data })
             sources.append({'quality':'D1', 'src': '/bucket/%s/d1.mp4' % source1Data })
             sources.append({'quality':'D2', 'src': '/bucket/%s/d2.mp4' % source1Data })
             sources.append({'quality':'D3', 'src': '/bucket/%s/d3.mp4' % source1Data })
     elif len(source2Data) > 0:
         for item in source2Data:
             sources.append({'quality':item[0].upper(), 'src': '/play/%s' % item[1] })
     elif len(source4Data) > 0:
         for item in source4Data:
             sources.append({'quality':item[0].upper(), 'src': '/play/%s' % item[1] })
     elif source3Data != '':
         try:
             source3Data = byteify(json.loads(source3Data))
             if 'sources' in source3Data:
                 source3Data = source3Data['sources']
             for key,val in source3Data.iteritems():
                 if val != '':
                     key = key.replace('src', '')
                     sources.append({'quality':key, 'src': '/play/%s' % val })
         except Exception:
             printExc()
     
     if len(sources):
         qualityMap = {'M1':'400', 'M2':'600', 'D1':'600', 'D2':'800', 'D3':'1000'}
         for item in sources:
             # ["http://vod1.playpuls.pl:1716/Edge/_definst_/amlst:", "http://vod6.playpuls.pl:1935/Edge/_definst_/amlst:"]
             servers = ["http://vod1.playpuls.pl:1716/Edge/_definst_/mp4:s3", "http://vod6.playpuls.pl:1716/Edge/_definst_/mp4:s3"]
             server = servers[random.randrange(len(servers))]
             url = server + item['src'] #.replace("videos/converted/", "X").replace(".mp4", "")
             if 'hls' == proto:
                 url += '/playlist.m3u8'
             else:
                 url += '/manifest.mpd'
             videoUrls.append({'bitrate':qualityMap.get(item['quality'], '0'), 'name':'%s - %s' % (item['quality'], qualityMap.get(item['quality'], '0')), 'url':url})
         
     if 0 < len(videoUrls):
         max_bitrate = int(config.plugins.iptvplayer.playpuls_defaultformat.value)
         def __getLinkQuality( itemLink ):
             return int(itemLink['bitrate'])
         videoUrls = CSelOneLink(videoUrls, __getLinkQuality, max_bitrate).getSortedLinks()
         if config.plugins.iptvplayer.playpuls_usedf.value:
             videoUrls = [videoUrls[0]]            
     return videoUrls
Exemple #51
0
    def getLinksForItem(self, cItem):
        printDBG("EskaGo.getLinksForItem [%s]" % cItem)
        urlTab = []

        url = cItem['url']

        if self.up.getDomain(self.MAIN_ESKAPL_URL, onlyDomain=True) in url:
            sts, data = self.cm.getPage(url, self.defaultParams)
            if not sts: return []
            data = self.cm.ph.getDataBeetwenMarkers(
                data, '<div class="play_player">', '</div>')[1]
            url = self.cm.ph.getSearchGroups(data,
                                             '''href=['"]([^'^"]+?)['"]''')[0]
            if not self.cm.isValidUrl(url): return []

        sts, data = self.cm.getPage(url)
        if not sts: data = ''

        printDBG(
            '+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++'
        )

        if '/radio/' in url:
            tmp = self.cm.ph.getDataBeetwenMarkers(
                data, 'input[name="data-radio-url"]', ';',
                withMarkers=False)[1]
            url = self.cm.ph.getSearchGroups(tmp,
                                             '''(https?://[^'^"]+?)['"]''')[0]
            if url != '' and url.endswith('.pls'):
                sts, tmp = self.cm.getPage(url)
                if not sts: return []
                printDBG(tmp)
                tmp = tmp.split('File')
                if len(tmp): del tmp[0]
                for item in tmp:
                    printDBG('ITEM [%s]' % item)
                    url = self.cm.ph.getSearchGroups(
                        item, '''(https?://[^\s]+?)\s''')[0]
                    name = self.cm.ph.getSearchGroups(
                        item, '''Title[^=]*?=([^\s]+?)\s''')[0].strip()
                    urlTab.append({'name': name, 'url': url})
            else:
                tmp1 = self.cm.ph.getAllItemsBeetwenMarkers(
                    data, '<script', '</script>')
                for tmp in tmp1:
                    tmp = self.cm.ph.getAllItemsBeetwenMarkers(tmp, '{', '}')
                    for item in tmp:
                        if 'streamUrl' in item:
                            streamUrl = self.cm.ph.getSearchGroups(
                                item,
                                '''streamUrl\s*=\s*['"](https?://[^'^"]+?)['"]'''
                            )[0]
                            streamType = self.cm.ph.getSearchGroups(
                                item,
                                '''streamType\s*=\s*['"]([^'^"]+?)['"]''')[0]
                            if 'aac' in streamType:
                                streamUrl = streamUrl.replace('.mp3', '.aac')
                            elif 'mp3' in streamType:
                                streamUrl = streamUrl.replace('.aac', '.mp3')
                            urlTab.append({
                                'name': streamType,
                                'url': streamUrl
                            })

        elif '/tv/' in url or url.endswith('/player'):
            streamUriMap = {
                'eska-tv': ['eskatv-t/eskatv_720p', 'eskatv-t/eskatv_360p'],
                'polo-tv': ['polotv-p/stream1'],
                'eska-best-music-tv': ['best-t/best_720p', 'best-t/best_360p'],
                'eska-party-tv': [
                    'eska_party-t/eska_party_720p',
                    'eska_party-t/eska_party_360p'
                ],
                'music-vox-tv': ['vox2-p/stream1'],
                'vox-olds-cool-tv': ['vox-t/vox_720p', 'vox-t/vox_360p'],
                'eska-rock-tv':
                ['eska_rock-t/eska_rock_720p', 'eska_rock-t/eska_rock_360p'],
                'wawa-tv': ['wawa-t/wawa_720p', 'wawa-t/wawa_360p'],
                'polo-party-tv': [
                    'polo_party-t/polo_party_720p',
                    'polo_party-t/polo_party_360p'
                ],
                'player': ['fokustv-p/stream1'],
                'hip-hop-tv': ['hiphoptv-p/stream1'],
            }

            marker = cItem['url'].split('/')[-1]
            printDBG(">>>>>>>>>>>>>>> marker [%s]" % marker)
            tab = streamUriMap.get(marker, [])
            data = self.cm.ph.getDataBeetwenMarkers(data,
                                                    '$.post(',
                                                    'function',
                                                    withMarkers=False)[1]
            printDBG(data)
            secureUri = self.cm.ph.getSearchGroups(
                data, '''(https?://[^'^"]+?)['"]''')[0]
            streamUri = self.cm.ph.getSearchGroups(
                data, '''streamUri['"\s]*?:\s*?['"]([^'^"]+?)['"]''')[0]

            if secureUri == '':
                secureUri = 'https://api.stream.smcdn.pl/api/secureToken.php'
            elif streamUri not in tab:
                tab.insert(0, streamUri)

            printDBG(">>>>>>>>>>>>>>> tab %s" % tab)
            for streamUri in tab:
                sts, url = self.cm.getPage(secureUri,
                                           post_data={'streamUri': streamUri})
                if not sts: continue

                printDBG('++++++++++++++++++++++++++')
                printDBG(url)
                printDBG('++++++++++++++++++++++++++')

                if self.cm.isValidUrl(url):
                    data = getDirectM3U8Playlist(url,
                                                 checkExt=True,
                                                 checkContent=True)
                    for item in data:
                        item['url'] = urlparser.decorateUrl(
                            item['url'], {
                                'iptv_proto': 'm3u8',
                                'iptv_livestream': True
                            })
                        urlTab.append(item)

        return urlTab
 def getLinksForVideo(self, cItem):
     printDBG("Playpuls.getLinksForVideo [%s]" % cItem['url'])
     videoUrls =[]
     header = dict(self.HEADER)
     header['Referer'] = cItem['url']
     sts, data = self.cm.getPage(cItem['url'], {'use_cookie': True, 'load_cookie': False, 'save_cookie': True, 'cookiefile': self.COOKIE_FILE, 'header':header})
     if not sts: return videoUrls
     sts, data = self.cm.getPage(cItem['url'], {'use_cookie': True, 'load_cookie': True, 'save_cookie': False, 'cookiefile': self.COOKIE_FILE, 'header':header})
     if not sts: return videoUrls
     
     sts, data = self.cm.ph.getDataBeetwenMarkers(data, '<section id="section-player" ', '</script>', False)
     if not sts: return videoUrls
     
     source1Data = self.cm.ph.getSearchGroups(data, "var source = '([^']+?)'")[0]
     source2Data = re.compile("var source([MD][123]) = '([^']+?)'").findall(data)
     quality     = self.cm.ph.getSearchGroups(data, "var quality = '([01])';")[0]
     
     sources = []
     proto = config.plugins.iptvplayer.playpuls_defaultproto.value
     printDBG("Playpuls.getLinksForVide proto[%s] source1Data[%r] source2Data[%r] quality[%r]" % (proto, source1Data, source2Data, quality))
     if '' != source1Data:
         if '' != quality:
             mobileSrc = ''
             urlBase = 'http://redir.atmcdn.pl/http/o2/pulstv/vod/' + source1Data
             if '1' == quality:
                 if 'hls' != proto:
                     mobileSrc = urlBase + '/mp4/864x486_800_bp.mp4'
                 desktopHtmlHdHighSrc   = urlBase + '/mp4/1280x720_2500_hp.mp4'
                 desktopHtmlHdMediumSrc = urlBase + '/mp4/864x486_1600_hp.mp4'
                 desktopHtmlHdLowSrc    = urlBase + '/mp4/864x486_800_bp.mp4'
                 videoUrls.append({'bitrate':'2500', 'name':'High - 2500',   'url':desktopHtmlHdHighSrc})
                 videoUrls.append({'bitrate':'1600', 'name':'Medium - 1600', 'url':desktopHtmlHdMediumSrc})
                 videoUrls.append({'bitrate':'800',  'name':'Low - 800',     'url':desktopHtmlHdLowSrc})
     
             elif '0' == quality:
                 if 'hls' != proto:
                     mobileSrc = urlBase + '/mp4/720x576_800_bp.mp4'
                 desktopHtmlSdHighSrc = urlBase + '/mp4/720x576_1600_hp.mp4'
                 desktopHtmlSdLowSrc  = urlBase + '/mp4/720x576_800_bp.mp4'
                 videoUrls.append({'bitrate':'1600', 'name':'Medium - 1600', 'url':desktopHtmlSdHighSrc})
                 videoUrls.append({'bitrate':'800',  'name':'Low - 800',     'url':desktopHtmlSdLowSrc})
             
             if '' != mobileSrc:
                 videoUrls.append({'bitrate':'800', 'name':'Mobile - 800', 'url':mobileSrc})
             else:
                 mobileSrc = 'http://redir.atmcdn.pl/hls/o2/pulstv/vod/' + source1Data + '/hls/playlist.hls/playlist.m3u8'
                 mobileSrc = getDirectM3U8Playlist(mobileSrc, checkExt=False)
                 for item in mobileSrc:
                     item['url'] = self.up.decorateUrl(item['url'], {'iptv_proto':'m3u8', 'iptv_livestream':False})
                     item['bitrate'] = str(int(item.get('bitrate', '800000'))/1000)
                     item['name'] = 'Mobile(hls) - %s' % item['bitrate']
                     videoUrls.append(item)
         else:
             sources.append({'quality':'M1', 'src': '/bucket/%s/m1.mp4' % source1Data })
             sources.append({'quality':'M2', 'src': '/bucket/%s/m2.mp4' % source1Data })
             sources.append({'quality':'D1', 'src': '/bucket/%s/d1.mp4' % source1Data })
             sources.append({'quality':'D2', 'src': '/bucket/%s/d2.mp4' % source1Data })
             sources.append({'quality':'D3', 'src': '/bucket/%s/d3.mp4' % source1Data })
     else:
         for item in source2Data:
             sources.append({'quality':item[0], 'src': '/play/%s' % item[1] })
             
     if len(sources):
         qualityMap = {'M1':'400', 'M2':'600', 'D1':'600', 'D2':'800', 'D3':'1000'}
         for item in sources:
             if 'hls' == proto:
                 url = "http://193.187.64.119:1935/Edge/_definst_/mp4:s3%s/playlist.m3u8" % item['src']
             else:
                 url = 'rtmp://193.187.64.119:1935/Edge/_definst_ playpath=mp4:s3%s swfUrl=http://vjs.zencdn.net/4.12/video-js.swf pageUrl=%s' % (item['src'], cItem['url'])
             videoUrls.append({'bitrate':qualityMap[item['quality']], 'name':'%s - %s' % (item['quality'], qualityMap[item['quality']]), 'url':url})
         
     if 0 < len(videoUrls):
         max_bitrate = int(config.plugins.iptvplayer.playpuls_defaultformat.value)
         def __getLinkQuality( itemLink ):
             return int(itemLink['bitrate'])
         videoUrls = CSelOneLink(videoUrls, __getLinkQuality, max_bitrate).getSortedLinks()
         if config.plugins.iptvplayer.playpuls_usedf.value:
             videoUrls = [videoUrls[0]]            
     return videoUrls
Exemple #53
0
    def getLinksForVideo(self, cItem):
        printDBG("BajeczkiOrg.getLinksForVideo [%s]" % cItem)
        urlTab = self.cacheLinks.get(cItem['url'], [])
        if urlTab: return urlTab

        self.cacheLinks = {}

        sts, data = self.getPage(cItem['url'])
        if not sts: return

        #data = self.cm.ph.getDataBeetwenNodes(data, ('<div', '>', 'entry-content'), ('<button', '>'))[1]
        data = re.sub("<!--[\s\S]*?-->", "", data)

        tmp = ph.find(data, '<video', '</video>', flags=ph.IGNORECASE)[1]
        tmp = ph.findall(tmp, '<source', '>', flags=ph.IGNORECASE)
        for item in tmp:
            url = self.getFullUrl(
                self.cm.ph.getSearchGroups(item,
                                           '''src=['"]([^'^"]+?)['"]''',
                                           ignoreCase=True)[0])
            type = self.cm.ph.getSearchGroups(item,
                                              '''type=['"]([^'^"]+?)['"]''',
                                              ignoreCase=True)[0].lower()
            if 'mp4' in type:
                name = self.up.getDomain(url)
                urlTab.append({
                    'name':
                    name,
                    'url':
                    strwithmeta(url, {
                        'direct_link': True,
                        'Referer': self.cm.meta['url']
                    }),
                    'need_resolve':
                    1
                })

        tmp = ph.findall(data, ('<div', '>', 'data-item'),
                         flags=ph.IGNORECASE | ph.START_E)
        for item in tmp:
            if 'sources' not in item: continue
            item = ph.clean_html(ph.getattr(item, 'data-item'))
            try:
                item = json_loads(item)
                for it in item['sources']:
                    it['type'] = it.get(
                        'type',
                        it['src'].split('?', 1)[0].rsplit('.', 1)[-1]).lower()
                    url = strwithmeta(it['src'], {
                        'direct_link': True,
                        'Referer': self.cm.meta['url']
                    })
                    if 'mp4' in it['type']:
                        urlTab.append({
                            'name': it['type'],
                            'url': url,
                            'need_resolve': 1
                        })
                    elif 'mpeg' in it['type']:
                        urlTab.extend(getDirectM3U8Playlist(url))
            except Exception:
                printExc()

        tmp = self.cm.ph.getAllItemsBeetwenMarkers(data,
                                                   '<iframe',
                                                   '>',
                                                   caseSensitive=False)
        for item in tmp:
            url = self.getFullUrl(
                self.cm.ph.getSearchGroups(item,
                                           '''src=['"]([^'^"]+?)['"]''',
                                           ignoreCase=True)[0])
            if 1 == self.up.checkHostSupport(url):
                name = self.up.getDomain(url)
                urlTab.append({
                    'name':
                    name,
                    'url':
                    strwithmeta(url, {'Referer': cItem['url']}),
                    'need_resolve':
                    1
                })

        if not urlTab:
            unique = set()
            data = re.compile(
                '''['">]\s*?(https?://[^'^"^<]*?/watch\?v=[^'^"]+?)\s*?[<'"]'''
            ).findall(data)
            for url in data:
                if url not in unique:
                    urlTab.append({
                        'name':
                        'Youtube',
                        'url':
                        strwithmeta(url, {'Referer': cItem['url']}),
                        'need_resolve':
                        1
                    })
                    unique.add(url)

        if urlTab:
            self.cacheLinks[cItem['url']] = urlTab

        return urlTab
 def getTeamCastLink(self, url):
     printDBG("getTeamCastLink url[%s]" % url)
     url = 'http://team-cast.pl.cp-21.webhostbox.net/' + url
     sts, data = self.cm.getPage(url)
     if not sts: return []
     url = self.cm.ph.getSearchGroups(data, """src=['"](http://team-cast.pl.cp-21.webhostbox.net[/]+?kanalyFlash/[^'^"]+?)['"]""")[0]
     
     sts, data = self.cm.getPage(url)
     if sts:
         O1I = self.cm.ph.getSearchGroups(data, "='([^']+?)'")[0] 
         if '' != O1I:
             try:
                 data2 = data
                 printDBG('-------------------------------------------')
                 printDBG('getTeamCastLink javascript pack detected')
                 printDBG('-------------------------------------------')
                 data = MYOBFUSCATECOM_OIO(MYOBFUSCATECOM_0ll(O1I))
                 data = data.strip()
                 data = data[data.find('}(')+2:-2]
                 data = unpackJS(data, TEAMCASTPL_decryptPlayerParams)
                 data = data[data.find('}(')+2:-2]
                 data = unpackJS(data, SAWLIVETV_decryptPlayerParams)
                 data = data[data.find('}(')+2:-2]
                 data = unpackJS(data, TEAMCASTPL_decryptPlayerParams)
                 data = self.cm.ph.getSearchGroups(data, "_escape='([^']+?)'")[0]
                 data = data.replace('%', '\\u00').decode('unicode-escape').encode("utf-8")
                 #printDBG("=======================================================================")
                 #printDBG(data)
                 #printDBG("=======================================================================")
             except:
                 printExc()
                 data = data2
             data2 = ''
                 
         if "goodcast.co" in data:
             id = self.cm.ph.getSearchGroups(data, "id='([0-9]+?)';")[0]
             if '' != id:
                 videoUrl = 'http://goodcast.co/stream.php?id='+id+'&width=640&height=480'
                 videoUrl = strwithmeta(videoUrl, {'Referer':url})
                 return self.up.getVideoLinkExt(videoUrl)
         elif "yukons.net" in data:
             channel = CParsingHelper.getDataBeetwenMarkers(data, 'channel="', '"', False)[1]
             videoUrl = strwithmeta('http://yukons.net/watch/'+channel, {'Referer':url})
             return self.up.getVideoLinkExt(videoUrl)
         elif "privatestream.tv" in data:
             videoUrl = self.cm.ph.getSearchGroups(data, '"(http://privatestream.tv/[^"]+?)"')[0]
             videoUrl = strwithmeta(videoUrl, {'Referer':url})
             return self.up.getVideoLinkExt(videoUrl)
         elif "ustream.tv" in data:
             videoUrl = self.cm.ph.getSearchGroups(data, 'src="([^"]+?ustream.tv[^"]+?)"')[0]
             if videoUrl.startswith('//'):
                 videoUrl = 'http:' + videoUrl
                 videoUrl = strwithmeta(videoUrl, {'Referer':url})
                 return self.up.getVideoLinkExt(videoUrl)
         elif 'rtmp://' in data:
             tmp = self.cm.ph.getSearchGroups(data, """(rtmp://[^'^"]+?)['"]""")[0]
             tmp = tmp.split('&amp;')
             r = tmp[0]
             if 1 < len(tmp)and tmp[1].startswith('c='):
                 playpath = tmp[1][2:]
             else:
                 playpath = self.cm.ph.getSearchGroups(data, """['"]*url['"]*[ ]*?:[ ]*?['"]([^'^"]+?)['"]""")[0]
             if '' != playpath:
                 r += ' playpath=%s' % playpath.strip()
             swfUrl = self.cm.ph.getSearchGroups(data, """['"](http[^'^"]+?swf)['"]""")[0]
             r += ' swfUrl=%s pageUrl=%s' % (swfUrl, url)
             return [{'name':'team-cast', 'url':r}]
         elif 'abcast.biz' in data:
             file = self.cm.ph.getSearchGroups(data, "file='([^']+?)'")[0]
             if '' != file:
                 videoUrl = 'http://abcast.biz/embed.php?file='+file+'&width=640&height=480'
                 videoUrl = strwithmeta(videoUrl, {'Referer':url})
                 return self.up.getVideoLinkExt(videoUrl)
         elif 'shidurlive.com' in data:
             videoUrl = self.cm.ph.getSearchGroups(data, """src=['"](http[^'^"]+?shidurlive.com[^'^"]+?)['"]""")[0]
             if '' != videoUrl:
                 videoUrl = strwithmeta(videoUrl, {'Referer':url})
                 return self.up.getVideoLinkExt(videoUrl)
         elif 'sawlive.tv' in data:
             videoUrl = self.cm.ph.getSearchGroups(data, """src=['"](http[^'^"]+?sawlive.tv[^'^"]+?)['"]""")[0]
             if '' != videoUrl:
                 videoUrl = strwithmeta(videoUrl, {'Referer':url})
                 return self.up.getVideoLinkExt(videoUrl)
         elif "castalba.tv" in data:
             id = self.cm.ph.getSearchGroups(data, """id=['"]([0-9]+?)['"];""")[0]
             if '' != id:
                 videoUrl = 'http://castalba.tv/embed.php?cid='+id+'&wh=640&ht=400&r=team-cast.pl.cp-21.webhostbox.net'
                 videoUrl = strwithmeta(videoUrl, {'Referer':url})
                 return self.up.getVideoLinkExt(videoUrl)
         elif "fxstream.biz" in data:
             file = self.cm.ph.getSearchGroups(data, """file=['"]([^'^"]+?)['"];""")[0]
             if '' != file:
                 videoUrl = 'http://fxstream.biz/embed.php?file='+file+'&width=640&height=400'
                 videoUrl = strwithmeta(videoUrl, {'Referer':url})
                 return self.up.getVideoLinkExt(videoUrl)
         else:
             file = self.cm.ph.getSearchGroups(data, """['"]([^'^"]+?\.m3u8)['"]""")[0]
             if '' != file:
                 return getDirectM3U8Playlist(file, checkExt=False)
             printDBG("=======================================================================")
             printDBG(data)
             printDBG("=======================================================================")
     return []
Exemple #55
0
    def getVideoLink(self, cItem):
        printDBG("BilaSportPwApi.getVideoLink")
        urlsTab = []

        sts, data = self.getPage(cItem['url'])
        if not sts: return urlsTab
        cUrl = self.cm.meta['url']
        baseUrl = cUrl

        url = self.getFullUrl(
            ph.search(data, '''['"]([^'^"]*?/iframes/[^'^"]+?)['"]''')[0],
            cUrl)
        if not url: return urlsTab
        sts, data = self.getPage(url)
        if not sts: return urlsTab
        cUrl = self.cm.meta['url']

        url = self.getFullUrl(ph.search(data, ph.IFRAME)[1], cUrl)
        if url:
            sts, data = self.getPage(url)
            if not sts: return urlsTab
            cUrl = self.cm.meta['url']

        replaceTab = self.cm.ph.getDataBeetwenMarkers(data, 'prototype.open',
                                                      '};', False)[1]
        printDBG(replaceTab)
        replaceTab = re.compile(
            '''\.replace\(['"](\s*[^'^"]+?)['"]\s*\,\s*['"]([^'^"]+?)['"]'''
        ).findall(replaceTab)
        printDBG(replaceTab)
        if len(replaceTab):
            scriptUrl = '|' + base64.b64encode(
                json_dumps(replaceTab).encode('utf-8'))
        else:
            scriptUrl = ''
            tmp = ph.findall(data,
                             ('<script', '>', ph.check(ph.none,
                                                       ('jsdelivr', ))))
            for item in tmp:
                scriptUrl = self.getFullUrl(ph.getattr(item, 'src'), cUrl)
                break

        hlsTab = []
        hlsUrl = re.compile('''(https?://[^'^"]+?\.m3u8(?:\?[^'^"]+?)?)['"]''',
                            re.IGNORECASE).findall(data)
        if len(hlsUrl):
            hlsUrl = hlsUrl[-1]
            hlsTab = getDirectM3U8Playlist(hlsUrl,
                                           checkContent=True,
                                           sortWithMaxBitrate=9000000)
            for idx in range(len(hlsTab)):
                hlsTab[idx]['need_resolve'] = 1
                hlsTab[idx]['url'] = strwithmeta(
                    hlsTab[idx]['url'], {
                        'name': cItem['name'],
                        'Referer': url,
                        'priv_script_url': scriptUrl
                    })

        if hlsTab:
            return hlsTab

        if 1 == self.up.checkHostSupport(cUrl):
            return self.up.getVideoLinkExt(
                strwithmeta(cUrl, {'Referer': baseUrl}))

        return []
    def getLinksForVideo(self, Index = 0, selItem = None):
        listLen = len(self.host.currList)
        if listLen < Index and listLen > 0:
            printDBG( "ERROR getLinksForVideo - current list is to short len: %d, Index: %d" % (listLen, Index) )
            return RetHost(RetHost.ERROR, value = [])
        
        if self.host.currList[Index]["type"] != 'video':
            printDBG( "ERROR getLinksForVideo - current item has wrong type" )
            return RetHost(RetHost.ERROR, value = [])

        retlist = []
        url = self.host.currList[Index].get("url", '')
        name = self.host.currList[Index].get("name", '')
        
        printDBG(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> [%s] [%s]" % (name, url))
        urlList = None
        
        if -1 != url.find('teledunet'):
            new_url = TeledunetParser().get_rtmp_params(url)
            if 0 < len(url): retlist.append(CUrlItem("Własny link", new_url))
        elif url.startswith('http://goldvod.tv/'):
            url = self.host.getGoldvodLink(url)
        elif 'web-live.tv' in url:
            url = self.host.getSatLiveLink(url)
        elif 'vidtv.pl' in url:
            url = self.host.getVidTvLink(url)
        elif 'looknij.tv' in url:
            url = self.host.getLooknijTvLink(url)
        elif 'tvisport.cba.pl' in url:
            urlList = self.host.getTvSportCdaLink(url)
        elif 'nettv.pw' in url:
            urlList = self.host.getNettvpwLink(url)
        elif 'weeb.tv' in name:
            url = self.host.getWeebTvLink(url)
        elif name == "team-cast.pl":
            urlList = self.host.getTeamCastLink(url)
        elif "filmon_channel" == name:
            urlList = self.host.getFilmOnLink(channelID=url)
        elif "videostar_channels" == name:
            urlList = self.host.getVideostarLink(channelID=url)
            #if 1 < len(tmpList):
            #    for item in tmpList:
            #        retlist.append(CUrlItem(item['name'], item['url']))
            #elif 1 == len(tmpList):
            #    url =  tmpList[0]['url']
        elif name == "webcamera.pl":
            urlList = self.host.getWebCameraLink(url)
        elif name == "prognoza.pogody.tv":
            urlList = self.host.prognozaPogodyLink(url)
            
        if isinstance(urlList, list):
            for item in urlList:
                retlist.append(CUrlItem(item['name'], item['url']))
        elif isinstance(url, basestring):
            if url.endswith('.m3u'):
                tmpList = self.host.getDirectVideoHasBahCa(name, url)
                for item in tmpList:
                    retlist.append(CUrlItem(item['name'], item['url']))
            else:
                iptv_proto = urlparser.decorateUrl(url).meta.get('iptv_proto', '')
                if 'm3u8' == iptv_proto:
                    tmpList = getDirectM3U8Playlist(url, checkExt=False)
                    for item in tmpList:
                        retlist.append(CUrlItem(item['name'], item['url']))
                elif 'f4m' == iptv_proto:
                    tmpList = getF4MLinksWithMeta(url, checkExt=False)
                    for item in tmpList:
                        retlist.append(CUrlItem(item['name'], item['url']))
                else:
                    if '://' in url:
                        retlist.append(CUrlItem("Link", url))
            
        return RetHost(RetHost.OK, value = retlist)
Exemple #57
0
    def getLinksForVideo(self, cItem):
        printDBG("Laola1TV.getLinksForVideo [%s]" % cItem)
        urlTab = []

        sts, data = self.cm.getPage(cItem['url'])
        if not sts: return []
        baseUrl = self.cm.meta['url']

        data = self.cm.ph.getDataBeetwenMarkers(data,
                                                '<div class="videoplayer"',
                                                '</script>')[1]
        printDBG(data)
        getParams = {}
        getParams['videoid'] = self.cm.ph.getSearchGroups(
            data, '\svideoid\s*:\s*"([0-9]*?)"')[0]
        getParams['partnerid'] = self.cm.ph.getSearchGroups(
            data, '\spartnerid\s*:\s*"([0-9]*?)"')[0]
        getParams['language'] = self.cm.ph.getSearchGroups(
            data, '\slanguage\s*:\s*"([a-z]*?)"')[0]
        getParams['portal'] = self.cm.ph.getSearchGroups(
            data, '\portalid\s*:\s*"([a-z]*?)"')[0]
        getParams['format'] = 'iphone'
        vidUrl = self.cm.ph.getSearchGroups(data,
                                            '\configUrl\s*:\s*"([^"]*?)"')[0]
        if vidUrl.startswith('//'):
            vidUrl = 'http:' + vidUrl
        vidUrl += '?' + urllib.urlencode(getParams)
        vidUrl = self._getFullUrl(vidUrl, baseUrl)

        sts, data = self.getPage(vidUrl)
        if not sts: return []

        try:
            data = byteify(json.loads(data))
            url = data['video']['streamAccess']
            req_abo = []
            for item in data['video']['abo']['required']:
                req_abo.append(str(item))
        except Exception:
            return []
            printExc()

        ######################################################
        streamaccessTab = []
        post_data = {}
        for idx in range(len(req_abo)):
            post_data[idx] = req_abo[idx]
        sts, data = self.getPage(url, {}, post_data)
        try:
            data = byteify(json.loads(data))
            for item in data['data']['stream-access']:
                streamaccessTab.append(item)
        except Exception:
            printExc()

        comment = ''
        for streamaccess in streamaccessTab:
            for myip in [
                    '', config.plugins.iptvplayer.laola1tv_myip1.value,
                    config.plugins.iptvplayer.laola1tv_myip2.value
            ]:
                if '' != myip: header = {'X-Forwarded-For': myip}
                else: header = {}
                sts, data = self.getPage(streamaccess, {'header': header})
                if not sts: return urlTab
                data = self.cm.ph.getDataBeetwenMarkers(
                    data, '<data>', '</data>', False)[1]
                printDBG(data)
                comment = self.cm.ph.getSearchGroups(data,
                                                     'comment="([^"]+?)"')[0]
                auth = self.cm.ph.getSearchGroups(data, 'auth="([^"]+?)"')[0]
                if auth in ['restricted', 'blocked']: continue
                url = self.cm.ph.getSearchGroups(data, 'url="([^"]+?)"')[0]
                url = url + '?hdnea=' + auth

                if myip != '':
                    url = strwithmeta(url, {'X-Forwarded-For': myip})

                COOKIE_FILE = GetCookieDir('m3u8_laola1.tv')
                rm(COOKIE_FILE)
                cookieParams = {
                    'use_cookie': True,
                    'load_cookie': True,
                    'save_cookie': True,
                    'cookiefile': COOKIE_FILE
                }
                tmp = getDirectM3U8Playlist(url,
                                            checkExt=False,
                                            cookieParams=cookieParams,
                                            checkContent=True)
                if len(tmp):
                    urlMeta = {
                        'iptv_proto': 'm3u8',
                        'Origin': self.up.getDomain(baseUrl, False),
                        'Cookie': self.cm.getCookieHeader(COOKIE_FILE),
                        'User-Agent': self.cm.HOST,
                        'Referer': baseUrl
                    }
                for idx in range(len(tmp)):
                    tmp[idx]['need_resolve'] = 0
                    tmp[idx]['url'] = strwithmeta(tmp[idx]['url'], urlMeta)
                    urlTab.append(tmp[idx])
                break
            if 0 < len(urlTab):
                break

        if 0 < len(urlTab):
            max_bitrate = int(
                config.plugins.iptvplayer.laola1tv_defquality.value)

            def __getLinkQuality(itemLink):
                try:
                    value = itemLink['bitrate']
                    return int(value)
                except Exception:
                    printExc()
                    return 0

            urlTab = CSelOneLink(urlTab, __getLinkQuality,
                                 max_bitrate).getSortedLinks()
            if config.plugins.iptvplayer.laola1tv_onelink.value:
                urlTab = [urlTab[0]]
        else:
            SetIPTVPlayerLastHostError(comment)

        return urlTab