def _getVideoUrls(self, vodData):
        urls = []
        re_compile_srcreq = re.compile('<srcreq ([^>]+?)>')
        max_bitrate = int(config.plugins.iptvplayer.iplaDefaultformat.value)

        def __getLinkQuality(itemLink):
            return int(itemLink['bitrate'])

        try:
            links = re_compile_srcreq.findall(vodData)
            for link in links:
                attrib = self.__getAttribs(link)
                drm = attrib['drmtype']
                if drm == '0':
                    if config.plugins.iptvplayer.ZablokujWMV.value and attrib[
                            'format'] == '0':
                        continue
                    name = "Jakość: %s\t format: %s\t  bitrate: %s" % (
                        attrib['quality'], attrib['format'], attrib['bitrate'])
                    urls.append({
                        'name': name,
                        'url': attrib['url'],
                        'bitrate': attrib['bitrate']
                    })
        except Exception:
            printExc()
        urls = CSelOneLink(urls, __getLinkQuality,
                           max_bitrate).getSortedLinks()
        if config.plugins.iptvplayer.iplaUseDF.value:
            urls = [urls[0]]
        return urls
    def getLinksForVideo(self, cItem):
        printDBG("TVJWORG.getLinksForVideo [%s]" % cItem)
        urlTab = []

        try:
            tmpTab = cItem.get('files', [])
            for item in tmpTab:
                try:
                    linkVideo = item['progressiveDownloadURL']
                    linkVideo = urlparser.decorateUrl(
                        linkVideo, {'Referer': 'http://tv.jw.org/'})
                    urlTab.append({
                        'name': item['label'],
                        'url': linkVideo,
                        'need_resolve': 0
                    })
                except Exception:
                    printExc()

            if 1 < len(urlTab):
                error = False
                max_bitrate = int(
                    config.plugins.iptvplayer.tvjworg_default_format.value)

                def __getLinkQuality(itemLink):
                    try:
                        return int(itemLink['name'][0:-1])
                    except Exception:
                        error = True
                        return 0

                oneLink = CSelOneLink(urlTab, __getLinkQuality, max_bitrate)
                if not error and config.plugins.iptvplayer.tvjworg_use_df.value:
                    urlTab = oneLink.getOneLink()
                else:
                    urlTab = oneLink.getSortedLinks()
        except Exception:
            printExc()

        return urlTab
示例#3
0
 def getLinksForVideo(self, cItem):
     printDBG("UKTVPlay.getLinksForVideo [%s]" % cItem)
     
     retTab = []
     
     videoUrl = 'http://c.brightcove.com/services/mobile/streaming/index/master.m3u8?videoId=%s' % cItem['f_video_id']
     retTab = getDirectM3U8Playlist(videoUrl, checkContent=True)
     
     def __getLinkQuality( itemLink ):
         try: return int(itemLink['bitrate'])
         except Exception: return 0
     
     retTab = CSelOneLink(retTab, __getLinkQuality, 99999999).getSortedLinks()
     
     return retTab
示例#4
0
    def getLinksForVideo(self, cItem):
        printDBG("VODPL.getLinksForVideo [%s]" % cItem)
        url = cItem['url']
        videoUrls = []
        tmpTab = []
        tries = 0
        while tries < 2:
            tries += 1
            sts, data = self.cm.getPage(url)
            if not sts: return videoUrls
            ckmId = self.cm.ph.getSearchGroups(data,
                                               'data-params-mvp="([^"]+?)"')[0]
            if '' == ckmId:
                ckmId = self.cm.ph.getSearchGroups(data,
                                                   'id="mvp:([^"]+?)"')[0]
            if '' != ckmId:
                tmpTab = self._getVideoTab(ckmId)
                break
            data = self.cm.ph.getDataBeetwenMarkers(data, 'pulsembed_embed',
                                                    '</div>')[1]
            url = self.cm.ph.getSearchGroups(data, 'href="([^"]+?)"')[0]

        tab = []
        for item in tmpTab:
            if item[0] == 'mp4':
                tab.append(item)

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

        maxRes = int(
            config.plugins.iptvplayer.onetvodDefaultformat.value) * 1.1
        tab = CSelOneLink(tab, __getLinkQuality, maxRes).getSortedLinks()
        if config.plugins.iptvplayer.onetvodUseDF.value and len(tab) > 0:
            tab = [tab[0]]

        for item in tab:
            name = "type: %s \t bitrate: %s" % (item[0], item[2])
            url = item[1]
            videoUrls.append({'name': name, 'url': url, 'need_resolve': 0})

        return videoUrls
    def getLinksForVideo(self, cItem):
        printDBG("WpTV.getLinksForVideo [%s]" % cItem)
        urlTab = []

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

        vidId = self.cm.ph.getSearchGroups(data, 'data-mid="([^"]+?)"')[0]
        vidUrl = self.MAIN_URL + "player/mid,%s,embed.json" % vidId
        try:
            sts, data = self.cm.getPage(vidUrl, self.defaultParams)
            if not sts: return []

            tmpTab = []
            qMap = {"HQ": '2', "LQ": '1'}
            data = byteify(json.loads(data))
            for item in data['clip']['url']:
                if 'mp4' not in item['type']: continue
                urlTab.append({
                    'name': item['quality'] + ' ' + item['type'],
                    'url': self.getFullUrl(item['url']),
                    'quality': qMap.get(item['quality'], '3'),
                    'need_resolve': 0
                })

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

                def __getLinkQuality(itemLink):
                    if 'mobile' in itemLink['name']: return 0
                    return int(itemLink['quality'])

                urlTab = CSelOneLink(urlTab, __getLinkQuality,
                                     max_bitrate).getSortedLinks()
                if config.plugins.iptvplayer.wpUseDF.value:
                    urlTab = [urlTab[0]]
        except Exception:
            printExc()
        return urlTab
    def getVideoLink(self, cItem):
        printDBG("DjingComApi.getVideoLink")
        urlsTab = []
        hlsUrl = cItem.get('iptv_hls_url', '')
        printDBG("hlsUrl||||||||||||||||| " + hlsUrl)
        if hlsUrl != '':
            hlsUrl = strwithmeta(
                hlsUrl, {
                    'User-Agent': self.defaultParams['header']['User-Agent'],
                    'Referer': cItem['url']
                })
            urlsTab = getDirectM3U8Playlist(hlsUrl, checkContent=True)

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

        return CSelOneLink(urlsTab, __getLinkQuality,
                           99999999).getSortedLinks()
