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
Esempio n. 2
0
    def downloadSubtitleFile(self, cItem):
        printDBG("YoutubeComProvider.downloadSubtitleFile")
        retData = {}
        title = cItem['title']
        lang = cItem['lang']
        subId = cItem.get('ytid', '0')
        fileName = self._getFileName(title, lang, subId, self.youtubeId)
        fileName = GetSubtitlesDir(fileName)

        urlParams = dict(self.defaultParams)
        urlParams['max_data_size'] = self.getMaxFileSize()
        sts, data = self.cm.getPage(cItem['url'], urlParams)
        if not sts:
            SetIPTVPlayerLastHostError(_('Failed to download subtitle.'))
            return retData

        try:
            with open(fileName, 'w') as f:
                f.write(data)
        except Exception:
            printExc()
            SetIPTVPlayerLastHostError(_('Failed to write file "%s".') % fileName)
            rm(fileName)
            return retData

        printDBG(">>")
        printDBG(fileName)
        printDBG("<<")
        retData = {'title': title, 'path': fileName, 'lang': lang, 'ytid': self.youtubeId, 'sub_id': subId}

        return retData
Esempio n. 3
0
    def downloadSubtitleFile(self, cItem):
        printDBG("OpenSubOrgProvider.downloadSubtitleFile")
        retData = {}
        title = cItem['title']
        fileName = cItem['file_name']
        url = cItem['url']
        lang = cItem['lang']
        encoding = cItem['encoding']
        imdbid = cItem['imdbid']

        urlParams = dict(self.defaultParams)
        urlParams['return_data'] = False

        try:
            fileSize = self.getMaxFileSize()
            sts, response = self.cm.getPage(url, urlParams)
            data = response.read(fileSize)
            response.close()
        except Exception:
            printExc()
            sts = False

        if not sts:
            SetIPTVPlayerLastHostError(_('Failed to download subtitle.'))
            return retData

        try:
            buf = StringIO(data)
            f = gzip.GzipFile(fileobj=buf)
            data = f.read()
        except Exception:
            printExc()
            SetIPTVPlayerLastHostError(_('Failed to gzip.'))
            return retData

        try:
            data = data.decode(encoding).encode('UTF-8')
        except Exception:
            printExc()
            SetIPTVPlayerLastHostError(_('Failed to decode to UTF-8.'))
            return retData

        fileName = GetSubtitlesDir(fileName)
        printDBG(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
        printDBG(fileName)
        printDBG(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
        try:
            with open(fileName, 'w') as f:
                f.write(data)
            retData = {
                'title': title,
                'path': fileName,
                'lang': lang,
                'imdbid': imdbid
            }
        except Exception:
            SetIPTVPlayerLastHostError(
                _('Failed to write file "%s".') % fileName)
            printExc()
        return retData
 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)
     try:
         if 'Duze obciazenie!' in data and loggedIn==False:
             message = self.cleanHtmlStr(re.compile('<script.+?</script>', re.DOTALL).sub("", data))
             GetIPTVNotify().push(message, 'info', 5)
             SetIPTVPlayerLastHostError(message)
         if '/sms' in self.cm.meta['url']:
             message = 'Duze obciazenie!'
             GetIPTVNotify().push(message, 'info', 5)
             SetIPTVPlayerLastHostError(message)
     except Exception:
         pass
     return sts, data
Esempio n. 5
0
    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
Esempio n. 6
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
Esempio n. 7
0
    def decryptSignatures(self, encSignatures, playerUrl):
        decSignatures = []
        code = ''
        jsname = 'ytsigndec'
        jshash = 'hash7_' + playerUrl.split('://', 1)[-1]
        if not is_js_cached(jsname, jshash):

            # get main function
            sts, self.playerData = self.cm.getPage(playerUrl)
            if not sts: return []

            t1 = time.time()
            code = []
            mainFunctionName = self._findMainFunctionName()
            if not mainFunctionName:
                SetIPTVPlayerLastHostError(
                    _('Encryption function name extraction failed!\nPlease report the problem to %s'
                      ) % 'https://github.com/persianpros/e2iplayer/issues')
                return []
            printDBG("mainFunctionName >> %s" % mainFunctionName)

            mainFunction = self._findFunction(mainFunctionName)
            if not mainFunction:
                SetIPTVPlayerLastHostError(
                    _('Encryption function body extraction failed!\nPlease report the problem to %s'
                      ) % 'https://github.com/persianpros/e2iplayer/issues')
                return []
            code.append(mainFunction)

            funNames = self._getAllLocalSubFunNames(mainFunction)
            for funName in funNames:
                fun = self._findFunction(funName)
                code.insert(0, fun)

            objects = self._getAllObjectsWithMethods(mainFunction)
            for objName, methods in objects.iteritems():
                obj = self._findObject(objName, methods)
                code.insert(0, obj)

            code.append(
                'e2i_dec=[];for (var idx in e2i_enc){e2i_dec.push(%s(e2i_enc[idx]));};print(JSON.stringify(e2i_dec));'
                % mainFunctionName)
            code = '\n'.join(code)
            printDBG("---------------------------------------")
            printDBG("|    ALGO FOR SIGNATURE DECRYPTION    |")
            printDBG("---------------------------------------")
            printDBG(code)
            printDBG("---------------------------------------")
        else:
            printDBG("USE ALGO FROM CACHE: %s" % jshash)

        js_params = [{'code': 'e2i_enc = %s;' % json_dumps(encSignatures)}]
        js_params.append({'name': jsname, 'code': code, 'hash': jshash})
        ret = js_execute_ext(js_params)
        if ret['sts'] and 0 == ret['code']:
            try:
                decSignatures = json_loads(ret['data'])
            except Exception:
                printExc()
        return decSignatures
Esempio n. 8
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})

        addParams['ignore_http_code_ranges'] = [(503, 503)]
        sts, data = self.cm.getPage(url, addParams, post_data)

        try:
            if 'Duze obciazenie!' in data and self.loggedIn==False:
                message = self.cleanHtmlStr(data)
                GetIPTVNotify().push(message, 'info', 5)
                SetIPTVPlayerLastHostError(message)
            if '/sms' in self.cm.meta['url']:
                message = 'Duze obciazenie!'
                GetIPTVNotify().push(message, 'info', 5)
                SetIPTVPlayerLastHostError(message)
        except Exception:
            pass
        return sts, data
