Beispiel #1
0
 def converFileToUtf8(self, inFile, outFile, lang=''):
     printDBG('CBaseSubProviderClass.converFileToUtf8 inFile[%s] outFile[%s]' % (inFile, outFile))
     # detect encoding
     encoding = ''
     cmd = '%s "%s"' % (GetUchardetPath(), inFile)
     ret = self.iptv_execute(cmd)
     if ret['sts'] and 0 == ret['code']:
         encoding = MapUcharEncoding(ret['data'])
         if 0 != ret['code'] or 'unknown' in encoding:
             encoding = ''
         else: encoding = encoding.strip()
     
     if lang == '':
         lang = GetDefaultLang() 
     
     if lang == 'pl' and encoding == 'iso-8859-2':
         encoding = GetPolishSubEncoding(tmpFile)
     elif '' == encoding:
         encoding = 'utf-8'
         
     # convert file to UTF-8
     try:
         with open(inFile) as f:
             data = f.read()
         try:
             data = data.decode(encoding).encode('UTF-8')
             if self.writeFile(outFile, data):
                 return True
         except Exception:
             printExc()
             SetIPTVPlayerLastHostError(_('Failed to convert the file "%s" to UTF-8.') % inFile)
     except Exception:
         printExc()
         SetIPTVPlayerLastHostError(_('Failed to open the file "%s".') % inFile)
     return False
    def processCaptcha(self, key):
        post_data = None
        token = ''
        iteration = 0
        reCaptchaUrl = 'https://www.google.com/recaptcha/api/noscript?k=%s' % (key)
        while iteration < 20:
            sts, data = self.cm.getPage(reCaptchaUrl, {'header':self.HTTP_HEADER, 'raw_post_data':True}, post_data=post_data)
            if not sts: 
                SetIPTVPlayerLastHostError(_('Fail to get "%s".') % reCaptchaUrl)
                return ''
        
            imgUrl = self.cm.ph.getSearchGroups(data, 'src="(image[^"]+?)"')[0]
            iteration += 1
            message = self.cm.ph.getSearchGroups(data, '<p[^>]*>([^<]+?)</p>')[0]
            token = self.cm.ph.getSearchGroups(data, '<textarea[^>]*>([^<]+?)</textarea>')[0]
            if '' != token: 
                printDBG('>>>>>>>> Captcha token[%s]' % (token))
                break
            elif message == '':
                printDBG('>>>>>>>> Captcha Failed')
                break

            recaptcha_challenge_field = self.cm.ph.getSearchGroups(data, 'name="recaptcha_challenge_field"[^>]+?value="([^"]+)"')[0]
            imgUrl = 'https://www.google.com/recaptcha/api/%s' % (imgUrl.replace('&amp;', '&'))
            message = clean_html(message)
            accepLabel = clean_html(self.cm.ph.getSearchGroups(data, 'type="submit"[^>]+?value="([^"]+)"')[0])
            
            filePath = GetTmpDir('.iptvplayer_captcha.jpg')
            printDBG(">>>>>>>> Captcha message[%s]" % (message))
            printDBG(">>>>>>>> Captcha accep label[%s]" % (accepLabel))
            printDBG(">>>>>>>> Captcha imgUrl[%s] filePath[%s]" % (imgUrl, filePath))
            
            params = {'maintype': 'image', 'subtypes':['jpeg'], 'check_first_bytes':['\xFF\xD8','\xFF\xD9']}
            ret = self.cm.saveWebFile(filePath, imgUrl, params)
            if not ret.get('sts'):
                SetIPTVPlayerLastHostError(_('Fail to get "%s".') % imgUrl)
                break
            
            params = deepcopy(IPTVMultipleInputBox.DEF_PARAMS)
            params['accep_label'] = _('Send')
            params['title'] = accepLabel
            params['list'] = []
            item = deepcopy(IPTVMultipleInputBox.DEF_INPUT_PARAMS)
            item['label_size'] = (300,57)
            item['input_size'] = (300,25)
            item['icon_path'] = filePath
            item['input']['text'] = ''
            params['list'].append(item)
            
            ret = 0
            retArg = self.sessionEx.waitForFinishOpen(IPTVMultipleInputBox, params)
            printDBG('>>>>>>>> Captcha response[%s]' % (retArg))
            if retArg is not None and len(retArg) and retArg[0]:
                recaptcha_response_field = retArg[0]
                printDBG('>>>>>>>> Captcha recaptcha_response_field[%s]' % (recaptcha_response_field))
                post_data = urllib.urlencode({'recaptcha_challenge_field': recaptcha_challenge_field, 'recaptcha_response_field':recaptcha_response_field, 'submit':accepLabel}, doseq=True)
            else:
                break
        
        return token