示例#7
0
    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=[])
        retlist = []
        if 'ekstraklasa.tv' in self.host.currList[Index].get('host', ''):
            tab = self.host.getLinks_ETV(self.host.currList[Index].get(
                'url', ''))

            tmp = tab
            tab = []
            for item in tmp:
                if item[0] == Ekstraklasa.ETV_FORMAT:
                    tab.append(item)

            def __getLinkQuality(itemLink):
                return int(itemLink[2])

            maxRes = int(config.plugins.iptvplayer.ekstraklasa_defaultformat.
                         value) * 1.1
            tab = CSelOneLink(tab, __getLinkQuality, maxRes).getSortedLinks()
            printDBG(
                ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>. tab[%s]" %
                tab)
            if config.plugins.iptvplayer.ekstraklasa_usedf.value and 0 < len(
                    tab):
                tab = [tab[0]]

            for item in tab:
                nameLink = "type: %s \t bitrate: %s" % (item[0], item[2])
                url = item[1]
                retlist.append(
                    CUrlItem(nameLink.encode('utf-8'), url.encode('utf-8'), 0))
        elif 'ekstraklasa.org' in self.host.currList[Index].get('host', ''):
            pass
        return RetHost(RetHost.OK, value=retlist)
示例#8
0
    def getLinksForVideo(self, url):
        printDBG("getLinksForVideo url[%s]" % url)
        ytformats = config.plugins.iptvplayer.ytformat.value
        maxRes = int(config.plugins.iptvplayer.ytDefaultformat.value) * 1.1
        dash = config.plugins.iptvplayer.ytShowDash.value

        if not url.startswith("http://") and not url.startswith("https://"):
            url = 'http://www.youtube.com/' + url
        tmpTab, dashTab = self.ytp.getDirectLinks(url,
                                                  ytformats,
                                                  dash,
                                                  dashSepareteList=True)

        def __getLinkQuality(itemLink):
            val = self.cm.ph.getSearchGroups('|%s|' % itemLink['format'],
                                             '[^0-9]([0-9]+?)[^0-9]')[0]
            if '' == val: return 0
            return int(val)

        tmpTab = CSelOneLink(tmpTab, __getLinkQuality, maxRes).getSortedLinks()
        if config.plugins.iptvplayer.ytUseDF.value and 0 < len(tmpTab):
            tmpTab = [tmpTab[0]]

        videoUrls = []
        for item in tmpTab:
            videoUrls.append({
                'name': item['format'] + ' | ' + item['ext'],
                'url': item['url']
            })
        for item in dashTab:
            videoUrls.append({
                'name':
                _("[dash] ") + item['format'] + ' | ' + item['ext'],
                'url':
                item['url']
            })
        return videoUrls
示例#9
0
    def getLinks(self, id):
        printDBG("TvnVod.getLinks cItem.id[%r]" % id)
        videoUrls = []

        for pl in ['Panasonic', 'Samsung',
                   'Android2']:  #, 'Android4']: #'Android', ''Samsung',
            if pl in ['Android', 'Android2', 'Panasonic']:
                url = '&type=episode&id=%s&limit=%d&page=1&sort=newest&m=%s' % (
                    id, self.itemsPerPage, 'getItem')
            else:
                url = 'm=getItem&id=%s&android23video=1&deviceType=Tablet&os=4.1.1&playlistType=&connectionType=WIFI&deviceScreenWidth=1920&deviceScreenHeight=1080&appVersion=3.3.4&manufacturer=unknown&model=androVMTablet' % id
            url = self.getBaseUrl(pl) + url

            sts, data = self.cm.getPage(url,
                                        {'header': self.getHttpHeader(pl)})
            if not sts: continue
            try:
                data = json.loads(data)
                if 'success' == data['status']:
                    data = data['item']
                    # videoTime = 0
                    # tmp = self._getJItemStr(data, 'run_time', '')
                    # if '' != tmp:
                    # tmp = tmp.split(":")
                    # videoTime = int(tmp[0])*60*60+int(tmp[1])*60+int(tmp[2])

                    plot = self._getJItemStr(data, 'lead', '')
                    printDBG("data:\n%s\n" % data)
                    videos = data['videos']['main']['video_content']
                    if None == videos:
                        SetIPTVPlayerLastHostError("DRM protection.")
                    else:
                        for video in videos:
                            url = self._getJItemStr(video, 'url', '')
                            if '' == url:
                                SetIPTVPlayerLastHostError("DRM protection.")
                            #    url = self._getJItemStr(video, 'src', '')
                            if '' != url:
                                url = strwithmeta(url, {'tvn_platform': pl})
                                qualityName = self._getJItemStr(
                                    video, 'profile_name', '')
                                videoUrls.append({
                                    'name': qualityName,
                                    'profile_name': qualityName,
                                    'url': url,
                                    'need_resolve': 1
                                })
                    if 1 < len(videoUrls):
                        max_bitrate = int(
                            config.plugins.iptvplayer.TVNDefaultformat.value)

                        def __getLinkQuality(itemLink):
                            return int(
                                TvnVod.QUALITIES_TABLE.get(
                                    itemLink['profile_name'], 9999))

                        videoUrls = CSelOneLink(videoUrls, __getLinkQuality,
                                                max_bitrate).getSortedLinks()
                        if config.plugins.iptvplayer.TVNUseDF.value:
                            videoUrls = [videoUrls[0]]
            except Exception:
                printExc()
            if len(videoUrls):
                break
        return videoUrls