Esempio n. 9
0
    def getLinksForVideo(self, cItem):
        printDBG("JooglePL.getLinksForVideo [%s]" % cItem)
        urlTab = []
        sts, data = self.cm.getPage(cItem['url'])
        if not sts: return []
        sts, data = self.cm.ph.getDataBeetwenMarkers(
            data, '<div id="player-content">', '<script>', True)
        if not sts:
            SetIPTVPlayerLastHostError(_("Cannot find player content"))
            return []
        playerUrl = self._getFullUrl(
            self.cm.ph.getSearchGroups(data, 'src="([^"]+?)"')[0])
        if playerUrl == '':
            SetIPTVPlayerLastHostError(self.cleanHtmlStr(data))
            return []
        sts, data = self.cm.getPage(playerUrl, {'Referer': cItem['url']})
        if not sts: return []

        directVideoUrl = self.cm.ph.getSearchGroups(data,
                                                    'file=(http[^"]+?)"')[0]
        if directVideoUrl != '':
            urlTab.append({'name': 'Direct', 'url': directVideoUrl})
        else:
            if 'proxy.link' in data:
                proxyUrl = self.cm.ph.getSearchGroups(
                    data, 'proxy.link=(http[^"]+?)"')[0]
            else:
                proxyUrl = self.cm.ph.getSearchGroups(data,
                                                      'src="([^"]+?)"')[0]
            if proxyUrl != '': urlTab.extend(self.up.getVideoLinkExt(proxyUrl))
            else: SetIPTVPlayerLastHostError(self.cleanHtmlStr(data))

        return urlTab