Beispiel #3
0
    def downloadAndUnpack(self, url, params={}, post_data=None, unpackToSubDir=False):
        data, fileName = self.downloadFileData(url, params, post_data)
        if data == None:
            return None
        ext = fileName.rsplit('.', 1)[-1].lower()
        printDBG("fileName[%s] ext[%s]" % (fileName, ext))
        if ext not in ['zip', 'rar']:
            SetIPTVPlayerLastHostError(_('Unknown file extension "%s".') % ext)
            return None
            
        tmpFile = GetTmpDir( self.TMP_FILE_NAME )
        tmpArchFile = tmpFile + '.' + ext
        tmpDIR = ''
        if unpackToSubDir:
            dirName = fileName.rsplit('.', 1)[0].split('filename=', 1)[-1]
            if dirName != '':
                tmpDIR = GetSubtitlesDir(dirName)
        
        if tmpDIR == '':
            tmpDIR = GetTmpDir(self.TMP_DIR_NAME)
        
        printDBG(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
        printDBG(fileName)
        printDBG(tmpFile)
        printDBG(tmpArchFile)
        printDBG(tmpDIR)
        printDBG(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")

        if not self.writeFile(tmpArchFile, data):
            return None
        
        if not self.unpackArchive(tmpArchFile, tmpDIR):
            rm(tmpArchFile)
            return None
        return tmpDIR
Beispiel #4
0
    def getVideoLinks(self, videoUrl):
        printDBG("CineTO.getVideoLinks [%s]" % videoUrl)
        videoUrl = strwithmeta(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

        sts, data = self.getPage(videoUrl)
        if sts:
            videoUrl = data.meta['url']
            urlTab = self.up.getVideoLinkExt(videoUrl)
            if 0 == len(urlTab) and 'gcaptchaSetup' in data:
                SetIPTVPlayerLastHostError(
                    _('Link protected with google recaptcha v2.'))
        else:
            urlTab = self.up.getVideoLinkExt(videoUrl)

        return urlTab
Beispiel #5
0
    def listItems(self, cItem, nextCategory):
        printDBG("MaxtvGO.listItems [%s]" % cItem)

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

        article = self.getArticleContent(cItem, data)
        if len(article):
            title = article[0]['title']
            icon = article[0]['images'][0]['url']
            params = dict(cItem)
            params.update({'good_for_fav': True, 'title': title, 'icon': icon})
            self.addVideo(params)

        cookieHeader = self.cm.getCookieHeader(self.COOKIE_FILE)
        catsTitle = ''
        data = self.cm.ph.getDataBeetwenNodes(data,
                                              ('<div', '>', 'slajder_film'),
                                              ('<div', '>', 'chat_round'))[1]
        data = re.compile('(<h3[^>]*?>[^>]*?</[^>]*?>)').split(data)
        for catData in data:
            if catData.startswith('<h3'):
                catsTitle = self.cleanHtmlStr(catData)
            tmp = self.cm.ph.getAllItemsBeetwenMarkers(catData, '<a', '</a>')
            for item in tmp:
                url = self.getFullUrl(
                    self.cm.ph.getSearchGroups(
                        item, '''href=['"]([^'^"]+?)['"]''')[0])
                icon = self.getFullIconUrl(
                    self.cm.ph.getSearchGroups(
                        item, '''src=['"]([^'^"]+?)['"]''')[0])
                icon = strwithmeta(
                    icon, {
                        'Cookie': cookieHeader,
                        'User-Agent': self.USER_AGENT,
                        'Referer': cItem['url']
                    })
                title = self.cleanHtmlStr(
                    self.cm.ph.getSearchGroups(
                        item, '''alt=['"]([^'^"]+?)['"]''')[0])
                if title == '':
                    title = catsTitle + ' ' + self.cleanHtmlStr(
                        icon.split('/')[-1].split('.', 1)[0].replace(
                            'small', ''))
                # 'category':nextCategory,
                params = dict(cItem)
                params.update({
                    'good_for_fav': True,
                    'title': title,
                    'url': url,
                    'icon': icon
                })
                self.addVideo(params)

        if self.loggedIn != True and 0 == len(self.currList):
            msg = _(
                'The host %s requires registration. \nPlease fill your login and password in the host configuration. Available under blue button.'
                % self.getMainUrl())
            GetIPTVNotify().push(msg, 'error', 10)
            SetIPTVPlayerLastHostError(msg)
Beispiel #6
0
 def unpackZipArchive(self, tmpFile, tmpDIR):
     errorCode = 0 
     # check if archive is not evil
     cmd = "unzip -l '{0}' 2>&1 ".format(tmpFile)
     ret = self.iptv_execute(cmd)
     if not ret['sts'] or 0 != ret['code']:
         errorCode = ret['code']
         if errorCode == 0: errorCode = 9
     elif '..' in ret['data']:
         errorCode = 9
     
     # if archive is valid then upack it
     if errorCode == 0:
         cmd = "unzip -o '{0}' -d '{1}' 2>/dev/null".format(tmpFile, tmpDIR)
         ret = self.iptv_execute(cmd)
         if not ret['sts'] or 0 != ret['code']:
             errorCode = ret['code']
             if errorCode == 0: errorCode = 9
     
     if errorCode != 0:
         message = _('Unzip error code[%s].') % errorCode
         if str(errorCode) == str(127):
             message += '\n' + _('It seems that unzip utility is not installed.')
         elif str(errorCode) == str(9):
             message += '\n' + _('Wrong format of zip archive.')
         SetIPTVPlayerLastHostError(message)
         return False
     
     return True
Beispiel #7
0
    def getVideoLinks(self, videoUrl):
        printDBG("HDStreams.getVideoLinks [%s]" % videoUrl)
        meta = strwithmeta(videoUrl).meta
        linksKey = meta.get('links_key', '')
        post_data = meta.get('post_data', {})

        for idx in range(len(self.cacheLinks[linksKey])):
            if self.cacheLinks[linksKey][idx]['url'].meta[
                    'links_key'] == linksKey:
                tmp_post = self.cacheLinks[linksKey][idx]['url'].meta.get(
                    'post_data', {})
                if tmp_post == post_data:
                    if not self.cacheLinks[linksKey][idx]['name'].startswith(
                            '*'):
                        self.cacheLinks[linksKey][idx][
                            'name'] = '*' + self.cacheLinks[linksKey][idx][
                                'name']
                    break

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

        urlParams = dict(self.defaultParams)
        urlParams['header'] = dict(self.AJAX_HEADER)
        urlParams['header']['Referer'] = videoUrl
        urlParams['header']['x-csrf-token'] = self.cm.ph.getSearchGroups(
            data, '''<[^>]+?csrf-token[^>]+?content=['"]([^'^"]+?)['"]''')[0]
        urlParams['header']['x-xsrf-token'] = self.cm.getCookieItem(
            self.COOKIE_FILE, 'XSRF-TOKEN')
        urlParams['header']['x-requested-with'] = 'XMLHttpRequest'
        urlParams['ignore_http_code_ranges'] = [(401, 401)]

        sts, data = self.getPage(videoUrl + '/stream', urlParams, post_data)
        if not sts: return []

        if 'captcha' in data.lower():
            SetIPTVPlayerLastHostError(
                _('Link protected with google recaptcha v2.'))

        try:
            printDBG(data)
            tmp = byteify(json.loads(data))['s']
            if '{' not in tmp: tmp = base64.b64decode(tmp)
            tmp = byteify(json.loads(tmp))
            printDBG(tmp)
            ciphertext = base64.b64decode(tmp['ct'][::-1])
            iv = unhexlify(tmp['iv'])
            salt = unhexlify(tmp['s'])
            b = urlParams['header'][
                'x-csrf-token']  #urlParams['header']['User-Agent']
            tmp = self.cryptoJS_AES_decrypt(ciphertext, base64.b64encode(b),
                                            salt)
            printDBG(tmp)
            tmp = byteify(json.loads(tmp))
            videoUrl = tmp
        except Exception:
            printExc()

        return self.up.getVideoLinkExt(videoUrl)
Beispiel #8
0
 def __call__(self, *args, **kwargs):
     SetIPTVPlayerLastHostError()
     self.Thread = threading.Thread(target=self.run,
                                    name=self.Callable.__name__,
                                    args=args,
                                    kwargs=kwargs)
     self.Thread.start()
     return self
Beispiel #9
0
 def writeFile(self, filePath, data):
     printDBG('CBaseSubProviderClass.writeFile path[%s]' % filePath)
     try:
         with open(filePath, 'w') as f:
             f.write(data)
         return True
     except Exception:
         printExc()
         SetIPTVPlayerLastHostError(_('Failed to write file "%s".') % filePath)
     return False
Beispiel #10
0
 def getPage(self, url, params={}, post_data=None):
     if params == {}: params = dict(self.defaultParams)
     sts, data = self.cm.getPage(url, params, post_data)
     if sts and data.meta.get('status_code', 0) in [410, 404] and 'captcha' in data:
         errorMsg = [_('Link protected with google recaptcha v2.')]
         errorMsg.append(_("Please visit \"%s\" and confirm that you are human." % self.getMainUrl()))
         if not self.loggedIn: errorMsg.append(_('Please register and set login and password in the host configuration, to solve this problems permanently.'))
         errorMsg = '\n'.join(errorMsg)
         GetIPTVNotify().push(errorMsg, 'info', 10)
         SetIPTVPlayerLastHostError(errorMsg)
     return sts, data
    def getVideoLinks(self, videoUrl):
        printDBG("SerienStreamTo.getVideoLinks [%s]" % videoUrl)
        urlTab = []
        videoUrl = strwithmeta(videoUrl)
        key = videoUrl.meta.get('base_url', '')
        if key != '' and key in self.cacheLinks:
            for idx in range(len(self.cacheLinks[key])):
                if self.cacheLinks[key][idx]['url'] == videoUrl:
                    if not self.cacheLinks[key][idx]['name'].startswith('*'):
                        self.cacheLinks[key][idx][
                            'name'] = '*' + self.cacheLinks[key][idx]['name']

        if self.cm.isValidUrl(videoUrl):
            if 1 != self.up.checkHostSupport(videoUrl):
                params = dict(self.defaultParams)
                try:
                    params['return_data'] = False
                    params['no_redirection'] = True
                    tries = 0
                    tmpUrl = videoUrl
                    while tries < 3:
                        sts, response = self.getPage(videoUrl, params)
                        printDBG("+++++++++++")
                        printDBG(response.info())
                        printDBG("+++++++++++")
                        url = ''
                        for key in response.info():
                            if key.upper() == 'LOCATION':
                                url = response.info()[key]
                        response.close()
                        if not self.cm.isValidUrl(url):
                            break
                        videoUrl = url
                        tries += 1
                except Exception:
                    printExc()

            if 1 != self.up.checkHostSupport(videoUrl):
                sts, data = self.getPage(videoUrl)
                if sts and 'google.com/recaptcha/' in data and 'sitekey' in data:
                    message = _('Link protected with google recaptcha v2.')
                    if True != self.loggedIn:
                        message += '\n' + _(
                            'Please fill your login and password in the host configuration (available under blue button) and try again.'
                        )
                    else:
                        message += '\n' + self.cleanHtmlStr(
                            self.cm.ph.getDataBeetwenMarkers(
                                data, '<small', '</small>')[1])
                        message += '\n' + _('Please retry later.')
                    SetIPTVPlayerLastHostError(message)

            urlTab = self.up.getVideoLinkExt(videoUrl)
        return urlTab
    def _initialize_api(self, video_id):
        sts, data = self.cm.getPage('http://www.vevo.com/')
        if sts:
            oauth_token = self.cm.ph.getSearchGroups(
                data, '''"access_token":"([^"]+?)"''')[0]

        if 'THIS PAGE IS CURRENTLY UNAVAILABLE IN YOUR REGION' in data:
            SetIPTVPlayerLastHostError(
                _('%s said: This page is currently unavailable in your region')
                % self.IE_NAME)

        self._api_url_template = 'http://apiv2.vevo.com/%s?token=' + oauth_token
Beispiel #13
0
 def unpackArchive(self, tmpFile, tmpDIR):
     printDBG('CBaseSubProviderClass.unpackArchive tmpFile[%s], tmpDIR[%s]' % (tmpFile, tmpDIR))
     rmtree(tmpDIR, ignore_errors=True)
     if not mkdirs(tmpDIR):
         SetIPTVPlayerLastHostError(_('Failed to create directory "%s".') % tmpDIR)
         return False
     if tmpFile.endswith('.zip'):
         return self.unpackZipArchive(tmpFile, tmpDIR)
     elif tmpFile.endswith('.rar'):
         cmd = "unrar e -o+ -y '{0}' '{1}' 2>/dev/null".format(tmpFile, tmpDIR)
         printDBG("cmd[%s]" % cmd)
         ret = self.iptv_execute(cmd)
         if not ret['sts'] or 0 != ret['code']:
             message = _('Unrar error code[%s].') % ret['code']
             if str(ret['code']) == str(127):
                 message += '\n' + _('It seems that unrar utility is not installed.')
             elif str(ret['code']) == str(9):
                 message += '\n' + _('Wrong format of rar archive.')
             SetIPTVPlayerLastHostError(message)
             return False
         return True
     return False
Beispiel #14
0
 def getLinksForVideo(self, cItem):
     printDBG("TVNowDE.getLinksForVideo [%s]" % cItem)
     retTab = []
     
     cacheTab = self.cacheLinks.get(cItem['url'], [])
     if len(cacheTab):
         return cacheTab
     
     urlDashClear = '' #cItem.get('dashclear', '')
     if not self.cm.isValidUrl(urlDashClear):
         try:
             seoUrlItem = cItem['f_seo_url_format']
             seoUrlFormat = cItem['f_seo_url_item']
             station = cItem['f_station']
             url = self.getFullUrl('/movies/{0}/{1}?fields=*,format,files,manifest,breakpoints,paymentPaytypes,trailers,packages&station={2}'.format(seoUrlItem, seoUrlFormat, station))
             sts, data = self.getPage(url)
             if not sts: return []
             try: data = byteify(json.loads(data))
             except Exception: data = 'error'
             
             if 'error' in data: data = cItem['orig_item']
             
             urlDashClear = data['manifest']['dashclear']
             if data.get('isDrm', False): 
                 SetIPTVPlayerLastHostError(_("Video with DRM protection."))
             if not self.cm.isValidUrl(urlDashClear): return []
         except Exception:
             printExc()
     
     if self.cm.isValidUrl(urlDashClear):
         urlHlsClear = urlDashClear.replace('/vodnowusodash.', '/vodnowusohls.').split('?', 1)
         urlHlsClear[0] = urlHlsClear[0][:-3] + 'm3u8'
         urlHlsClear = '?'.join(urlHlsClear)
         hlsTab  = getDirectM3U8Playlist(urlHlsClear, checkContent=True)
         dashTab = getMPDLinksWithMeta(urlDashClear, False)
         try:
             hlsTab  = sorted(hlsTab, key=lambda item: -1 * int(item.get('bitrate', 0)))
             dashTab = sorted(dashTab, key=lambda item: -1 * int(item.get('bandwidth', 0)))
         except Exception:
             printExc()
         if config.plugins.iptvplayer.tvnowde_prefered_format.value == 'hls':
             retTab.extend(hlsTab)
             retTab.extend(dashTab)
         else:
             retTab.extend(dashTab)
             retTab.extend(hlsTab)
     if len(retTab):
         self.cacheLinks[cItem['url']] = retTab
     
     return retTab
Beispiel #15
0
 def listVideoItems(self, cItem):
     printDBG("TVNowDE.listVideoItems [%s]" % cItem)
     page = cItem.get('page', 1)
     url  = cItem['url'] + '&page=%s' % page 
     fChannels = cItem.get('f_channels', [])
     
     sts, data = self.getPage(url)
     if not sts: return 
     try:
         data = byteify(json.loads(data))
         subKey = cItem.get('sub_key', '')
         if subKey != '': data = data[subKey]
         for item in data['items']:
             try:
                 if not config.plugins.iptvplayer.tvnowde_show_paid_items.value and not item.get('free', False): 
                     continue
                     
                 if not config.plugins.iptvplayer.tvnowde_show_drm_items.value and item.get('isDrm', False): 
                     SetIPTVPlayerLastHostError(_("Items with DRM protection."))
                     continue
                 
                 urlDashClear = item['manifest']['dashclear']
                 if not self.cm.isValidUrl(urlDashClear): continue
                 
                 station = self.getStr(item['format'], 'station')
                 if len(fChannels) and station not in fChannels: continue
                 
                 id = self.getStr(item, 'id')
                 icon = 'https://ais.tvnow.de/tvnow/movie/{0}/600x716/title.jpg'.format(id)
                 title    = self.getStr(item, 'title')
                 desc     = self.cleanHtmlStr(self.getStr(item, 'articleLong'))
                 seoUrlItem = self.getStr(item, 'seoUrl')
                 seoUrlFormat = self.getStr(item['format'], 'seoUrl')
                 
                 descTab = []
                 for d in [('broadcastStartDate', _('%s')), ('episode', _('episode: %s')), ('duration', _('duration: %s'))]:
                     t = self.getStr(item, d[0])
                     if t != '': descTab.append(d[1] % t)
                 if len(descTab):
                     desc = ' | '.join(descTab) + '[/br]' + desc
                 
                 url = '/%s/%s' % (seoUrlFormat, seoUrlItem)
                 params = {'good_for_fav':True, 'orig_item':item, 'dashclear':urlDashClear, 'f_seo_url_format':seoUrlFormat, 'f_seo_url_item':seoUrlItem, 'f_station':station, 'title':title, 'url':url, 'icon':icon, 'desc':desc}
                 self.addVideo(params)
             except Exception:
                 printExc()
     except Exception:
         printExc()
 def getLinksForVideo(self, cItem):
     printDBG("EFilmyTv.getLinksForVideo [%s]" % cItem)
     self.tryTologin()
     
     retTab = []
     cacheKey = cItem['url']
     cacheTab = self.cacheLinks.get(cacheKey, [])
     if len(cacheTab): return cacheTab
     
     sts, data = self.getPage(cItem['url'])
     if not sts: return []
     
     cUrl = data.meta['url']
     
     errorMessage = self.cleanHtmlStr(self.cm.ph.getDataBeetwenNodes(data, ('<div', '>', 'deleted'), ('<div', '>'))[1])
     SetIPTVPlayerLastHostError(errorMessage)
     
     data = self.cm.ph.getAllItemsBeetwenNodes(data, ('<span', '>', 'playername'), ('</div></div', '>'))
     printDBG(data)
     for item in data:
         movieId = self.cm.ph.getDataBeetwenNodes(item, ('<div', '>', 'play'), ('<div', '>'))[1]
         movieId = self.cm.ph.getSearchGroups(movieId, '''\sid=['"]([0-9]+?(?:_s)?)['"]''')[0]
         if movieId == '': continue
         if movieId.endswith('_s'): baseUrl = '/seriale.php'
         else: baseUrl = '/filmy.php'
         
         item = item.split('</div>', 1)
         name = self.cleanHtmlStr(item[0]).replace('Odtwarzacz', '').replace('Wersja', '')
         
         item = self.cm.ph.getAllItemsBeetwenMarkers(item[-1], '<input', '>')
         for it in item:
             val = self.cm.ph.getSearchGroups(it, '''\svalue=['"]([^'^"]+?)['"]''')[0]
             if 'bez' in val.lower(): 
                 if not self.loggedIn: continue
                 type = 'show_premium'
             else: 
                 type = 'show_player'
             url = self.getFullUrl(baseUrl + '?cmd=%s&id=%s' % (type, movieId), cUrl)
             retTab.append({'name':'%s - %s' % (name, val), 'url':strwithmeta(url, {'Referer':cUrl, 'f_type':type}), 'need_resolve':1})
     if len(retTab):
         self.cacheLinks[cacheKey] = retTab
     return retTab
 def getVideoLink(self, cItem):
     printDBG("WizjaTvApi.getVideoLink")
     urlsTab = []
     
     sts, data = self.cm.getPage(cItem['url'], self.http_params)
     if not sts: return urlsTab
     
     data = self.cm.ph.getAllItemsBeetwenMarkers(data, '<iframe', '>', caseSensitive=False)
     printDBG(data)
     for item in data:
         url = self.getFullUrl(self.cm.ph.getSearchGroups(item, '''src=['"]([^'^"]+?)['"]''')[0])
         if not self.cm.isValidUrl(url): continue
         HTTP_HEADER= dict(self.HTTP_HEADER)
         HTTP_HEADER.update( {'Referer':cItem['url']} )
         params = dict(self.http_params)
         params['header'] = HTTP_HEADER
         
         tries = 0
         while tries < 2:
             tries += 1
             
             if 'porter' in url or 'player' in item:
                 sts, tmp = self.cm.getPage(url, params)
                 if not sts: break
                 printDBG(tmp)
                 videoUrl = urllib.unquote(self.cm.ph.getSearchGroups(tmp, '''['"]?src['"]?\s*:\s*['"](rtmp[^'^"]+?)['"]''')[0])
                 killUrl  = self.getFullUrl(self.cm.ph.getSearchGroups(tmp, '''<a[^>]+?href=["']([^'^"]*?killme\.php[^'^"]*?)''')[0])
                 if videoUrl != '':
                     urlTab   = self.cm.ph.getSearchGroups(videoUrl, '''rtmp://([^/]+?)/([^/]+?)/([^/]+?)\?(.+?)&streamType''', 4)
                     rtmp = 'rtmp://' + urlTab[0] + '/' + urlTab[1] + '?' + urlTab[3] + \
                            ' playpath=' + urlTab[2] + '?' + urlTab[3] + \
                            ' app=' + urlTab[1] + '?' + urlTab[3] + \
                            ' swfVfy=1 flashVer=WIN\\2020,0,0,306 swfUrl=http://wizja.tv/player/StrobeMediaPlayback_v3.swf live=1 token=fake pageUrl=' + cItem['url']
                     urlsTab.append({'name':'rtmp', 'url':rtmp})
                 elif self.cm.isValidUrl(killUrl):
                     sts, tmp = self.cm.getPage(killUrl, params)
                     continue
                 SetIPTVPlayerLastHostError(self.cleanHtmlStr(tmp))
             break
     return urlsTab
 def getLinksForVideo(self, cItem):
     printDBG("MRPiracyGQ.getLinksForVideo [%s]" % cItem)
     urlTab = self.cacheLinks.get(cItem['url'], [])
     
     if len(urlTab): return urlTab
     
     sts, data = self.getPage(cItem['url'])
     if not sts: return urlTab
     
     trailerUrl = self.cm.ph.getSearchGroups(data, '''trailer\(\s*["'](https?://youtube.com/[^"^']+?)["']''')[0]
     
     tmp = self.cm.ph.getDataBeetwenMarkers(data, '<div id="deleted">', '</center>')[1]
     
     errorMsg = self.cleanHtmlStr(self.cm.ph.getDataBeetwenMarkers(tmp, '<h2', '</h2>')[1])
     errorMsg += ' ' + self.cleanHtmlStr(self.cm.ph.getDataBeetwenMarkers(tmp, '<p', '</p>')[1])
     SetIPTVPlayerLastHostError(errorMsg)
     
     token = self.cm.ph.getSearchGroups(data, '''var\s+form_data\s*=\s*['"]([^'^"]+?)['"]''')[0]
     jscode = []
     jscode.append(self.cm.ph.getDataBeetwenNodes(data, ('<script', '>'), ('</script', '>'), False)[1])
     tmp = self.cm.ph.getDataBeetwenNodes(data, ('<div', '>', 'server'), ('</script', '>'))[1]
     jscode.append(self.cm.ph.getDataBeetwenNodes(tmp, ('<script', '>'), ('</script', '>'), False)[1])
     jscode = '\n'.join(jscode)
     
     linksData = self.cm.ph.getAllItemsBeetwenNodes(data, ('<div', '>', 'buttonSv'), ('</div', '>'))
     dataObj = re.compile('''\sdata\-([^=]+?)=['"]([^'^"]+?)['"]''')
     for item in linksData:
         playerData = dict(dataObj.findall(item))
         name = self.cm.ph.getSearchGroups(item, '''src=["']([^"^']+?)["']''')[0].split('/')[-1].replace('.png', '').title()
         playerData['ref_url'] = cItem['url']
         url = '>' + '%s' % playerData
         playerData['jscode'] = jscode
         urlTab.append({'name':name, 'url':strwithmeta(url, playerData), 'need_resolve':1})
     
     if self.cm.isValidUrl(trailerUrl):
         urlTab.append({'name':_('Trailer'), 'url':trailerUrl, 'need_resolve':1})
     
     if len(urlTab):
         self.cacheLinks[cItem['url']] = urlTab
     return urlTab
Beispiel #19
0
    def getVideoLinks(self, videoUrl):
        printDBG("GamatoMovies.getVideoLinks [%s]" % videoUrl)
        urlTab = []

        # mark requested link as used one
        if len(self.cacheLinks.keys()):
            key = self.cacheLinks.keys()[0]
            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

        shortUri = videoUrl
        domain = self.up.getDomain(videoUrl)
        sts, data = self.cm.getPage(videoUrl)
        if sts and 'shorte.st/' in data:
            videoUrl = videoUrl.replace(domain, 'sh.st')
            domain = 'sh.st'

        if 'sh.st' in domain or 'viid.me' in domain or 'skiip.me' in domain or 'clkmein.com' in domain:
            from Plugins.Extensions.IPTVPlayer.libs.unshortenit import unshorten
            uri, sts = unshorten(videoUrl)
            videoUrl = str(uri)
            if not self.cm.isValidUrl(videoUrl):
                SetIPTVPlayerLastHostError(str(sts))
            else:
                # set resolved uri in cache
                if len(self.cacheLinks.keys()):
                    key = self.cacheLinks.keys()[0]
                    for idx in range(len(self.cacheLinks[key])):
                        if shortUri in self.cacheLinks[key][idx]['url']:
                            self.cacheLinks[key][idx]['url'] = videoUrl
                            break
        if self.cm.isValidUrl(videoUrl):
            return self.up.getVideoLinkExt(videoUrl)

        return urlTab
Beispiel #20
0
    def getPage(self, url, addParams={}, post_data=None):
        HTTP_HEADER = dict(self.HEADER)
        addParams = dict(addParams)
        addParams.update({'header': HTTP_HEADER})

        proxy = config.plugins.iptvplayer.zalukajtv_proxy.value
        if proxy != 'None':
            if proxy == 'proxy_1':
                proxy = config.plugins.iptvplayer.alternative_proxy1.value
            else:
                proxy = config.plugins.iptvplayer.alternative_proxy2.value
            addParams = dict(addParams)
            addParams.update({'http_proxy': proxy})

        sts, data = self.cm.getPage(url, addParams, post_data)
        if sts and None == data:
            sts = False
        if sts and 'Duze obciazenie!' in data:
            SetIPTVPlayerLastHostError(
                self.cleanHtmlStr(
                    re.compile('''<script.+?</script>''',
                               re.DOTALL).sub("", data)))
        return sts, data
 def getVideoLinks(self, videoUrl):
     printDBG("FilmPalastTo.getVideoLinks [%s]" % videoUrl)
     linksTab = []
     
     videoUrl = strwithmeta(videoUrl)
     
     key = videoUrl.meta.get('links_key', '')
     if key != '':
         if key in self.cacheLinks:
             for idx in range(len(self.cacheLinks[key])):
                 if self.cacheLinks[key][idx]['url'] == videoUrl and not self.cacheLinks[key][idx]['name'].startswith('*'):
                     self.cacheLinks[key][idx]['name'] = '*' + self.cacheLinks[key][idx]['name']
     
     data_id    = videoUrl.meta.get('data_id', '')
     data_stamp = videoUrl.meta.get('data_stamp', '')
     
     #sts, data = self.getPage(key, self.defaultParams)
     #if not sts: return []
     
     url = self.getFullUrl('/stream/%s/%s' % (data_id, data_stamp))
     urlParams = dict(self.defaultParams)
     urlParams['header'] = dict(self.AJAX_HEADER)
     urlParams['header']['Referer'] = key
     sts, data = self.getPage(url, urlParams, {'streamID':data_id})
     if not sts: return []
     
     try:
         data = byteify(json.loads(data))
         url = data.get('url', '')
         if self.cm.isValidUrl(url):
             return self.up.getVideoLinkExt(url)
         SetIPTVPlayerLastHostError(data['msg'])
     except Exception:
         printExc()
     
     return linksTab
    def getVideoLinks(self, videoUrl):
        printDBG("FilmezzEU.getVideoLinks [%s]" % videoUrl)
        videoUrl = strwithmeta(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

        url = videoUrl
        post_data = None
        while True:
            try:
                httpParams = dict(self.defaultParams)
                httpParams['return_data'] = False

                sts, response = self.cm.getPage(url, httpParams, post_data)
                videoUrl = response.geturl()
                response.close()
            except Exception:
                printExc()
                return []

            if self.up.getDomain(self.getMainUrl()) in videoUrl:
                sts, data = self.getPage(videoUrl)
                if not sts: return []

                if 'captcha' in data:
                    data = re.sub("<!--[\s\S]*?-->", "", data)

                if 'google.com/recaptcha/' in data and 'sitekey' in data:
                    message = _('Link protected with google recaptcha v2.')
                    if True != self.loggedIn:
                        message += '\n' + _(
                            'Please fill your login and password in the host configuration (available under blue button) and try again.'
                        )
                    SetIPTVPlayerLastHostError(message)
                    break
                elif '<input name="captcha"' in data:
                    data = self.cm.ph.getDataBeetwenMarkers(
                        data, '<div align="center">', '</form>')[1]
                    captchaTitle = self.cleanHtmlStr(
                        self.cm.ph.getDataBeetwenMarkers(data, '<h3',
                                                         '</h3>')[1])
                    captchaDesc = self.cleanHtmlStr(
                        self.cm.ph.getDataBeetwenMarkers(
                            data, '</h3>', '</span>')[1])

                    # parse form data
                    data = self.cm.ph.getDataBeetwenMarkers(
                        data, '<form', '</form>')[1]

                    imgUrl = self.cm.ph.getSearchGroups(
                        data, 'src="([^"]+?)"')[0]
                    if imgUrl != '': imgUrl = '/' + imgUrl
                    if imgUrl.startswith('/'):
                        imgUrl = urlparse.urljoin(videoUrl, imgUrl)

                    printDBG("img URL [%s]" % imgUrl)

                    actionUrl = self.cm.ph.getSearchGroups(
                        data, 'action="([^"]+?)"')[0]
                    if actionUrl != '': actionUrl = '/' + actionUrl
                    if actionUrl.startswith('/'):
                        actionUrl = urlparse.urljoin(videoUrl, actionUrl)
                    elif actionUrl == '':
                        actionUrl = videoUrl

                    captcha_post_data = dict(
                        re.findall(
                            r'''<input[^>]+?name=["']([^"^']*)["'][^>]+?value=["']([^"^']*)["'][^>]*>''',
                            data))

                    if self.cm.isValidUrl(imgUrl):
                        params = dict(self.defaultParams)
                        params['header'] = dict(params['header'])
                        params['header'][
                            'Accept'] = 'image/png,image/*;q=0.8,*/*;q=0.5'
                        params = dict(self.defaultParams)
                        params.update({
                            'maintype':
                            'image',
                            'subtypes': ['jpeg', 'png'],
                            'check_first_bytes':
                            ['\xFF\xD8', '\xFF\xD9', '\x89\x50\x4E\x47'],
                            'header':
                            params['header']
                        })
                        filePath = GetTmpDir('.iptvplayer_captcha.jpg')
                        ret = self.cm.saveWebFile(filePath,
                                                  imgUrl.replace('&amp;', '&'),
                                                  params)
                        if not ret.get('sts'):
                            SetIPTVPlayerLastHostError(
                                _('Fail to get "%s".') % imgUrl)
                            return urlTab

                        params = deepcopy(IPTVMultipleInputBox.DEF_PARAMS)
                        params['accep_label'] = _('Send')
                        params['title'] = captchaTitle
                        params['status_text'] = captchaDesc
                        params['with_accept_button'] = True
                        params['list'] = []
                        item = deepcopy(IPTVMultipleInputBox.DEF_INPUT_PARAMS)
                        item['label_size'] = (160, 75)
                        item['input_size'] = (480, 25)
                        item['icon_path'] = filePath
                        item['title'] = _('Answer')
                        item['input']['text'] = ''
                        params['list'].append(item)

                        ret = 0
                        retArg = self.sessionEx.waitForFinishOpen(
                            IPTVMultipleInputBox, params)
                        printDBG(retArg)
                        if retArg and len(retArg) and retArg[0]:
                            printDBG(retArg[0])
                            captcha_post_data['captcha'] = retArg[0][0]
                            post_data = captcha_post_data
                            url = actionUrl

                        if not sts:
                            return urlTab
                        else:
                            continue

                tmp = re.compile('''<iframe[^>]+?src=['"]([^"^']+?)['"]''',
                                 re.IGNORECASE).findall(data)
                for url in tmp:
                    if 1 == self.up.checkHostSupport(url):
                        videoUrl = url
                        break
            break

        if self.cm.isValidUrl(videoUrl):
            urlTab = self.up.getVideoLinkExt(videoUrl)

        return urlTab
Beispiel #23
0
    def tryTologin(self):
        printDBG('tryTologin start')
        
        if PlusDEDE.login == None and PlusDEDE.password == None:
            if self.readLoginMarker() == self.calcLoginMarker(config.plugins.iptvplayer.plusdede_login.value, config.plugins.iptvplayer.plusdede_password.value):
                PlusDEDE.login = config.plugins.iptvplayer.plusdede_login.value
                PlusDEDE.password = config.plugins.iptvplayer.plusdede_password.value
            else:
                PlusDEDE.password = ''
                PlusDEDE.login = ''
                rm(self.COOKIE_FILE)
        
        if True != self.loggedIn or PlusDEDE.login != config.plugins.iptvplayer.plusdede_login.value or\
            PlusDEDE.password != config.plugins.iptvplayer.plusdede_password.value:
            
            if True != self.loggedIn and PlusDEDE.login == config.plugins.iptvplayer.plusdede_login.value and\
                PlusDEDE.password == config.plugins.iptvplayer.plusdede_password.value:
                sts, data = self.getPage(self.getMainUrl())
                if sts:
                    token = self.cm.ph.getSearchGroups(data, '''(<meta[^>]+?_token[^>]+?/>)''')[0]
                    token = self.cm.ph.getSearchGroups(token, '''content=['"]([^"^']+?)['"]''')[0]
                    if '' != token and '/logout' in data:
                        self.HTTP_HEADER['X-CSRF-TOKEN'] = token
                        self.AJAX_HEADER['X-CSRF-TOKEN'] = token
                        self.loggedIn = True
                        return True
        
            PlusDEDE.login = config.plugins.iptvplayer.plusdede_login.value
            PlusDEDE.password = config.plugins.iptvplayer.plusdede_password.value
            self.saveLoginMarker()
            
            rm(self.COOKIE_FILE)
            
            self.loggedIn = False
            
            if '' == PlusDEDE.login.strip() or '' == PlusDEDE.password.strip():
                self.sessionEx.open(MessageBox, _('The host %s requires registration. \nPlease fill your login and password in the host configuration. Available under blue button.' % self.getMainUrl()), type = MessageBox.TYPE_ERROR, timeout = 10 )
                return False
            
            url = self.getFullUrl('/login?popup=1')
            sts, data = self.getPage(url)
            if not sts: return False
            
            sts, tmp = self.cm.ph.getDataBeetwenNodes(data, ('<form', '>'), ('</form', '>'))
            if not sts: return False
            
            actionUrl = self.getFullUrl(self.cm.ph.getSearchGroups(tmp, '''action=['"]([^'^"]+?)['"]''')[0])
            tmp = self.cm.ph.getAllItemsBeetwenMarkers(tmp, '<input', '>')
            post_data = {}
            for item in tmp:
                name  = self.cm.ph.getSearchGroups(item, '''name=['"]([^'^"]+?)['"]''')[0]
                value = self.cm.ph.getSearchGroups(item, '''value=['"]([^'^"]+?)['"]''')[0]
                post_data[name] = value
            
            post_data.update({'email':PlusDEDE.login, 'password':PlusDEDE.password})
            
            # fill captcha
            #############################################################################################
            imgUrl = self.getFullUrl(self.cm.ph.getSearchGroups(data, '''<img[^>]+?src=['"]([^"^']+?)['"]''')[0])
            if self.cm.isValidUrl(imgUrl):
                header = dict(self.HTTP_HEADER)
                header['Accept'] = 'image/png,image/*;q=0.8,*/*;q=0.5'
                params = dict(self.defaultParams)
                params.update( {'maintype': 'image', 'subtypes':['jpeg', 'png'], 'check_first_bytes':['\xFF\xD8','\xFF\xD9','\x89\x50\x4E\x47'], 'header':header} )
                filePath = GetTmpDir('.iptvplayer_captcha.jpg')
                ret = self.cm.saveWebFile(filePath, imgUrl.replace('&amp;', '&'), params)
                if not ret.get('sts'):
                    SetIPTVPlayerLastHostError(_('Fail to get "%s".') % imgUrl)
                    return False

                params = deepcopy(IPTVMultipleInputBox.DEF_PARAMS)
                params['accep_label'] = self.cleanHtmlStr(self.cm.ph.getDataBeetwenNodes(data, ('<button', '>', 'submit'), ('</button', '>'))[1])

                params['title'] = _('Captcha')
                params['status_text'] = self.cleanHtmlStr(self.cm.ph.getDataBeetwenNodes(data, ('<label', '>', 'captcha'), ('</label', '>'))[1])
                params['with_accept_button'] = True
                params['list'] = []
                item = deepcopy(IPTVMultipleInputBox.DEF_INPUT_PARAMS)
                item['label_size'] = (300,80)
                item['input_size'] = (480,25)
                item['icon_path'] = filePath
                item['title'] = _('Answer')
                item['input']['text'] = ''
                params['list'].append(item)
    
                ret = 0
                retArg = self.sessionEx.waitForFinishOpen(IPTVMultipleInputBox, params)
                printDBG(retArg)
                if retArg and len(retArg) and retArg[0]:
                    printDBG(retArg[0])
                    name = self.cm.ph.getDataBeetwenNodes(data, ('<input', '>', 'captcha'), ('</input', '>'))[1]
                    printDBG(name)
                    name = self.cm.ph.getSearchGroups(name, '''name=['"]([^"^']+?)['"]''')[0]
                    printDBG(name)
                    post_data['captcha'] = retArg[0][0]
            #############################################################################################
            
            httpParams = dict(self.defaultParams)
            httpParams['header'] = dict(self.AJAX_HEADER)
            httpParams['header']['Referer'] = url
            httpParams['header']['X-CSRF-TOKEN'] = self.cm.ph.getSearchGroups(data, '''(<meta[^>]+?_token[^>]+?/>)''')[0]
            httpParams['header']['X-CSRF-TOKEN'] = self.cm.ph.getSearchGroups(httpParams['header']['X-CSRF-TOKEN'], '''content=['"]([^"^']+?)['"]''')[0]
            error = ''
            sts, data = self.cm.getPage(actionUrl, httpParams, post_data)
            try:
                tmp = byteify(json.loads(data))['content']
                printDBG(tmp)
                tmp = self.cm.ph.getAllItemsBeetwenNodes(tmp, ('<div', '>', 'alert'), ('</div', '>'))
                tab = []
                for t in tmp:
                    t = self.cleanHtmlStr(t)
                    if t == '': continue
                    tab.append(t)
                error = ', '.join(tab)
            except Exception:
                printExc()
            
            sts, data = self.getPage(self.getMainUrl())
            if sts and '/logout' in data:
                self.HTTP_HEADER['X-CSRF-TOKEN'] = httpParams['header']['X-CSRF-TOKEN'] 
                self.AJAX_HEADER['X-CSRF-TOKEN'] = httpParams['header']['X-CSRF-TOKEN']
                self.loggedIn = True
            else:
                if error == '': error = _('Login failed.')
                SetIPTVPlayerLastHostError(error)
                printDBG('tryTologin failed')
        return self.loggedIn
    def getVideoLinks(self, videoUrl):
        printDBG("KinomanCO.getVideoLinks [%s]" % videoUrl)
        self.tryTologin()
        
        videoUrl = strwithmeta(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
                        
        url = self.getFullUrl('/api/link/embed?width=500&height=500', 'api')
        post_data = '{"code":"%s","secure": 1}' % (videoUrl)
        videoUrl = ''
        try:
            while True:
                httpParams = dict(self.defaultParams)
                httpParams.update({'raw_post_data':True, 'ignore_http_code_ranges':[(401,401), (500,500)]})
                httpParams['header'] = dict(httpParams['header'])
                httpParams['header']['Content-Type'] = 'application/json; charset=UTF-8'
                sts, data = self.getPage(url, httpParams, post_data)
                printDBG(data)
                if sts:
                    data = byteify(json.loads(data), '', True)
                    if not isinstance(data, str):
                        videoUrl = data['link']
                    elif 'captcha' in data.lower():
                        sts, data = self.getPage(self.getFullUrl('/api/captcha', 'api'))
                        if not sts:
                            SetIPTVPlayerLastHostError(_('Network connection failed.'))
                            break
                        data = byteify(json.loads(data), '', True)
                        captchaTitle = self._('Fill captcha')
                        imgUrl = data['image']
                        KinomanCO.CAPTCHA_HASHKEY = data['key']
                        self.defaultParams['header']['x-captcha-hashkey'] = KinomanCO.CAPTCHA_HASHKEY
                        
                        if self.cm.isValidUrl(imgUrl):
                            header = dict(self.HEADER)
                            header['Accept'] = 'image/png,image/*;q=0.8,*/*;q=0.5'
                            params = dict(self.defaultParams)
                            params.update( {'maintype': 'image', 'subtypes':['jpeg', 'png'], 'check_first_bytes':['\xFF\xD8','\xFF\xD9','\x89\x50\x4E\x47'], 'header':header} )
                            filePath = GetTmpDir('.iptvplayer_captcha.jpg')
                            rm(filePath)
                            ret = self.cm.saveWebFile(filePath, imgUrl, params)
                            if not ret.get('sts'):
                                SetIPTVPlayerLastHostError(_('Fail to get "%s".') % imgUrl)
                                return []

                            params = deepcopy(IPTVMultipleInputBox.DEF_PARAMS)
                            params['accep_label'] = _('Send')
                            params['title'] = _('Captcha')
                            params['status_text'] = captchaTitle
                            params['with_accept_button'] = True
                            params['list'] = []
                            item = deepcopy(IPTVMultipleInputBox.DEF_INPUT_PARAMS)
                            item['label_size'] = (160,75)
                            item['input_size'] = (480,25)
                            item['icon_path'] = filePath
                            item['title'] = _('Answer')
                            item['input']['text'] = ''
                            params['list'].append(item)
                            params['vk_params'] = {'invert_letters_case':True}
                
                            ret = 0
                            retArg = self.sessionEx.waitForFinishOpen(IPTVMultipleInputBox, params)
                            printDBG(retArg)
                            if retArg and len(retArg) and retArg[0]:
                                printDBG(retArg[0])
                                KinomanCO.CAPTCHA_CHALLENGE = retArg[0][0]
                                self.defaultParams['header']['x-captcha-challenge'] = KinomanCO.CAPTCHA_CHALLENGE
                                continue
                            break
                    elif 'x-user-token' not in httpParams['header'] and '_user_token' in data:
                        msg = _('The host %s requires registration. \nPlease fill your login and password in the host configuration. Available under blue button.' % self.getMainUrl())
                        SetIPTVPlayerLastHostError(msg)
                    else:
                        SetIPTVPlayerLastHostError(_('Unknown server response: "%s"') % data)
                else:
                    SetIPTVPlayerLastHostError(_('Network connection failed.'))
                break
        except Exception:
            SetIPTVPlayerLastHostError(_('Unknown server response.'))
            printExc()
        
        directLink = False
        if self.cm.isValidUrl(videoUrl):
            if 0 == self.up.checkHostSupport(videoUrl):
                params = dict(self.defaultParams)
                params.update({'return_data':False})
                try:
                    sts, response = self.cm.getPage(videoUrl, params)
                    videoUrl = response.geturl()
                    type = response.info().type.lower()
                    printDBG("type [%s]" % type)
                    if 'video' in type:
                        directLink = True
                    response.close()
                except Exception:
                    printExc()
            if directLink:
                urlTab.append({'name':'direct_link', 'url':strwithmeta(videoUrl, {})})
            else:
                urlTab = self.up.getVideoLinkExt(videoUrl)
        
        return urlTab
Beispiel #25
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
Beispiel #26
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
    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
    def _real_extract2(self, url, hls=None, smil=True):
        mobj = re.match(self._VALID_URL, url)
        video_id = mobj.group('id')

        if hls == None: hls = config.plugins.iptvplayer.vevo_allow_hls.value

        json_url = 'http://api.vevo.com/VideoService/AuthenticateVideo?isrc=%s' % video_id
        response = self._download_json(json_url, video_id)
        video_info = response['video'] or {}

        if not video_info and response.get('statusCode') != 909:
            if 'statusMessage' in response:
                SetIPTVPlayerLastHostError(response['statusMessage'])
                raise ExtractorError('%s said: %s' %
                                     (self.IE_NAME, response['statusMessage']),
                                     expected=True)
            raise ExtractorError('Unable to extract videos')

        if not video_info:
            if url.startswith('vevo:'):
                raise ExtractorError(
                    'Please specify full Vevo URL for downloading',
                    expected=True)
            webpage = self._download_webpage(url, video_id)

        formats = self._formats_from_json(video_info)

        is_explicit = video_info.get('isExplicit')
        if is_explicit is True:
            age_limit = 18
        elif is_explicit is False:
            age_limit = 0
        else:
            age_limit = None

        # Download via HLS API
        if hls or 0 == len(formats):
            formats.extend(self._download_api_formats(video_id))

        # Download SMIL
        if smil or 0 == len(formats):
            smil_blocks = sorted((f
                                  for f in video_info.get('videoVersions', [])
                                  if f['sourceType'] == 13),
                                 key=lambda f: f['version'])
            smil_url = '%s/Video/V2/VFILE/%s/%sr.smil' % (
                self._SMIL_BASE_URL, video_id, video_id.lower())
            if smil_blocks:
                smil_url_m = self._search_regex(r'url="([^"]+)"',
                                                smil_blocks[-1]['data'],
                                                'SMIL URL',
                                                default=None)
                if smil_url_m is not None:
                    smil_url = smil_url_m
            if smil_url:
                smil_xml = self._download_webpage(smil_url,
                                                  video_id,
                                                  'Downloading SMIL info',
                                                  fatal=False)
                if smil_xml:
                    formats.extend(self._formats_from_smil(smil_xml))

        return {
            'id': video_id,
            'title': '',
            'formats': formats,
            'thumbnail': '',
            'uploader': '',
            'duration': video_info.get('duration', 0),
            'age_limit': age_limit,
        }
    def getLinksForVideo(self, cItem):
        printDBG("C3player.getLinksForVideo [%s]" % cItem)
        linksTab = []
        hlsLinksTab = []
        hdsLinksTab = []

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

        hlsUrl = self.cm.ph.getSearchGroups(
            data,
            '''['"]?file['"]?\s*?:\s*?['"](https?://[^'^"]+?\.m3u8(?:\?[^'^"]+?)?)['"]'''
        )[0]
        if hlsUrl != '':
            hlsLinksTab = getDirectM3U8Playlist(hlsUrl,
                                                checkExt=True,
                                                checkContent=True,
                                                sortWithMaxBitrate=999999999)
        else:
            embedToken = self.cm.ph.getSearchGroups(
                data,
                '''['"]?embedToken['"]?\s*?:\s*?['"](https?://[^'^"]+?)['"]'''
            )[0]
            if embedToken == '':
                errorMsg = self.cleanHtmlStr(
                    self.cm.ph.getDataBeetwenNodes(data,
                                                   ('<div', '>', 'geo_block'),
                                                   ('</div', '>'))[1])
                SetIPTVPlayerLastHostError(errorMsg)
            if embedToken == '' and config.plugins.iptvplayer.tv3player_use_web_proxy.value:
                # http://getproxi.es/IE-proxies/
                proxy = 'http://ruproxy.herokuapp.com/index.php?q={0}&hl=e1'.format(
                    urllib.quote(cItem['url']))
                params = {'header': dict(self.HEADER)}
                params['header']['Referer'] = proxy
                #params['header']['cookie_items'] = {'flags':'2e5'}
                sts, data = self.cm.getPage(proxy, params)
                if not sts: return []
                printDBG("+++++++++++++++++++++++++++++++++++++++")
                printDBG(data)
                printDBG("+++++++++++++++++++++++++++++++++++++++")
                embedToken = self.cm.ph.getSearchGroups(
                    data,
                    '''['"]?embedToken['"]?\s*?:\s*?['"](https?://[^'^"]+?)['"]'''
                )[0]

            if embedToken != '':
                parsedUri = urlparse(embedToken)
                auth = parsedUri.path.split('/embed_token/', 1)[-1].split('/')
                if len(auth) > 1:
                    url = 'https://player.ooyala.com/sas/player_api/v2/authorization/embed_code/%s/%s?embedToken=%s&device=html5&domain=www.tv3.ie&auth_token=' % (
                        auth[0], auth[1], urllib.quote(embedToken))
                    sts, data = self.cm.getPage(url)
                    if not sts: return []
                    try:
                        printDBG(data)
                        data = byteify(json.loads(data))
                        for item in data['authorization_data'][
                                auth[1]]['streams']:
                            if item['url']['format'] == 'encoded':
                                url = base64.b64decode(item['url']['data'])
                            else:
                                url = item['url']['data']
                            if item['delivery_type'] == 'hls':
                                hlsLinksTab = getDirectM3U8Playlist(
                                    url,
                                    checkExt=True,
                                    checkContent=True,
                                    sortWithMaxBitrate=999999999)
                            elif item['delivery_type'] == 'hds':
                                hdsLinksTab = getF4MLinksWithMeta(
                                    url,
                                    checkExt=False,
                                    sortWithMaxBitrate=999999999)
                    except Exception:
                        printExc()

        for idx in range(len(hlsLinksTab)):
            hlsLinksTab[idx]['url'] = strwithmeta(hlsLinksTab[idx]['url'],
                                                  {'iptv_proto': 'm3u8'})

        for idx in range(len(hdsLinksTab)):
            hdsLinksTab[idx]['url'] = strwithmeta(hdsLinksTab[idx]['url'],
                                                  {'iptv_proto': 'f4m'})

        linksTab.extend(hlsLinksTab)
        linksTab.extend(hdsLinksTab)
        return linksTab
Beispiel #30
0
    def getVideoLinks(self, baseUrl):
        printDBG("YifyTV.getVideoLinks [%s]" % baseUrl)

        # 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 baseUrl 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

        urlTab = []

        baseUrl = strwithmeta(baseUrl)
        imdbid = baseUrl.meta.get('imdbid', '')
        sub_tracks = baseUrl.meta.get('external_sub_tracks', [])

        header = dict(self.AJAX_HEADER)
        #header['Referer'] = baseUrl.meta['Referer']

        if 'sou' in baseUrl.meta:
            souTab = [baseUrl.meta['sou']]
            if souTab[0] == 'pic':
                souTab.append('adr')
            if souTab[0] == 'adr':
                souTab.append('pic')

            for sou in souTab:
                post_data = {'fv': '27', 'url': baseUrl, 'sou': sou}
                url = 'https://ymovies.tv/playerlite/pk/pk/plugins/player_p2.php'
                sts, data = self.getPage(url, {'header': header}, post_data)
                if not sts: return []

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

                try:
                    attempt = 0
                    while attempt < 3:
                        attempt += 1
                        printDBG(data)
                        if 'jscode' in data:
                            try:
                                data = byteify(json.loads(data))[0]['jscode'][
                                    1:-1]  #.replace('eval(', 'print(')
                                jsTab = ['']
                                jsTab.append(
                                    '''var iptv_href="%s"; var iptv_domain="%s"; var iptv_video_id="%s"; var iptv_jwpath="%s";\n'''
                                    % (self.getMainUrl(),
                                       self.up.getDomain(
                                           self.getMainUrl()), imdbid, url))
                                jsTab.append(
                                    base64.b64decode(
                                        '''ZnVuY3Rpb24gU2hvd0Rpdigpe31mdW5jdGlvbiBzaG93aUZyYW1lKCl7cHJpbnQoYXJndW1lbnRzWzBdKX1mdW5jdGlvbiBnZXRKd1BhdGgoKXtyZXR1cm4gaXB0dl9qd3BhdGh9ZnVuY3Rpb24gZ2V0X3BhcmFtc19ub19zb3JjZXMoKXtyZXR1cm4gaXB0dl92aWRlb19pZH1mdW5jdGlvbiBzZXRUaW1lb3V0KHQsbil7aWYoaXB0dl9kaXJlY3QpdHJ5e3QoKX1jYXRjaChlKXtwcmludCgiXG4iKX1lbHNlIHRoaXMudHJ5dXAoKX12YXIgZG9jdW1lbnQ9e30sd2luZG93PXRoaXMsbG9jYXRpb249e307bG9jYXRpb24uaHJlZj1pcHR2X2hyZWYsbG9jYXRpb24uaG9zdG5hbWU9aXB0dl9kb21haW4sbG9jYXRpb24udG9TdHJpbmc9ZnVuY3Rpb24oKXtyZXR1cm4gaXB0dl9ocmVmfSxkb2N1bWVudC5sb2NhdGlvbj1sb2NhdGlvbjt2YXIgZWxlbWVudD1mdW5jdGlvbih0KXt0aGlzLnRleHQ9ZnVuY3Rpb24oKXtyZXR1cm4ibm9uZSJ9LHRoaXMuZmlyc3Q9ZnVuY3Rpb24oKXtyZXR1cm4gbmV3IGVsZW1lbnR9fSwkPWZ1bmN0aW9uKHQpe3JldHVybiBuZXcgZWxlbWVudCh0KX0scGxheWVybW9kZT0iIixzb3VyY2VTZWxlY3RlZD0wLHNvdXJjZXM9W3tzdWJfZGVsYXk6MCxzdWJfZmFjdG9yOjF9XTskLmdldD1mdW5jdGlvbigpe3JldHVybiBwcmludChhcmd1bWVudHNbMF0pLHtkb25lOlNob3dEaXYsZXJyb3I6U2hvd0Rpdn19LCQucG9zdD1mdW5jdGlvbigpe3ByaW50KCJcbklQVFZfUE9TVF9TVEFSVFxuIikscHJpbnQoSlNPTi5zdHJpbmdpZnkoe3VybDphcmd1bWVudHNbMF0scGFyYW1zOmFyZ3VtZW50c1sxXX0pKSxwcmludCgiXG5JUFRWX1BPU1RfRU5EXG4iKX07'''
                                    ))
                                jsTab.append('var iptv_fun = %s; iptv_fun();' %
                                             data)

                                for iptv_direct in ["false", "true"]:
                                    jsTab[
                                        0] = 'var iptv_direct = %s;' % iptv_direct
                                    jscode = '\n'.join(jsTab)
                                    printDBG(
                                        "+++++++++++++++++++++++  CODE  ++++++++++++++++++++++++"
                                    )
                                    printDBG(jscode)
                                    printDBG(
                                        "+++++++++++++++++++++++++++++++++++++++++++++++++++++++"
                                    )
                                    ret = iptv_js_execute(jscode)
                                    if not ret['sts'] or 0 != ret['code']:
                                        ret = iptv_js_execute(
                                            jscode.replace('eval(', 'print('))
                                    if ret['sts'] and 0 == ret['code']:
                                        decoded = ret['data'].strip()
                                        printDBG('DECODED DATA -> [%s]' %
                                                 decoded)
                                        data = decoded
                                        break
                                if 'jscode' in data:
                                    data = data[data.
                                                find("["):data.rfind("]") + 1]
                                    data = byteify(json.loads('"%s"' % data))
                                    continue
                            except Exception:
                                printExc()

                            if 'IPTV_POST_START' in data:
                                data = self.cm.ph.getDataBeetwenMarkers(
                                    data, 'IPTV_POST_START', 'IPTV_POST_END',
                                    0)[1]
                                try:
                                    tmp = byteify(json.loads(data.strip()))
                                    sts, data = self.getPage(
                                        tmp['url'], {
                                            'header': header,
                                            'raw_post_data': True
                                        }, tmp['params'])
                                    if not sts: return []
                                    tmp = byteify(json.loads(data))
                                    for hostDomain in tmp['hosts']:
                                        urlTab.append({
                                            'name':
                                            hostDomain,
                                            'url':
                                            'http://%s%s' %
                                            (hostDomain, tmp['path'])
                                        })
                                    if len(urlTab): break
                                except Exception:
                                    printExc()

                            g3 = self.cm.ph.getSearchGroups(
                                data + '&', '''[&\?]g3=([^&]+?)&''')[0]
                            emb = self.cm.ph.getSearchGroups(
                                data + '&', '''[&\?]emb=([^&^\*]+?)[&\*]''')[0]
                            if emb != '': data = urllib.unquote(emb)
                            if g3 != '':
                                post_data = {
                                    'fv': '0',
                                    'g3': urllib.unquote(g3)
                                }
                                url = 'https://ymovies.tv/playerlite/pk/pk/plugins/player_g3.php'
                                sts, data = self.getPage(
                                    url, {'header': header}, post_data)
                                if not sts: return []
                                printDBG(data)
                            elif self.cm.isValidUrl(
                                    data) and 1 == self.up.checkHostSupport(
                                        data):
                                urlTab = self.up.getVideoLinkExt(data)
                                break
                            else:
                                if 'showiFrame(' in data:
                                    url = urllib.unquote(
                                        self.cm.ph.getDataBeetwenMarkers(
                                            data, "emb='+'", "'", False)[1])
                                    tmp = url.split('sub.file')
                                    url = tmp[0]
                                    subTrack = urllib.unquote(tmp[1])
                                    if url.startswith('//'):
                                        url = 'http:' + url
                                    if subTrack.startswith('//'):
                                        subTrack = 'http:' + subTrack
                                    tmpUrlTab = self.up.getVideoLinkExt(url)
                                    if self.cm.isValidUrl(subTrack):
                                        format = subTrack[-3:]
                                        for idx in range(len(tmpUrlTab)):
                                            tmpUrlTab[idx][
                                                'url'] = strwithmeta(
                                                    tmpUrlTab[idx]['url'], {
                                                        'external_sub_tracks':
                                                        [{
                                                            'title': '',
                                                            'url': subTrack,
                                                            'lang': 'en',
                                                            'format': format
                                                        }]
                                                    })
                                    urlTab.extend(tmpUrlTab)
                                    printDBG(urlTab)
                                    break

                                if 'sources[sourceSelected]["paramId"]' in data:
                                    data = data.replace('"+"',
                                                        '').replace(' ', '')
                                    paramSite = self.cm.ph.getSearchGroups(
                                        data,
                                        'sources\[sourceSelected\]\["paramSite"\]="([^"]+?)"'
                                    )[0]
                                    data = self.cm.ph.getSearchGroups(
                                        data,
                                        'sources\[sourceSelected\]\["paramId"\]="([^"]+?)"'
                                    )[0]
                                    printDBG(
                                        'data ------------------------- [%s]' %
                                        data)
                                    if data.startswith('enc'):
                                        encrypted = base64.b64decode(data[3:])
                                        key = unhexlify(
                                            base64.b64decode(
                                                'MzAzOTM4NzMzOTM3MzU0MTMxMzIzMzczMzEzMzM1NjQ2NDY2Njc3NzQ4MzczODM0MzczNTMzMzQzNjcyNjQ3Nw=='
                                            ))
                                        iv = unhexlify(
                                            base64.b64decode(
                                                'NWE0MTRlMzEzNjMzNjk2NDZhNGM1MzUxMzU0YzY0MzU='
                                            ))
                                        cipher = AES_CBC(key=key,
                                                         padding=noPadding(),
                                                         keySize=32)
                                        data = cipher.decrypt(
                                            encrypted, iv).split('\x00')[0]
                                        if 'ucl' == paramSite:
                                            urlTab.extend(
                                                self.up.getVideoLinkExt(
                                                    "https://userscloud.com/embed-"
                                                    + data + "-1280x534.html"))
                                        elif 'tus' == paramSite:
                                            urlTab.extend(
                                                self.up.getVideoLinkExt(
                                                    "https://tusfiles.net/embed-"
                                                    + data +
                                                    "-1280x534.html?v=34"))
                                        elif 'up' == paramSite:
                                            urlTab.extend(
                                                self.up.getVideoLinkExt(
                                                    "http://uptobox.com/" +
                                                    data))
                                        break

                        if '("' in data:
                            data = self.cm.ph.getDataBeetwenMarkers(
                                data, '(', ')', False)[1]
                            data = byteify(json.loads(data))
                        if isinstance(data, basestring):
                            data = byteify(json.loads(data))
                        printDBG(data)
                        for item in data:
                            #printDBG('++++++++++++++++++++++\n%s\n++++++++++++++++++++++' % item)
                            if (item.get('type', '').startswith('video/')
                                    or item.get('type', '').startswith(
                                        'application/x-shockwave-flash')
                                ) and self.cm.isValidUrl(item.get('url', '')):
                                urlTab.append({
                                    'name':
                                    '{0}x{1}'.format(item.get('height', ''),
                                                     item.get('width', '')),
                                    'url':
                                    item['url'],
                                    'need_resolve':
                                    0
                                })
                    break
                except Exception:
                    SetIPTVPlayerLastHostError(
                        'The Mirror is broken.\nIf available you can choose other source.'
                    )
                    printExc()
                    return []

                if len(urlTab): break

        elif self.cm.isValidUrl(baseUrl):
            urlTab = self.up.getVideoLinkExt(baseUrl)

        printDBG(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
        printDBG(urlTab)

        for idx in range(len(urlTab)):
            subs = list(
                strwithmeta(urlTab[idx]['url']).meta.get(
                    'external_sub_tracks', []))
            subs.extend(sub_tracks)
            urlTab[idx]['url'] = strwithmeta(urlTab[idx]['url'],
                                             {'external_sub_tracks': subs})

        printDBG(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
        printDBG(urlTab)
        return urlTab