示例#10
0
    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()
            response.close()
        except Exception:
            printExc()
            return []

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

        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
示例#11
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):
         try:
             if not self.cm.isValidUrl(url): return
             if 'width' in item and 'height' in item:
                 name = '%sx%s' % (item['width'], item['height'])
             else:
                 name = item.get('name', str(item['bitrate']))
             bitrate = item['bitrate']
             urlTab.append({'name':name, 'url':url, 'bitrate':bitrate, 'need_resolve':0})
         except Exception:
             printExc()
     
     tmp = self.cm.ph.getDataBeetwenMarkers(data, 'talkPage.init",', ')<', False)[1]
     try:
         playerData = byteify(json.loads(tmp))['__INITIAL_DATA__']
         tmp = playerData['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)
         
         if 0 == len(urlTab):
             h264Tab = tmp['resources'].get('h264', [])
             if h264Tab == None: h264Tab = []
             for item in h264Tab:
                 _addLinkItem(urlTab, item, item['file'])
         
         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
 def getLinksForVideo(self, cItem):
     printDBG("SVTPlaySE.getLinksForVideo [%s]" % cItem)
     videoUrls = []
     
     hlsUrl  = cItem.get('hls_url')
     dashUrl = cItem.get('dash_url')
     
     subtitlesTab = []
     
     if hlsUrl == None or dashUrl == None:
         if 'api' not in self.up.getDomain(cItem['url']):
             url = self.getFullUrl(cItem['url'])
             sts, data = self.cm.getPage(url, self.defaultParams)
             if not sts: return []
             videoId = self.cm.ph.getSearchGroups(data, '<video\s+?data-video-id="([^"]+?)"')[0]
             url = 'http://api.svt.se/videoplayer-api/video/' + videoId
         else:
             url = cItem['url']
         
         sts, data = self.cm.getPage(url, self.defaultParams)
         if not sts: return []
         
         printDBG(data)
         
         try:
             data = byteify(json.loads(data))
             
             videoItem = data.get('video', None)
             if videoItem  == None: videoItem = data
             for item in videoItem['videoReferences']:
                 if self.cm.isValidUrl(item['url']):
                     if 'dashhbbtv' in item['format']:
                         dashUrl = item['url']
                     elif 'hls' in item['format']:
                         hlsUrl = item['url']
             
             for item in videoItem['subtitleReferences']:
                 format = item['url'][-3:]
                 if format in ['srt', 'vtt']:
                     subtitlesTab.append({'title':format, 'url':self.getFullIconUrl(item['url']), 'lang':'n/a', 'format':format})
         except Exception: 
             printExc()
     
     tmpTab = []
     if config.plugins.iptvplayer.svt_prefered_format.value == 'hls':
         tmpTab.append(hlsUrl)
         tmpTab.append(dashUrl)
     else:
         tmpTab.append(dashUrl)
         tmpTab.append(hlsUrl)
     
     max_bitrate = int(config.plugins.iptvplayer.svt_default_quality.value)
     for item in tmpTab:
         if item == '': continue
         if item == dashUrl:
             item = getMPDLinksWithMeta(item, False)
         elif item == hlsUrl:
             vidTab = []
             # item = strwithmeta(item, {'X-Forwarded-For':'83.172.75.170'})
             try:
                 tmp = urlparse.urlparse(item)
                 tmp = urlparse.parse_qs(tmp.query)['alt'][0]
                 vidTab = getDirectM3U8Playlist(tmp, False, checkContent=True)
             except Exception:
                 printExc()
             if 0 == len(vidTab):
                 item = getDirectM3U8Playlist(item, False, checkContent=True)
             else:
                 item = vidTab
         else: continue
         
         if len(item):
             def __getLinkQuality( itemLink ):
                 try: return int(itemLink['height'])
                 except Exception: return 0
             item = CSelOneLink(item, __getLinkQuality, max_bitrate).getSortedLinks()
             if config.plugins.iptvplayer.svt_use_default_quality.value:
                 videoUrls.append(item[0])
                 break
             videoUrls.extend(item)
     
     if len(subtitlesTab):
         for idx in range(len(videoUrls)):
             videoUrls[idx]['url'] = strwithmeta(videoUrls[idx]['url'], {'external_sub_tracks':subtitlesTab})
             videoUrls[idx]['need_resolve'] = 0
     
     return videoUrls
    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 []
            
            url, sec_header, post_data = self._getSecurityData(data, params)
            params['header'].update(sec_header)
            params['header']['X-Requested-With'] = 'XMLHttpRequest'
            params['load_cookie'] = True
            if not self.cm.isValidUrl(url):
                url = self.baseUrl + url
            sts, data = self.cm.getPage(url, params, post_data)
            printDBG("=======================================================")
            printDBG(data)
            printDBG("=======================================================")
            if not sts: return []
            
            try: 
                data = byteify( json.loads(data) )
                data = data['mans']
            except Exception: printExc()
            try:
                mp4Url = strwithmeta(data["mp4"], {'User-Agent':'Mozilla/5.0', 'Referer':url})
                sts, tmp = self.cm.getPage(mp4Url, {'User-Agent':'Mozilla/5.0', 'Referer':url})
                tmpTab = []
                tmp = byteify(json.loads(tmp))
                printDBG(tmp)
                for key in tmp:
                    mp4Url = tmp[key]
                    if mp4Url.split('?')[0].endswith('.mp4'):
                        tmpTab.append({'url':mp4Url, 'heigth':key})
                    
                def __getLinkQuality( itemLink ):
                    return int(itemLink['heigth'])
                    
                maxRes = config.plugins.iptvplayer.moonwalk_df_format.value
                tmpTab = CSelOneLink(tmpTab, __getLinkQuality, maxRes).getSortedLinks()
                if config.plugins.iptvplayer.moonwalk_use_df.value:
                    tmpTab = [tmpTab[0]]
                for item in tmpTab:
                    linksTab.append({'name':'[mp4] %sp' % __getLinkQuality(item), 'url':item['url']})
            except Exception:
                printExc()

            if 'm3u8' == config.plugins.iptvplayer.moonwalk_format.value:
                hlsUrl = strwithmeta(data['m3u8'], {'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', 'Referer':url})
                tmpTab = getDirectM3U8Playlist(hlsUrl)
                def __getLinkQuality( itemLink ):
                    return int(itemLink['heigth'])
                maxRes = config.plugins.iptvplayer.moonwalk_df_format.value
                tmpTab = CSelOneLink(tmpTab, __getLinkQuality, maxRes).getSortedLinks()
                if config.plugins.iptvplayer.moonwalk_use_df.value:
                    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
                maxRes = config.plugins.iptvplayer.moonwalk_df_format.value
                tmpTab = CSelOneLink(tmpTab, __getLinkQuality, maxRes).getSortedLinks()
                if config.plugins.iptvplayer.moonwalk_use_df.value:
                    tmpTab = [tmpTab[0]]
                for item in tmpTab:
                    linksTab.append({'name':'[f4m/hds] %sp' % __getLinkQuality(item), 'url':item['url']})
        except Exception:
            printExc()
        return linksTab
    def getLinksForVideo(self, cItem):
        printDBG("TvGryPL.getLinksForVideo [%s]" % cItem)
        allLinksTab = []
        urlTab = []

        rm(self.COOKIE_FILE)

        sts, data = self.getPage(
            cItem['url'], self.defaultParams
        )  #{'use_cookie':True, 'cookie_items':{'agegate':1}})
        if not sts: return urlTab

        ageMarker = '<div class="player-AGEGATE">'
        if ageMarker in data:
            tmp = self.cm.ph.getSearchGroups(
                config.plugins.iptvplayer.tvgrypl_date_of_birth.value,
                '''([0-9]{4})[-]?([0-9][0-9]?)[-]?([0-9][0-9]?)''', 3)
            printDBG(">>>>>YEAR[%s] MONTH[%s] DAY[%s]" %
                     (tmp[0], tmp[1], tmp[2]))
            if '' != tmp[0] and '' != tmp[1] and '' != tmp[2]:
                urlParams = dict(self.defaultParams)
                urlParams['header'] = dict(self.AJAX_HEADER)
                urlParams['header']['Referer'] = cItem['url']

                sts, data = self.getPage('https://tvgry.pl/ajax/agegate.asp',
                                         urlParams, {
                                             'day': int(tmp[2]),
                                             'month': int(tmp[1]),
                                             'year': int(tmp[0])
                                         })
                if not sts: return []

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

                if ageMarker in data:
                    SetIPTVPlayerLastHostError(
                        "Twój wiek nie został poprawnie zweryfikowany przez serwis http://tvgry.pl/.\nSprawdź ustawioną datę urodzenia w konfiguracji hosta."
                    )
            else:
                SetIPTVPlayerLastHostError(
                    "Wprowadź datę urodzenia w konfiguracji hosta - wymagane przez serwis http://tvgry.pl/."
                )

        url = self.cm.ph.getSearchGroups(
            data, '''<iframe[^>]+?src=['"]([^"^']+?)['"]''', 1, True)[0]
        if self.cm.isValidUrl(url):
            allLinksTab = self.up.getVideoLinkExt(url)

        urlIDS = []
        urlTemplate = ''
        data = self.cm.ph.getDataBeetwenMarkers(data, 'sources:', ']')[1]
        data = self.cm.ph.getAllItemsBeetwenMarkers(data, '{', '}')
        for item in data:
            url = self.cm.ph.getSearchGroups(
                item, '''['"]?file['"]?\s*:\s*['"]([^'^"]+?)['"]''')[0]
            name = self.cm.ph.getSearchGroups(
                item, '''['"]?label['"]?\s*:\s*['"]([^'^"]+?)['"]''')[0]
            if self.cm.isValidUrl(url):
                id = self.cm.ph.getSearchGroups(url, '''(/[0-9]+_)[0-9]+''')[0]
                if id != '' and id not in urlIDS:
                    urlIDS.append(id)
                    if urlTemplate == '': urlTemplate = url.replace(id, '{0}')

                q = ""
                if '/500_' in url or "Mobile" in url:
                    q = 'MOB'
                elif '/750_' in url or "SD" in url:
                    q = 'SD'
                elif '/1280_' in url or "720p" in url:
                    q = 'HD'
                if q != '':
                    urlTab.append({
                        'name':
                        name,
                        'url':
                        strwithmeta(url, {"Range": "bytes=0-"}),
                        'q':
                        q,
                        'need_resolve':
                        0
                    })

        if urlTemplate != '':
            params = dict(self.defaultParams)
            params['header'] = dict(params['header'])
            params['header']['Range'] = "bytes=0-"
            params['return_data'] = False
            params['header'].pop('Accept', None)
            for item in [('/500_', 'MOB'), ('/750_', 'SD'), ('/1280_', 'HD')]:
                if item[0] in urlIDS: continue
                try:
                    url = urlTemplate.format(item[0])
                    sts, response = self.cm.getPage(url, params)
                    if 'mp4' in response.info().get('Content-Type',
                                                    '').lower():
                        urlTab.append({
                            'name':
                            item[1],
                            'url':
                            strwithmeta(url, {"Range": "bytes=0-"}),
                            'q':
                            item[1],
                            'need_resolve':
                            0
                        })
                    response.close()
                except Exception:
                    printExc()

        if 1 < len(urlTab):
            map = {'MOB': 0, 'SD': 1, 'HD': 2, 'FHD': 3}
            oneLink = CSelOneLink(
                urlTab, lambda x: map[x['q']],
                map[config.plugins.iptvplayer.tvgrypl_default_quality.value])
            if config.plugins.iptvplayer.tvgrypl_use_dq.value:
                urlTab = oneLink.getOneLink()
            else:
                urlTab = oneLink.getSortedLinks()

        if 0 == len(urlTab):
            return allLinksTab

        return urlTab
示例#15
0
def getMPDLinksWithMeta(manifestUrl,
                        checkExt=True,
                        cookieParams={},
                        sortWithMaxBandwidth=-1):
    if checkExt and not manifestUrl.split('?')[0].endswith('.mpd'):
        return []

    cm = common()

    def _getNumAttrib(data, name, default=0):
        try:
            return int(
                cm.ph.getSearchGroups(
                    data, '[\s]' + name + '''=['"]([^'^"]+?)['"]''')[0])
        except Exception:
            return default

    headerParams, postData = cm.getParamsFromUrlWithMeta(manifestUrl)
    headerParams.update(cookieParams)

    retPlaylists = []
    sts, data = cm.getPage(manifestUrl, headerParams, postData)
    if sts:
        liveStreamDetected = False
        if 'type="dynamic"' in data:
            liveStreamDetected = True

        representation = {'audio': [], 'video': []}
        tmp = cm.ph.getAllItemsBeetwenMarkers(data,
                                              "<Period",
                                              '</Period>',
                                              withMarkers=True)
        if len(tmp): data = tmp[-1]
        # TODO!!! select period based on duration
        data = cm.ph.getAllItemsBeetwenMarkers(data,
                                               "<AdaptationSet",
                                               '</AdaptationSet>',
                                               withMarkers=True)
        for item in data:
            type = ''
            if re.compile('''=['"]audio['"/]''').search(item):
                type = 'audio'
            elif re.compile('''=['"]video['"/]''').search(item):
                type = 'video'
            else:
                continue
            tmp = cm.ph.getAllItemsBeetwenMarkers(item,
                                                  '<Representation',
                                                  '>',
                                                  withMarkers=True)
            for rep in tmp:
                repParam = {}
                repParam['bandwidth'] = _getNumAttrib(rep, 'bandwidth')

                repParam['codecs'] = cm.ph.getSearchGroups(
                    rep, '''codecs=['"]([^'^"]+?)['"]''')[0]
                if '' == repParam['codecs']:
                    repParam['codecs'] = cm.ph.getSearchGroups(
                        item, '''codecs=['"]([^'^"]+?)['"]''')[0]

                repParam['codecs'] = repParam['codecs'].split('.')[0]
                if 'vp9' in repParam['codecs']:
                    continue

                if type == 'video':
                    repParam['width'] = _getNumAttrib(rep, 'width')
                    if 0 == repParam['width']:
                        repParam['width'] = _getNumAttrib(item, 'width')

                    repParam['height'] = _getNumAttrib(rep, 'height')
                    if 0 == repParam['height']:
                        repParam['height'] = _getNumAttrib(item, 'height')

                    repParam['frame_rate'] = cm.ph.getSearchGroups(
                        rep, '''frameRate=['"]([^'^"]+?)['"]''')[0]
                    if '' == repParam['frame_rate']:
                        repParam['frame_rate'] = cm.ph.getSearchGroups(
                            item, '''frameRate=['"]([^'^"]+?)['"]''')[0]
                else:
                    repParam['lang'] = cm.ph.getSearchGroups(
                        rep, '''lang=['"]([^'^"]+?)['"]''')[0]
                    if '' == repParam['lang']:
                        repParam['lang'] = cm.ph.getSearchGroups(
                            item, '''lang=['"]([^'^"]+?)['"]''')[0]

                representation[type].append(repParam)

        audioIdx = 0
        for audio in representation['audio']:
            audioItem = {}
            audioItem['livestream'] = liveStreamDetected
            audioItem['codecs'] = audio['codecs']
            audioItem['bandwidth'] = audio['bandwidth']
            audioItem['lang'] = audio['lang']
            audioItem['audio_rep_idx'] = audioIdx

            if len(representation['video']):
                videoIdx = 0
                for video in representation['video']:
                    videoItem = dict(audioItem)
                    videoItem['codecs'] += ',' + video['codecs']
                    videoItem['bandwidth'] += video['bandwidth']
                    videoItem['width'] = video['width']
                    videoItem['height'] = video['height']
                    videoItem['frame_rate'] = video['frame_rate']

                    videoItem['name']  = "[%s] bitrate: %s %dx%d %s %sfps" % ( videoItem['lang'],      \
                                                                               videoItem['bandwidth'], \
                                                                               videoItem['width'],     \
                                                                               videoItem['height'],    \
                                                                               videoItem['codecs'],    \
                                                                               videoItem['frame_rate'])
                    videoItem['url'] = strwithmeta(
                        manifestUrl, {
                            'iptv_proto': 'mpd',
                            'iptv_audio_rep_idx': audioIdx,
                            'iptv_video_rep_idx': videoIdx,
                            'iptv_livestream': videoItem['livestream']
                        })
                    retPlaylists.append(videoItem)
                    videoIdx += 1
            else:
                audioItem['name']  = "[%s] bandwidth: %s %s" % ( audioItem['lang'],      \
                                                                 audioItem['bandwidth'], \
                                                                 audioItem['codecs'])
                audioItem['url'] = strwithmeta(
                    manifestUrl, {
                        'iptv_proto': 'mpd',
                        'iptv_audio_rep_idx': audioIdx,
                        'iptv_livestream': audioItem['livestream']
                    })
                retPlaylists.append(audioItem)

            audioIdx += 1

    if sortWithMaxBandwidth > -1:

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

        retPlaylists = CSelOneLink(retPlaylists, __getLinkQuality,
                                   sortWithMaxBandwidth).getSortedLinks()

    return retPlaylists
示例#16
0
    def getLinksForVideo(self, cItem):
        printDBG("QuesttvCoUK.getLinksForVideo [%s]" % cItem)
        urlTab = []
        mp4Tab = []
        hlsTab = []

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

            videoId = self.cm.ph.getSearchGroups(
                data, '''data\-videoid=['"]([^'^"]+?)['"]''')[0]
            if videoId == '': return ''

            getParams = {}
            data = self.cm.ph.getDataBeetwenMarkers(data, '<object',
                                                    '</object>')[1]
            data = self.cm.ph.getAllItemsBeetwenMarkers(data, '<param', '>')
            for item in data:
                name = self.cm.ph.getSearchGroups(
                    item, '''name=['"]([^'^"]+?)['"]''')[0]
                if name not in ['playerID', '@videoPlayer', 'playerKey']:
                    continue
                value = self.cm.ph.getSearchGroups(
                    item, '''value=['"]([^'^"]+?)['"]''')[0]
                getParams[name] = value

            url = 'http://c.brightcove.com/services/viewer/htmlFederated?' + urllib.urlencode(
                getParams)
            sts, data = self.getPage(url)
            if sts:
                data = self.cm.ph.getDataBeetwenMarkers(
                    data, '"renditions":', ']', False)[1]
                try:
                    printDBG(data)
                    data = byteify(json.loads(data + ']'), '', True)
                    for item in data:
                        if item['videoCodec'] != 'H264': continue
                        url = item['defaultURL']
                        if not self.cm.isValidUrl(url): continue
                        name = '[mp4] bitrate: %s, %sx%s' % (
                            item['encodingRate'], item['frameWidth'],
                            item['frameHeight'])
                        mp4Tab.append({
                            'name': name,
                            'url': url,
                            'bitrate': item['encodingRate']
                        })

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

                        mp4Tab = CSelOneLink(mp4Tab, __getLinkQuality,
                                             999999999).getSortedLinks()
                except Exception:
                    printExc()

        hlsUrl = 'http://c.brightcove.com/services/mobile/streaming/index/master.m3u8?videoId=' + videoId
        hlsTab = getDirectM3U8Playlist(hlsUrl,
                                       checkContent=True,
                                       sortWithMaxBitrate=999999999)
        for idx in range(len(hlsTab)):
            hlsTab[idx]['name'] = '[hls] ' + hlsTab[idx]['name'].replace(
                'None', '').strip()

        urlTab.extend(mp4Tab)
        urlTab.extend(hlsTab)
        return urlTab
示例#17
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
示例#18
0
    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
示例#19
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
    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 = iptv_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
示例#21
0
def getDirectM3U8Playlist(M3U8Url,
                          checkExt=True,
                          variantCheck=True,
                          cookieParams={},
                          checkContent=False,
                          sortWithMaxBitrate=-1):
    if checkExt and not M3U8Url.split('?', 1)[0].endswith('.m3u8'):
        return []

    cm = common()
    meta = strwithmeta(M3U8Url).meta
    params, postData = cm.getParamsFromUrlWithMeta(M3U8Url)
    params.update(cookieParams)

    retPlaylists = []
    try:
        finallM3U8Url = meta.get('iptv_m3u8_custom_base_link', '')
        if '' == finallM3U8Url:
            params['with_metadata'] = True
            sts, data = cm.getPage(M3U8Url, params, postData)
            finallM3U8Url = data.meta['url']
        else:
            sts, data = cm.getPage(M3U8Url, params, postData)
            data = data.strip()

        m3u8Obj = m3u8.inits(data, finallM3U8Url)
        if m3u8Obj.is_variant:
            for playlist in m3u8Obj.playlists:
                item = {}
                if not variantCheck or playlist.absolute_uri.split(
                        '?')[-1].endswith('.m3u8'):
                    meta.update({
                        'iptv_proto': 'm3u8',
                        'iptv_bitrate': playlist.stream_info.bandwidth
                    })
                    item['url'] = strwithmeta(playlist.absolute_uri, meta)
                else:
                    meta.pop('iptv_proto', None)
                    item['url'] = decorateUrl(playlist.absolute_uri, meta)

                item['bitrate'] = playlist.stream_info.bandwidth
                if None != playlist.stream_info.resolution:
                    item['with'] = playlist.stream_info.resolution[0]
                    item['heigth'] = playlist.stream_info.resolution[1]
                else:
                    item['with'] = 0
                    item['heigth'] = 0

                item['width'] = item['with']
                item['height'] = item['heigth']
                try:
                    tmpCodecs = playlist.stream_info.codecs.split(',')
                    codecs = []
                    for c in tmpCodecs[::-1]:
                        codecs.append(c.split('.')[0].strip())
                        item['codecs'] = ','.join(codecs)
                except Exception:
                    item['codecs'] = None

                item['name']  = "bitrate: %s res: %dx%d %s" % ( item['bitrate'], \
                                                                item['width'],    \
                                                                item['height'],  \
                                                                item['codecs'] )
                retPlaylists.append(item)

            if sortWithMaxBitrate > -1:

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

                retPlaylists = CSelOneLink(
                    retPlaylists, __getLinkQuality,
                    sortWithMaxBitrate).getSortedLinks()
        else:
            if checkContent and 0 == len(m3u8Obj.segments):
                return []
            item = {
                'name': 'm3u8',
                'url': M3U8Url,
                'codec': 'unknown',
                'with': 0,
                'heigth': 0,
                'width': 0,
                'height': 0,
                'bitrate': 'unknown'
            }
            retPlaylists.append(item)
    except Exception:
        printExc()
    return retPlaylists
    def getVideoLink(self, cItem):
        printDBG("VideoStarApi.getVideoLink")
        urlsTab = []
        
        idx = cItem.get('priv_idx', -1)
        if idx < 0 or idx >= len(self.cacheChannelList):
            return urlsTab
            
        vidItem = self.cacheChannelList[idx]
        formatId = config.plugins.iptvplayer.videostar_streamprotocol.value
        tries = 0
        while True:
            tries += 1
            try:
                if self.loggedIn:
                    url = 'v1/channel/%s?format_id=%s&device_type=web' % (vidItem['id'], formatId)
                else:
                    url = 'v1/guest/channel/%s?format_id=%s&device_type=web' % (vidItem['id'], formatId)
                url = self.getFullUrl(url, 'api')
                sts, data = self.cm.getPage(url, self.defaultParams)
                printDBG(data)
                if not sts and not self.loggedIn and tries == 1:
                    rm(self.COOKIE_FILE)
                    self.doLogin('guest', 'guest')
                    sts, data = self.cm.getPage(self.getFullUrl('/static/guest/channels/list/web.json', 'static'), self.defaultParams)
                    if sts: continue
                
                if not sts: break
                data = byteify(json.loads(data))
                if data['data'] != None:
                    for item in data['data']['stream_channel']['streams']:
                        if formatId == '2':
                            if 'hls' in item['type']:
                                hslUrl = item['url'][0] # add here random
                                urlsTab.extend(getDirectM3U8Playlist(hslUrl, checkExt=False, cookieParams=self.defaultParams, checkContent=True))
                        elif formatId in ['3', '4']:
                            if 'dash' in item['type']:
                                dashUrl = item['url'][0] # add here random
                                urlsTab.extend(getMPDLinksWithMeta(dashUrl, checkExt=False, cookieParams=self.defaultParams))
                elif data['_meta'] != None:
                    info = data['_meta']['error']['info']
                    message = []
                    message.append('Oglądasz już kanał %s na urządeniu %s o adresie: %s.' % (info['channel_name'], info['device'], info['user_ip']))
                    message.append('W WP Pilocie nie możesz oglądać większej liczby kanałów jednocześnie.')
                    message.append('Czy chcesz kontynować tutaj?')
                    arg1 = self.sessionEx.waitForFinishOpen(MessageBox, '\n'.join(message), type = MessageBox.TYPE_YESNO)
                    if arg1:
                        url = self.getFullUrl('v1/channels/close', 'api')
                        paramsUrl = dict(self.defaultParams)
                        paramsUrl['header'] = dict(paramsUrl['header'])
                        paramsUrl['header']['Referer'] = self.getFullUrl('tv')
                        paramsUrl['header']['Origin'] = self.MAIN_URL[:-1]
                        paramsUrl['header']['content-type'] = 'application/json;charset=UTF-8'
                        paramsUrl['raw_post_data'] = True
                        sts, data = self.cm.getPage(url, paramsUrl, '{"channelId":"%s","t":"%s"}' % (info['channel_id'], self.userToken))
                        printDBG("==================== token1[%s] token2[%s]" % (self.userToken, info['stream_token']))
                        printDBG(data)
                        printDBG("====================")
                        continue

            except Exception:
                printExc()
            break
        
        if len(urlsTab):
            cookieHeader = self.cm.getCookieHeader(self.COOKIE_FILE)
            for idx in range(len(urlsTab)):
                urlsTab[idx]['url'] = strwithmeta(urlsTab[idx]['url'], {'Cookie':cookieHeader, 'User-Agent':self.USER_AGENT})
        
        if len(urlsTab):
            maxBitrate = int(config.plugins.iptvplayer.videostar_defquality.value) * 1.3
            def __getLinkQuality( itemLink ):
                try:
                    if 'bitrate' in itemLink:
                        return int(itemLink['bitrate'])
                    elif 'bandwidth' in itemLink:
                        return int(itemLink['bandwidth'])
                except Exception:
                    printExc()
                return 0
            
            oneLink = CSelOneLink(urlsTab, __getLinkQuality, maxBitrate)
            urlsTab = oneLink.getSortedLinks()
            if config.plugins.iptvplayer.videostar_use_defquality.value:
                urlsTab = [urlsTab[0]]
        
        return urlsTab
示例#23
0
def getF4MLinksWithMeta(manifestUrl,
                        checkExt=True,
                        cookieParams={},
                        sortWithMaxBitrate=-1):
    if checkExt and not manifestUrl.split('?')[0].endswith('.f4m'):
        return []

    cm = common()
    headerParams, postData = cm.getParamsFromUrlWithMeta(manifestUrl)
    headerParams.update(cookieParams)

    retPlaylists = []
    sts, data = cm.getPage(manifestUrl, headerParams, postData)
    if sts:
        liveStreamDetected = False
        if 'live' == CParsingHelper.getDataBeetwenMarkers(
                '<streamType>', '</streamType>', False):
            liveStreamDetected = True

        tmp = cm.ph.getDataBeetwenMarkers(data, '<manifest', '</manifest>')[1]
        baseUrl = cm.ph.getDataBeetwenReMarkers(tmp,
                                                re.compile('<baseURL[^>]*?>'),
                                                re.compile('</baseURL>'),
                                                False)[1].strip()
        printDBG(
            "|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| "
            + baseUrl)
        if baseUrl == '': baseUrl = manifestUrl
        tmp = cm.ph.getAllItemsBeetwenMarkers(tmp, '<media', '>')
        for item in tmp:
            link = cm.ph.getSearchGroups(item, '''href=['"]([^'^"]+)['"]''')[0]
            if link != '': link = urljoin(baseUrl, link)
            if cm.isValidUrl(link):
                try:
                    bitrate = int(
                        cm.ph.getSearchGroups(
                            item, '''bitrate=['"]([^'^"]+)['"]''')[0])
                except Exception:
                    bitrate = 0
                retPlaylists.append({
                    'name': '[f4m/hds] bitrate[%s]' % bitrate,
                    'bitrate': bitrate,
                    'url': link
                })

        if 0 == len(retPlaylists):
            bitrates = re.compile('bitrate="([0-9]+?)"').findall(data)
            for item in bitrates:
                link = strwithmeta(manifestUrl, {
                    'iptv_proto': 'f4m',
                    'iptv_bitrate': item
                })
                if liveStreamDetected:
                    link.meta['iptv_livestream'] = True
                try:
                    bitrate = int(item)
                except Exception:
                    bitrate = 0
                retPlaylists.append({
                    'name': '[f4m/hds] bitrate[%s]' % item,
                    'bitrate': bitrate,
                    'url': link
                })

        if 0 == len(retPlaylists):
            link = strwithmeta(manifestUrl, {'iptv_proto': 'f4m'})
            if liveStreamDetected:
                link.meta['iptv_livestream'] = True
            retPlaylists.append({
                'name': '[f4m/hds]',
                'bitrate': 0,
                'url': link
            })

        if sortWithMaxBitrate > -1:

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

            retPlaylists = CSelOneLink(retPlaylists, __getLinkQuality,
                                       sortWithMaxBitrate).getSortedLinks()
    return retPlaylists
示例#24
0
    def getVideoLinks(self, videoUrl):
        printDBG("KissCartoonMe.getVideoLinks [%s]" % videoUrl)
        urlTab = []

        referer = strwithmeta(videoUrl).meta.get('Referer', videoUrl)
        params = dict(self.defaultParams)
        params['header'] = dict(params['header'])
        params['header']['Referer'] = referer
        params['return_data'] = False

        try:
            sts, response = self.getPage(videoUrl, params)
            videoUrl = response.geturl()
            response.close()
        except Exception:
            printExc()
            return urlTab

        if 'kisscartoon' not in self.up.getDomain(videoUrl):
            return self.up.getVideoLinkExt(videoUrl)

        params.update({'return_data': True})
        sts, data = self.getPage(videoUrl, params)
        if not sts: return urlTab

        try:
            data = byteify(json.loads(data))
            printDBG(data)
            for item in data['playlist'][0].get('sources', []):
                if 'mp4' not in item['type']: continue
                url = item['file']
                name = item['label']
                urlTab.append({'name': name, 'url': url, 'need_resolve': 0})

            for item in data['playlist']:
                url = item.get('file', '')
                type = url.split('?', 1)[0].rsplit('.', 1)[-1].lower()
                if self.cm.isValidUrl(url):
                    if type == 'mp4':
                        name = item.get('label', 'mp4')
                        urlTab.append({
                            'name': name,
                            'url': url,
                            'need_resolve': 0
                        })
                    else:
                        urlTab.extend(
                            getDirectM3U8Playlist(url, checkContent=True))
        except Exception:
            printExc()

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

            def __getLinkQuality(itemLink):
                try:
                    return int(
                        self.cm.ph.getSearchGroups(
                            '|' + itemLink['name'] + '|',
                            '[^0-9]([0-9]+?)[^0-9]')[0])
                except Exception:
                    return 0

            urlTab = CSelOneLink(urlTab, __getLinkQuality,
                                 max_bitrate).getBestSortedList()
        return urlTab
    def getLinksForVideo(self, cItem):
        printDBG("FokusTV.getLinksForVideo [%s]" % cItem)
        urlTab = []

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

        if url.endswith('/player'):
            tab = ['fokustv-p/stream1']
            data = self.cm.ph.getDataBeetwenMarkers(data,
                                                    '$.post(',
                                                    'function',
                                                    withMarkers=False)[1]
            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)

            for streamUri in tab:
                sts, url = self.getPage(secureUri,
                                        post_data={'streamUri': streamUri})
                if not sts: continue

                if self.cm.isValidUrl(url):
                    data = getDirectM3U8Playlist(url,
                                                 checkExt=True,
                                                 checkContent=True)
                    for item in data:
                        item['url'] = strwithmeta(item['url'], {
                            'iptv_proto': 'm3u8',
                            'iptv_livestream': True
                        })
                        urlTab.append(item)
        else:
            data = self.cm.ph.getDataBeetwenMarkers(data, '<video',
                                                    '</video>')[1]
            data = self.cm.ph.getAllItemsBeetwenMarkers(
                data, '<source ', '>', False, False)
            for item in data:
                url = self.cm.ph.getSearchGroups(
                    item,
                    '''src=['"]([^"^']+?)['"]''')[0].replace('&amp;', '&')
                if url.startswith('//'):
                    url = 'http:' + url
                if not url.startswith('http'):
                    continue

                if 'video/mp4' in item:
                    type = self.cm.ph.getSearchGroups(
                        item, '''type=['"]([^"^']+?)['"]''')[0]
                    res = self.cm.ph.getSearchGroups(
                        item, '''res=['"]([^"^']+?)['"]''')[0]
                    label = self.cm.ph.getSearchGroups(
                        item, '''label=['"]([^"^']+?)['"]''')[0]
                    if label == '': label = res
                    if label == '': label = type
                    url = strwithmeta(url, {
                        'Referer': cItem['url'],
                        'User-Agent': self.USER_AGENT
                    })
                    urlTab.append({'name': '{0}'.format(label), 'url': url})
                elif 'mpegurl' in item:
                    url = strwithmeta(
                        url, {
                            'iptv_proto': 'm3u8',
                            'Referer': cItem['url'],
                            'Origin': self.up.getDomain(cItem['url'], False),
                            'User-Agent': self.USER_AGENT
                        })
                    tmpTab = getDirectM3U8Playlist(url,
                                                   checkExt=True,
                                                   checkContent=True)
                    for idx in range(len(tmpTab)):
                        tmpTab[idx]['url'].meta['iptv_proto'] = 'm3u8'
                    urlTab.extend(tmpTab)

        if 1 < len(urlTab):
            maxQuality = int(
                config.plugins.iptvplayer.fokustv_format.value) + 20

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

            oneLink = CSelOneLink(urlTab, __getLinkQuality, maxQuality)
            if config.plugins.iptvplayer.fokustv_df.value:
                urlTab = oneLink.getOneLink()
            else:
                urlTab = oneLink.getSortedLinks()

        return urlTab
    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