Esempio n. 10
0
    def processCaptcha(self, key, referer=None):
        post_data = None
        token = ''
        iteration = 0
        if referer != None:
            self.HTTP_HEADER['Referer'] = referer
        reCaptchaUrl = 'http://www.google.com/recaptcha/api/fallback?k=%s' % (key)
        while iteration < 20:
            #,'cookiefile':self.COOKIE_FILE, 'use_cookie': True, 'load_cookie': True, 'save_cookie':True
            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 ''

            printDBG("+++++++++++++++++++++++++++++++++++++++++")
            printDBG(data)
            printDBG("+++++++++++++++++++++++++++++++++++++++++")
            imgUrl = ph.search(data, '"(/recaptcha/api2/payload[^"]+?)"')[0]
            iteration += 1

            message = ph.clean_html(ph.find(data, ('<div', '>', 'imageselect-desc'), '</div>', flags=0)[1])
            if not message: message = ph.clean_html(ph.find(data, ('<label', '>', 'fbc-imageselect-message-text'), '</label>', flags=0)[1])
            if not message: message = ph.clean_html(ph.find(data, ('<div', '>', 'imageselect-message'), '</div>', flags=0)[1])
            if '' == message:
                token = ph.find(data, ('<div', '>', 'verification-token'), '</div>', flags=0)[1]
                token = ph.find(data, ('<textarea', '>'), '</textarea>', flags=0)[1].strip()
                if token == '': token = ph.search(data, '"this\.select\(\)">(.*?)</textarea>')[0]
                if token == '': token = ph.find(data, ('<textarea', '>'), '</textarea>', flags=0)[1].strip()
                if '' != token: printDBG('>>>>>>>> Captcha token[%s]' % (token))
                else: printDBG('>>>>>>>> Captcha Failed\n\n%s\n\n' % data)
                break

            cval = ph.search(data, 'name="c"\s+value="([^"]+)')[0]
            imgUrl = 'https://www.google.com%s' % (imgUrl.replace('&amp;', '&'))
            message = ph.clean_html(message)
            accepLabel = ph.clean_html(ph.search(data, 'type="submit"\s+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
            
            retArg = self.sessionEx.waitForFinishOpen(UnCaptchaReCaptchaWidget, imgFilePath=filePath, message=message, title="reCAPTCHA v2", additionalParams={'accep_label':accepLabel})
            printDBG('>>>>>>>> Captcha response[%s]' % (retArg))
            if retArg is not None and len(retArg) and retArg[0]:
                answer = retArg[0]
                printDBG('>>>>>>>> Captcha answer[%s]' % (answer))
                post_data = urllib.urlencode({'c': cval, 'response':answer}, doseq=True)
            else:
                break
        
        return token
Esempio n. 11
0
    def getLinks(self, id):
        printDBG("TvnVod.getLinks cItem.id[%r]" % id)
        videoUrls = []

        url = self.baseUrl + '&type=episode&id=%s&limit=%d&page=1&sort=newest&m=%s' % (
            id, self.itemsPerPage, 'getItem')
        sts, data = self.cm.getPage(url)
        if sts:
            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:
                                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:
                printExc()
        return videoUrls
Esempio n. 12
0
    def downloadSubtitleFile(self, cItem):
        printDBG("OpenSubOrgProvider.downloadSubtitleFile")
        retData = {}
        title = cItem['title']
        fileName = cItem['file_name']
        url = cItem['url']
        lang = cItem['lang']
        encoding = cItem['encoding']
        imdbid = cItem['imdbid']

        urlParams = dict(self.defaultParams)
        urlParams['max_data_size'] = self.getMaxFileSize()

        sts, data = self.cm.getPage(url, urlParams)
        if not sts:
            SetIPTVPlayerLastHostError(_('Failed to download subtitle.'))
            return retData

        try:
            data = DecodeGzipped(data)
        except Exception:
            printExc()
            SetIPTVPlayerLastHostError(_('Failed to gzip.'))
            return retData

        try:
            data = data.decode(encoding).encode('UTF-8')
        except Exception:
            printExc()
            SetIPTVPlayerLastHostError(_('Failed to decode to UTF-8.'))
            return retData

        fileName = GetSubtitlesDir(fileName)
        printDBG(">>")
        printDBG(fileName)
        printDBG("<<")
        try:
            with open(fileName, 'w') as f:
                f.write(data)
            retData = {
                'title': title,
                'path': fileName,
                'lang': lang,
                'imdbid': imdbid
            }
        except Exception:
            SetIPTVPlayerLastHostError(
                _('Failed to write file "%s".') % fileName)
            printExc()
        return retData
Esempio n. 13
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
Esempio n. 14
0
 def _doLogin(self, login, password):
     lang = GetDefaultLang()
     params = [login, hex_md5(password), lang, self.USER_AGENT]
     sts, data = self._rpcMethodCall("LogIn", params)
     if sts and (None == data or 0 == len(data)): sts = False 
     printDBG(">>>>>>>>>>>>>>>>>>>>>>>>>>>>> data[%s]" % data)
     if not sts:
         SetIPTVPlayerLastHostError(_('Login failed!'))
     elif ('' != login and self._checkStatus(data, 0)) or '' == login: 
         if 'token' in data[0]:
             self.loginToken = data[0]['token']
         else:
             SetIPTVPlayerLastHostError(_('Get token failed!') + '\n' + _('Error message: \"%s\".\nError code: \"%s\".') % (self.lastApiError['code'], self.lastApiError['message']) )
     else:
         SetIPTVPlayerLastHostError(_('Login failed!') + '\n' + _('Error message: \"%s\".\nError code: \"%s\".') % (self.lastApiError['code'], self.lastApiError['message']) )
Esempio n. 15
0
	def getVideos(self,videoUrl):
		urlTab = []	
		Url = self.MAIN_URL+'/'+videoUrl		
		sts, data = self.getPage(Url)
		if sts:
			printDBG('dddddaaaaattttaaaaa'+data)
			_data2 = re.findall('<iframe.*?src=["\'](.*?)["\']',data, re.S|re.IGNORECASE)
			if _data2:
				printDBG('01')
				URL_=_data2[0]
				if URL_.startswith('//'):
					URL_='http:'+URL_
				urlTab.append((URL_,'1'))
			else:
				printDBG('02')
				_data2 = re.findall('<body>.*?src=["\'](.*?)["\']',data, re.S|re.IGNORECASE)
				if _data2:
					printDBG('03')
					URL_=_data2[0]
					if URL_.startswith('//'):
						URL_='http:'+URL_
					urlTab.append((URL_,'1'))
				else:
					printDBG('04')
					if 'https://asiatv.cc/userpro/' in data:
						SetIPTVPlayerLastHostError('Only premium users!!')
				
		return urlTab
Esempio n. 16
0
    def getLinksForVideo(self, cItem):
        printDBG("WrestlingNet.getLinksForVideo [%s]" % cItem)
        urlTab = []
        sts, data = self.cm.getPage(cItem['url'])
        if not sts: return urlTab

        sts, data = self.cm.ph.getDataBeetwenMarkers(data, 'entry-content',
                                                     'video-meta-info',
                                                     True)  #'id="more-'
        if not sts:
            SetIPTVPlayerLastHostError(
                _("Please visit '%s' from using web-browser form the PC. If links are available please report this problem.\nEmail: [email protected]"
                  ) % cItem['url'])
            return urlTab

        data = data.split('<h2>')
        if len(data): del data[0]
        re_links = re.compile('<a[^>]+?href="([^"]+?)"[^>]*?>([^<]+?)</a>')
        for item in data:
            type = self.cleanHtmlStr(item.split('</h2>')[0])

            links = re_links.findall(item)
            for link in links:
                urlTab.append({'name': type + ' ' + link[1], 'url': link[0]})

        return urlTab
Esempio n. 17
0
 def listItems(self, cItem, nextCategory):
     printDBG("MaxtvGO.listItems [%s]" % cItem)
     
     sts, data = self.getPage(cItem['url'])
     if not sts: return
     
     try:
         data = byteify(json.loads(data))
         if data.get('error') != None:
             SetIPTVPlayerLastHostError(str(data['error']['message']))
         for item in data['data']:
             sTitle = self.cleanHtmlStr(item['name'])
             subItems = []
             for it in item['videos']:
                 title = self.cleanHtmlStr(it['title'])
                 #icon = self.getFullIconUrl(it['image'])
                 icon = str(it.get('vimeoPosterId', ''))
                 if icon != '': icon = 'http://i.vimeocdn.com/video/%s.jpg?mw=300' % icon
                 url = self.getFullUrl('video.php?film=') + it['code']
                 params = dict(cItem)
                 params.update({'type':'video', 'good_for_fav':True, 'title':title, 'url':url, 'icon':icon})
                 subItems.append(params)
             
             if len(subItems):
                 params = dict(cItem)
                 params.update({'category':nextCategory, 'good_for_fav':False, 'title':sTitle, 'sub_items':subItems})
                 self.addDir(params)
         
     except Exception:
         printExc()
     
         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)
Esempio n. 18
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
Esempio n. 19
0
    def getLinksForVideo(self, cItem, source_id=None):
        linksTab = []

        if 'item_data' not in cItem:
            sts, data = self.getPage(cItem['url'])
            if not sts: return
            client_location = self.cm.meta['url']
            data = ph.find(data, 'var contentResources = [', '];', flags=0)[1]
            try:
                data = json_loads('[%s]' % data)[0]
            except Exception:
                pass
        else:
            client_location = cItem['url']
            data = cItem['item_data']

        try:
            drm = data.get('drm')
            if drm:
                SetIPTVPlayerLastHostError(_('Link protected with DRM.'))
            video_id = data['id']
        except Exception:
            printExc()
            return []

        #dashLinks = self.doGetLinks(video_id, client_location, 'application/dash+xml')
        try:
            for it in (False, True):
                hlsLinks = self.doGetLinks(video_id, client_location,
                                           'application/x-mpegURL', it)
                if hlsLinks:
                    linksTab.extend(
                        getDirectM3U8Playlist(hlsLinks[0]['url'],
                                              checkExt=True,
                                              checkContent=True,
                                              sortWithMaxBitrate=999999999))
                    break

            for it in (True, False):
                mp4Links = self.doGetLinks(video_id, client_location,
                                           'video/mp4', it)
                for item in mp4Links:
                    if item['mimetype'] == 'video/mp4':
                        linksTab.append({
                            'name':
                            '[MP4] bitrate: %s' % item['bitrate'],
                            'url':
                            item['url'],
                            'bitrate':
                            item['bitrate']
                        })
                if mp4Links:
                    break
            if not mp4Links and drm:
                return []
            linksTab.sort(reverse=True, key=lambda k: int(k['bitrate']))
        except Exception:
            printExc()

        return linksTab
Esempio n. 20
0
    def getVideoLink(self, cItem):
        printDBG("InternetowaApi.getVideoLink")
        urlsTab = []

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

        SetIPTVPlayerLastHostError(self.cleanHtmlStr(self.cm.ph.getDataBeetwenNodes(data, ('<div', '>', 'nostream'), ('</div', '>'), False)[1]))

        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
            if 1 == self.up.checkHostSupport(url):
                url = strwithmeta(url, {'Referer':cUrl})
                urlsTab.extend( self.up.getVideoLinkExt(url) )
            else:
                params = dict(self.http_params)
                params['header'] = MergeDicts(self.HTTP_HEADER, {'Referer':cUrl})
                sts, tmp = self.cm.getPage(url, params)
                if not sts: continue
                tmp2 = self.cm.ph.getDataBeetwenMarkers(tmp, '<audio', '</audio>', False)[1]
                tmp2 = self.cm.ph.getDataBeetwenMarkers(tmp, '<audio', '</audio>', False)[1]
                tmp = self.cm.ph.getAllItemsBeetwenMarkers(tmp2, '<source', '>')
                for it in tmp:
                    printDBG(it)
                    type = self.cm.ph.getSearchGroups(it, '''type=['"]([^"^']+?)['"]''')[0].lower().split('/', 1)
                    mediaUrl = self.cm.getFullUrl( self.cm.ph.getSearchGroups(it, '''src=['"]([^"^']+?)['"]''')[0], self.cm.meta['url'])
                    if type[0] in ('audio', 'video'):
                        mediaUrl = strwithmeta(mediaUrl, {'User-Agent':params['header']['User-Agent'], 'Referer':self.cm.meta['url']})
                        urlsTab.append({'name':'[%s] %s' % (type[1], self.cm.getBaseUrl(url, True)), 'url':mediaUrl, 'need_resolve':0})
        return urlsTab
Esempio n. 21
0
    def _getLanguages(self):
        lang = GetDefaultLang()
        subParams = [{'name': 'sublanguageid', 'value': lang}]
        params = [self.loginToken, self._getArraryParam(subParams)]

        sts, data = self._rpcMethodCall("GetSubLanguages", params)
        printDBG(">>>>>>>>>>>>>>>>>>>>>>>>>>>>> data[%s]" % data)
        if sts:
            try:
                list = []
                defaultLanguageItem = None
                for item in data:
                    if 'LanguageName' in item and 'SubLanguageID' in item and 'ISO639' in item:
                        params = {
                            'title':
                            '{0} [{1}]'.format(item['LanguageName'],
                                               item['SubLanguageID']),
                            'lang':
                            item['SubLanguageID']
                        }
                        if lang != item['ISO639']:
                            list.append(params)
                        else:
                            defaultLanguageItem = params
                if None != defaultLanguageItem:
                    list.insert(0, defaultLanguageItem)
                return list
            except Exception:
                printExc()
        SetIPTVPlayerLastHostError(_('Get languages failed!'))
        return []
Esempio n. 22
0
    def listSearchResult(self, cItem, searchPattern, searchType):
        printDBG(
            "FuufPL.listSearchResult cItem[%s], searchPattern[%s] searchType[%s]"
            % (cItem, searchPattern, searchType))

        post_data = {'q': searchPattern}
        sts, data = self.cm.getPage(FuufPL.SRCH_URL, {}, post_data)
        if not sts: return

        try:
            data = byteify(json.loads(data))
            for item in data:
                url = item['url']
                title = self.cleanHtmlStr(item['name'])
                icon = self.cm.ph.getSearchGroups(item['name'],
                                                  'src="([^"]+?)"')[0]

                if '' != url and '' != title:
                    params = dict(cItem)
                    params.update({
                        'title': title,
                        'url': self._getFullUrl(url),
                        'icon': self._getFullUrl(icon)
                    })
                    self.addVideo(params)
        except:
            printExc()
            SetIPTVPlayerLastHostError(_("Parsing search result failed."))
Esempio n. 23
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
Esempio n. 24
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)
Esempio n. 25
0
    def getSubtitles(self, cItem):
        printDBG("YoutubeComProvider.getSubtitles")
        if not self.cm.isValidUrl(self.popcornsubtitlesUrl):
            SetIPTVPlayerLastHostError(_('Wrong uri.'))
            return

        url = self.popcornsubtitlesUrl
        urlParams = dict(self.defaultParams)

        sts, tmp = self.cm.getPage(url, urlParams)
        if not sts: return

        imdbid = self.cm.ph.getSearchGroups(tmp, '/(tt[0-9]+?)[^0-9]')[0]
        tmp = self.cm.ph.getDataBeetwenMarkers(tmp, '<tbody>', '</tbody>')[1]
        tmp = self.cm.ph.getAllItemsBeetwenMarkers(tmp,
                                                   '<tr',
                                                   '</tr>',
                                                   withMarkers=True)
        for item in tmp:
            url = self.getFullUrl(
                self.cm.ph.getSearchGroups(item,
                                           '''href=['"]([^'^"]+?)['"]''')[0])
            title = self.cleanHtmlStr(item)
            lang = self.cleanHtmlStr(
                self.cm.ph.getDataBeetwenMarkers(item, '<td', '</td>')[1])
            if self.cm.isValidUrl(url):
                params = dict(cItem)
                params.update({
                    'title': lang,
                    'url': url,
                    'lang': lang,
                    'imdbid': imdbid,
                    'desc': title
                })
                self.addSubtitle(params)
Esempio n. 26
0
    def downloadAndUnpack(self, url, params={}, post_data=None):
        data, fileName = self.downloadFileData(url, params, post_data)
        if data == None:
            return None
        ext = fileName.split('.')[-1].lower()
        if ext not in ['zip', 'rar']:
            SetIPTVPlayerLastHostError(_('Unknown file extension "%s".') % ext)
            return None

        tmpFile = GetTmpDir(self.TMP_FILE_NAME)
        tmpArchFile = tmpFile + '.' + ext
        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
    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
Esempio n. 28
0
 def getPage(self, baseUrl, addParams={}, post_data=None):
     if addParams == {}: addParams = dict(self.defaultParams)
     
     proxy = config.plugins.iptvplayer.hdsto_proxy.value
     if proxy == 'webproxy':
         addParams = dict(addParams)
         proxy = 'http://n-guyot.fr/exit/browse.php?u={0}&b=4'.format(urllib.quote(baseUrl, ''))
         addParams['header']['Referer'] = proxy + '&f=norefer'
         baseUrl = proxy
     elif 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})
     tries = 0
     while tries < 2:
         tries += 1
         sts, data = self.cm.getPage(baseUrl, addParams, post_data)
         if sts:
             if self.getFullUrl(self.cm.meta['url']).endswith('/home.php'):
                 SetIPTVPlayerLastHostError('\n'.join(self.membersOnly))
             elif config.plugins.iptvplayer.hdsto_proxy.value == 'webproxy' and 'sslagree' in data:
                 sts, data = self.cm.getPage('http://n-guyot.fr/exit/includes/process.php?action=sslagree', addParams, post_data)
                 continue
         break
     return sts, data
Esempio n. 29
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)
        if 'sh.st' in domain or 'viid.me' 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
Esempio n. 30
0
    def getVideoLinks(self, videoUrl):
        printDBG("BSTO.getVideoLinks [%s]" % videoUrl)
        urlTab = []

        key = strwithmeta(videoUrl).meta.get('links_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']

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

        errorMsg = ''

        baseUrl = self.cm.ph.getSearchGroups(
            data, '''href=['"][^'^"]*?(/out/[^'^"]+?)['"]''')[0]
        url = self.getFullUrl(baseUrl)
        params = dict(self.defaultParams)
        params['return_data'] = False
        try:
            prevUrl = url
            sts, response = self.cm.getPage(prevUrl, params)
            url = response.geturl()
            response.close()
            if url == prevUrl:
                sts, data = self.getPage(url)
                if 'bitte das Captcha' in data:
                    errorMsg = _('Link protected with google recaptcha v2.')
        except Exception:
            printExc()

        if 1 != self.up.checkHostSupport(url):
            url = baseUrl.replace('/out/', '/watch/')[1:]

            hostUrl = ''
            try:
                sts, data = self.cm.getPage(self.getFullUrl('/api/' + url),
                                            self.getHeaders(url))
                if not sts: return []

                data = byteify(json.loads(data))
                printDBG(data)

                hostUrl = data['fullurl']
            except Exception:
                printExc()
        else:
            hostUrl = url

        if 1 != self.up.checkHostSupport(hostUrl):
            SetIPTVPlayerLastHostError(errorMsg)
        elif self.cm.isValidUrl(hostUrl):
            urlTab = self.up.getVideoLinkExt(hostUrl)

        return urlTab