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
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
def TryToLogin(self): printDBG("Ekstraklasa.TryToLogin") if None == self.loggedIn or self.login != config.plugins.iptvplayer.ekstraklasa_login.value or\ self.password != config.plugins.iptvplayer.ekstraklasa_password.value: self.login = config.plugins.iptvplayer.ekstraklasa_login.value self.password = config.plugins.iptvplayer.ekstraklasa_password.value self.loggedIn = False self.loginMessage = '' if '' == self.login.strip() or '' == self.password.strip(): msg = _( 'The host %s requires subscription.\nPlease fill your login and password in the host configuration - available under blue button.' ) % self.getMainUrl() GetIPTVNotify().push(msg, 'info', 10) return False clsecret = 'PHb7Aw7KZXGMYvgfEz' clid = "ClubWebClient" #UA = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0' postData = { "client_id": clid, "client_secret": clsecret, "grant_type": "password", "username": self.login.strip(), "password": self.password.strip(), } sts, data = self.cm.getPage(self.AUTH_URL, post_data=postData) if sts: printDBG("------------- auth --------------") printDBG(data) printDBG("------------------------------") try: response = json_loads(data) self.token = response["access_token"] self.loggedIn = True printDBG('EuroSportPlayer.tryTologin end loggedIn[%s]' % self.loggedIn) return True except: msg = _('Login failed. Invalid email or password.') GetIPTVNotify().push(msg, 'error', 10) return False
def listMain(self, cItem): printDBG("HDSTo.listMain") sts, data = self.getPage(self.getMainUrl()) if not sts: return self.setMainUrl(self.cm.meta['url']) if self.getFullUrl(self.cm.meta['url']).endswith('/home.php'): GetIPTVNotify().push('\n'.join(self.membersOnly), 'info', 10) printDBG(data) tmp = self.cm.ph.getDataBeetwenNodes(data, ('<nav', '>'), ('</nav', '>'), False)[1] tmp = re.compile('(<li[^>]*?>|</li>|<ul[^>]*?>|</ul>)').split(tmp) if len(tmp) > 1: try: cTree = self.listToDir(tmp[1:-1], 0)[0] params = dict(cItem) params['c_tree'] = cTree['list'][0] params['category'] = 'cat_items' self.listCatItems(params, 'list_items') except Exception: printExc() MAIN_CAT_TAB = [{'category':'search', 'title': _('Search'), 'search_item':True }, {'category': 'search_history', 'title': _('Search history'), }] self.listsTab(MAIN_CAT_TAB, cItem)
def getPage(self, url, params={}, post_data=None): sts, data = self.cm.getPage(url, params, post_data) if sts: if 'lawfilter' in self.cm.meta['url']: msg = self.cleanHtmlStr(self.cm.ph.getDataBeetwenNodes(data, ('<div', '>', 'message'), ('</div', '>'), False)[1]) if msg != '': GetIPTVNotify().push(msg, 'info', 10) return sts, data
def informAboutGeoBlockingIfNeeded(self, country, onlyOnce=True): try: if onlyOnce and self.isGeoBlockingChecked: return except Exception: self.isGeoBlockingChecked = False sts, data = self.cm.getPage( 'https://dcinfos.abtasty.com/geolocAndWeather.php') if not sts: return try: data = json_loads(data) mycountry = data.get('country', '') if mycountry != country: if not mycountry: mycountry = '?' message = _( '%s uses "geo-blocking" measures to prevent you from accessing the services from abroad.\n Host country: %s, your country: %s' ) GetIPTVNotify().push( message % (self.getMainUrl(), country, mycountry), 'info', 5) self.isGeoBlockingChecked = True except Exception: printExc()
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)
def duktape_execute(cmd_params): ret = {'sts': False, 'code': -12, 'data': ''} noDuk = False cmd = GetDukPath() if cmd != '': cmd += ' ' + cmd_params + ' 2> /dev/null' printDBG("duktape_execute cmd[%s]" % cmd) ret = iptv_execute()(cmd) if ret['code'] == 127: noDuk = True else: noDuk = True ret['code'] = 127 if noDuk: messages = [ _('The %s utility is necessary here but it was not detected.') % ('duktape') ] messages.append( _('Please consider restarting your Engima2 and agree to install the %s utlity when %s asks.' ) % ('duktape', 'E2iStream')) GetIPTVNotify().push('\n'.join(messages), 'error', 40, 'no_duktape', 40) printDBG('duktape_execute cmd ret[%s]' % ret) return ret
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)
def tryToLogin(self): printDBG('FilmyNaDzis.tryTologin start') errorMsg = _('Error communicating with the server.') if None == self.loggedIn or self.login != config.plugins.iptvplayer.filmynadzis_login.value or\ self.password != config.plugins.iptvplayer.filmynadzis_password.value: self.login = config.plugins.iptvplayer.filmynadzis_login.value self.password = config.plugins.iptvplayer.filmynadzis_password.value rm(self.COOKIE_FILE) self.loggedIn = False self.loginMessage = '' if '' == self.login.strip() or '' == self.password.strip(): msg = _( 'The host %s requires subscription.\nPlease fill your login and password in the host configuration - available under blue button.' ) % self.getMainUrl() GetIPTVNotify().push(msg, 'info', 10) return False if not self.loggedIn: # try to login postData = { 'ihcaction': 'login', 'log': self.login, 'pwd': self.password } sts, data = self.cm.getPage(self.MAIN_URL, self.defaultParams, post_data=postData) if sts: responseUrl = self.cm.meta['url'] printDBG("response url : %s" % responseUrl) if 'ihc_login_fail' in responseUrl: msg = _('Login failed. Invalid email or password.') GetIPTVNotify().push(msg, 'error', 10) self.loggedIn = False elif 'ihc_success_login' in responseUrl: self.loggedIn = True printDBG('FilmyNaDzis.tryTologin end loggedIn[%s]' % self.loggedIn) return self.loggedIn
def readYoutubeApiKey(self): if self.youtube_api_key != config.plugins.iptvplayer.api_key_youtube.value: apiKey = config.plugins.iptvplayer.api_key_youtube.value if len(apiKey) > 0 and len(apiKey) != 39: if config.plugins.iptvplayer.api_key_warning.value == True: msg = _("Wrong Youtube Api Key length") GetIPTVNotify().push(msg, 'error', 5) self.youtube_api_key = apiKey if not self.youtube_api_key: if config.plugins.iptvplayer.api_key_warning.value == True: config.plugins.iptvplayer.api_key_warning.value = False msg = _( "Youtube searches are quicker, if you fill API key in setting menu" ) msg = msg + "\n" + ( "Search for 'how to create your own Youtube api key'") GetIPTVNotify().push(msg, 'info', 5)
def informAboutGeoBlockingIfNeeded(self, country, onlyOnce=True): try: if onlyOnce and self.isGeoBlockingChecked: return except Exception: self.isGeoBlockingChecked = False sts, data = self.cm.getPage('https://dcinfos.abtasty.com/geolocAndWeather.php') if not sts: return try: data = json_loads(data.strip()[1:-1], '', True) if data['country'] != country: message = _('%s uses "geo-blocking" measures to prevent you from accessing the services from outside the %s Territory.') GetIPTVNotify().push(message % (self.getMainUrl(), country), 'info', 5) self.isGeoBlockingChecked = True except Exception: printExc()
def tryToLogin(self): printDBG("DixMax.tryToLogin") if not (config.plugins.iptvplayer.dixmax_login.value and config.plugins.iptvplayer.dixmax_password.value): msg = _( 'The host %s requires subscription.\nPlease fill your login and password in the host configuration - available under blue button.' ) % self.getMainUrl() GetIPTVNotify().push(msg, 'info', 10) return False params = dict(self.defaultParams) params['header'].update( {'Content-Type': 'application/x-www-form-urlencoded'}) postData = { 'username': config.plugins.iptvplayer.dixmax_login.value.strip(), 'password': config.plugins.iptvplayer.dixmax_password.value.strip(), 'remember': 'on' } sts, data = self.getPage(self.SESSION_URL, params, post_data=postData) if not sts: return False printDBG("---------------") printDBG(data) printDBG("---------------") if 'Error' in data: msg = data GetIPTVNotify().push(msg, 'info', 10) return False else: self.loggedIn = True return True
def _getPage(self, baseUrl, addParams = {}, post_data = None): if addParams == {}: addParams = dict(self.defaultParams) if 'cookie_items' in addParams: timestamp = int(time.time()) if timestamp > self.timestam: timestamp += 180 hash = hexlify(md5(str(timestamp)).digest()) addParams['cookie_items']['token'] = '%s,%s' % (timestamp, hash) addParams['cloudflare_params'] = {'cookie_file':self.COOKIE_FILE, 'User-Agent':self.USER_AGENT} sts, data = self.cm.getPageCFProtection(baseUrl, addParams, post_data) if sts and 'zablokowany.html' in self.cm.meta['url']: messages = self.cleanHtmlStr(data) GetIPTVNotify().push(messages, 'error', 40, self.cm.meta['url'], 40) return sts, data
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 listMain(self, cItem): printDBG("OfficialFilmIllimite.listMain") sts, data = self.getPage(self.getMainUrl()) if not sts: return self.setMainUrl(self.cm.meta['url']) tmp = self.cm.ph.getDataBeetwenNodes(data, ('<div', '>', 'rmenus'), ('</div', '>'), False)[1] tmp = re.compile('(<li[^>]*?>|</li>|<ul[^>]*?>|</ul>)').split(tmp) if len(tmp) > 1: try: cTree = self.listToDir(tmp[1:-1], 0)[0] params = dict(cItem) params['c_tree'] = cTree['list'][0] params['category'] = 'cat_items' self.listCatItems(params, 'list_items') except Exception: printExc() data = self.cm.ph.getDataBeetwenNodes(data, ('<div', '>', 'filter-widget'), ('<script', '>'), False)[1] printDBG(data) baseTitle = self.cleanHtmlStr(self.cm.ph.getDataBeetwenNodes(data, ('<div', '>', 'header'), ('</div', '>'), False)[1]) + ': %s' tabsTitles = self.cm.ph.getAllItemsBeetwenNodes(data, ('<div', '>', 'filter-tab-'), ('</div', '>'), False ) tabsData = data.split('</i>') if len(tabsData): del tabsData[0] if len(tabsTitles) == len(tabsData): for idx in range(len(tabsData)): data = self.cm.ph.getAllItemsBeetwenMarkers(tabsData[idx], '<a', '</a>') subItems = [] for item in data: url = self.getFullUrl(self.cm.ph.getSearchGroups(item, '''href=['"]([^"^']+?)["']''', 1, True)[0]) title = self.cleanHtmlStr(item) params = dict(cItem) params.update({'title':title, 'url':url, 'category':'list_items'}) subItems.append(params) if len(subItems): params = dict(cItem) params.update({'title':baseTitle % self.cleanHtmlStr(tabsTitles[idx]), 'category':'sub_items', 'sub_items':subItems}) self.addDir(params) else: GetIPTVNotify().push("Parsing error. Number of tab titles mismatched number of tabs!", 'error', 10) MAIN_CAT_TAB = [{'category':'search', 'title': _('Search'), 'search_item':True }, {'category':'search_history', 'title': _('Search history'), }] self.listsTab(MAIN_CAT_TAB, cItem)
def getPage(self, baseUrl, addParams={}, post_data=None): if addParams == {}: addParams = dict(self.defaultParams) proxy = config.plugins.iptvplayer.seriesonlineio_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['cloudflare_params'] = { 'cookie_file': self.COOKIE_FILE, 'User-Agent': self.USER_AGENT } tries = 0 while tries < 2: tries += 1 captcha = False sts, data = self.cm.getPageCFProtection( baseUrl, addParams, post_data) #self.cm.getPage(baseUrl, addParams, post_data) if 'captcha' in self.cm.meta.get('url', ''): rm(self.COOKIE_FILE) captcha = True continue break if captcha: message = _('This site is protected with Google reCaptcha v2.') SetIPTVPlayerLastHostError(message) if not self.userInformedAboutCaptchaProtection: self.userInformedAboutCaptchaProtection = True GetIPTVNotify().push(message, 'error', 10) return sts, data
def checkLogin(self): printDBG('EuroSportPlayer.checkLogin start') # try to open account informations sts, data = self.getPage(self.USER_URL) if sts: data = json_loads(data) if data['data']['attributes']['anonymous']: printDBG("------------------------EUROSPORT------------------------------------") printDBG("connected as anonymous: login needed") printDBG("---------------------------------------------------------------------") self.tryTologin() else: printDBG("------------------------EUROSPORT------------------------------------") printDBG("Ok, connected as username: %s " % data['data']['attributes']['username']) printDBG("Last Login %s" % data['data']['attributes']['lastLoginTime']) printDBG("---------------------------------------------------------------------") if config.plugins.iptvplayer.eurosportplayer_login.value != data['data']['attributes']['username']: GetIPTVNotify().push(_("Username in settings is different from %s" % data['data']['attributes']['username']) + "\n" + _("Login needed"), 'error', 10) self.tryTologin() else: self.tryTologin()
def tryTologin(self): printDBG('EuroSportPlayer.tryTologin start') errorMsg = _('Error communicating with the server.') if None == self.loggedIn or self.login != config.plugins.iptvplayer.eurosportplayer_login.value or\ self.password != config.plugins.iptvplayer.eurosportplayer_password.value: self.login = config.plugins.iptvplayer.eurosportplayer_login.value self.password = config.plugins.iptvplayer.eurosportplayer_password.value rm(self.COOKIE_FILE) self.loggedIn = False self.loginMessage = '' if '' == self.login.strip() or '' == self.password.strip(): msg = '' sts, data = self.getPage(self.getMainUrl()) if sts and '/subscribe' not in data: msg = self.cleanHtmlStr(self.cm.ph.getDataBeetwenNodes(data, ('<div', '>', '"message"'), ('</div', '>'))[1]) if msg == '': msg = _('The host %s requires subscription.\nPlease fill your login and password in the host configuration - available under blue button.') % self.getMainUrl() GetIPTVNotify().push(msg, 'info', 10) return False if not self.getToken('init'): msg = _(errorMsg) + _('\nError[1].') GetIPTVNotify().push(msg, 'error', 10) return False try: baseUrl = self.serverApiData['server_path']['server'] + '/' url = self.getFullUrl('/login', baseUrl) sts, data = self.getPage(url) if not sts: return False getParams = dict(self.defaultParams) getParams['raw_post_data'] = True getParams['header'] = dict(self.AJAX_HEADER) clientData = self.serverApiData['prod']['authentication']['client'] url = clientData['links'][0]['href'] getParams['header'].update(clientData['links'][0]['headers']) getParams['header']['Authorization'] = getParams['header']['Authorization'].replace('{encodedUserToken}', self.tokenData['access_token']) post_data = '{"type":"email-password","email":{"address":"%s"},"password":{"value":"%s"}}' % (self.login, self.password) sts, data = self.getPage(url, getParams, post_data) if not sts and '401' in str(data): msg = _('Login failed. Invalid email or password.') GetIPTVNotify().push(msg, 'error', 10) return False else: data = byteify(json.loads(data)) printDBG(data) self.tokenData['access_code'] = data['code'] self.tokenData['access_timeout'] = time.time() + (data['exp'] - data['iat']) / 1000.0 if not self.getToken('code'): msg = _(errorMsg) + _('\nError[2].') GetIPTVNotify().push(msg, 'error', 10) return False self.loggedIn = True except Exception: printExc() printDBG('EuroSportPlayer.tryTologin end loggedIn[%s]' % self.loggedIn) return self.loggedIn
def getURLRequestData(self, params={}, post_data=None): def urlOpen(req, customOpeners, timeout): if len(customOpeners) > 0: opener = urllib2.build_opener(*customOpeners) if timeout != None: response = opener.open(req, timeout=timeout) else: response = opener.open(req) else: if timeout != None: response = urllib2.urlopen(req, timeout=timeout) else: response = urllib2.urlopen(req) return response if IsMainThread(): msg1 = _( 'It is not allowed to call getURLRequestData from main thread.' ) msg2 = _( 'You should never perform block I/O operations in the __init__.' ) msg3 = _( 'In next release exception will be thrown instead of this message!' ) GetIPTVNotify().push('%s\n\n%s\n\n%s' % (msg1, msg2, msg3), 'error', 40) if not self.useMozillaCookieJar: cj = cookielib.LWPCookieJar() else: cj = cookielib.MozillaCookieJar() response = None req = None out_data = None opener = None metadata = None timeout = params.get('timeout', None) if 'host' in params: host = params['host'] else: host = self.HOST if 'header' in params: headers = params['header'] elif None != self.HEADER: headers = self.HEADER else: headers = {'User-Agent': host} if 'User-Agent' not in headers: headers['User-Agent'] = host metadata = {} printDBG('pCommon - getURLRequestData() -> params: ' + str(params)) printDBG('pCommon - getURLRequestData() -> headers: ' + str(headers)) customOpeners = [] #cookie support if 'use_cookie' not in params and 'cookiefile' in params and ( 'load_cookie' in params or 'save_cookie' in params): params['use_cookie'] = True if params.get('use_cookie', False): if params.get('load_cookie', False): try: cj.load(params['cookiefile'], ignore_discard=True) except IOError: printDBG('Cookie file [%s] not exists' % params['cookiefile']) except Exception: printExc() try: for cookieKey in params.get('cookie_items', {}).keys(): printDBG("cookie_item[%s=%s]" % (cookieKey, params['cookie_items'][cookieKey])) cookieItem = cookielib.Cookie( version=0, name=cookieKey, value=params['cookie_items'][cookieKey], port=None, port_specified=False, domain='', domain_specified=False, domain_initial_dot=False, path='/', path_specified=True, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={'HttpOnly': None}, rfc2109=False) cj.set_cookie(cookieItem) except Exception: printExc() customOpeners.append(urllib2.HTTPCookieProcessor(cj)) if params.get('no_redirection', False): customOpeners.append(NoRedirection()) # debug #customOpeners.append(urllib2.HTTPSHandler(debuglevel=1)) #customOpeners.append(urllib2.HTTPHandler(debuglevel=1)) if not IsHttpsCertValidationEnabled(): try: if params.get('ssl_protocol', None) != None: ctx = ssl._create_unverified_context( params['ssl_protocol']) else: ctx = ssl._create_unverified_context() customOpeners.append(urllib2.HTTPSHandler(context=ctx)) except Exception: pass elif params.get('ssl_protocol', None) != None: ctx = ssl.SSLContext(params['ssl_protocol']) customOpeners.append(urllib2.HTTPSHandler(context=ctx)) #proxy support if self.useProxy: http_proxy = self.proxyURL else: http_proxy = '' #proxy from parameters (if available) overwrite default one if 'http_proxy' in params: http_proxy = params['http_proxy'] if '' != http_proxy: printDBG('getURLRequestData USE PROXY') customOpeners.append(urllib2.ProxyHandler({"http": http_proxy})) customOpeners.append(urllib2.ProxyHandler({"https": http_proxy})) pageUrl = params['url'] proxy_gateway = params.get('proxy_gateway', '') if proxy_gateway != '': pageUrl = proxy_gateway.format(urllib.quote_plus(pageUrl, '')) printDBG("pageUrl: [%s]" % pageUrl) if None != post_data: printDBG('pCommon - getURLRequestData() -> post data: ' + str(post_data)) if params.get('raw_post_data', False): dataPost = post_data elif params.get('multipart_post_data', False): customOpeners.append(MultipartPostHandler()) dataPost = post_data else: dataPost = urllib.urlencode(post_data) req = urllib2.Request(pageUrl, dataPost, headers) else: req = urllib2.Request(pageUrl, None, headers) if not params.get('return_data', False): out_data = urlOpen(req, customOpeners, timeout) else: gzip_encoding = False try: response = urlOpen(req, customOpeners, timeout) if response.info().get('Content-Encoding') == 'gzip': gzip_encoding = True try: metadata['url'] = response.geturl() metadata['status_code'] = response.getcode() if 'Content-Type' in response.info(): metadata['content-type'] = response.info( )['Content-Type'] except Exception: pass data = response.read() response.close() except urllib2.HTTPError, e: ignoreCodeRanges = params.get('ignore_http_code_ranges', [(404, 404), (500, 500)]) ignoreCode = False metadata['status_code'] = e.code for ignoreCodeRange in ignoreCodeRanges: if e.code >= ignoreCodeRange[ 0] and e.code <= ignoreCodeRange[1]: ignoreCode = True break if ignoreCode: printDBG('!!!!!!!! %s: getURLRequestData - handled' % e.code) if e.fp.info().get('Content-Encoding', '') == 'gzip': gzip_encoding = True try: metadata['url'] = e.fp.geturl() if 'Content-Type' in e.fp.info(): metadata['content-type'] = e.fp.info( )['Content-Type'] except Exception: pass data = e.fp.read() #e.msg #e.headers elif e.code == 503: if params.get('use_cookie', False): new_cookie = e.fp.info().get('Set-Cookie', '') printDBG("> new_cookie[%s]" % new_cookie) cj.save(params['cookiefile'], ignore_discard=True) raise e else: if e.code in [300, 302, 303, 307] and params.get( 'use_cookie', False) and params.get( 'save_cookie', False): new_cookie = e.fp.info().get('Set-Cookie', '') printDBG("> new_cookie[%s]" % new_cookie) #for cookieKey in params.get('cookie_items', {}).keys(): # cj.clear('', '/', cookieKey) cj.save(params['cookiefile'], ignore_discard=True) raise e try: if gzip_encoding: printDBG('Content-Encoding == gzip') buf = StringIO(data) f = gzip.GzipFile(fileobj=buf) out_data = f.read() else: out_data = data except Exception as e: printExc() msg1 = _( "Critical Error – Content-Encoding gzip cannot be handled!" ) msg2 = _("Last error:\n%s" % str(e)) GetIPTVNotify().push('%s\n\n%s' % (msg1, msg2), 'error', 20) out_data = data
def getPage(self, baseUrl, addParams = {}, post_data = None): images = [] errorMessages = [] if addParams == {}: addParams = dict(self.defaultParams) baseUrl = self.cm.iriToUri(baseUrl) proxy = config.plugins.iptvplayer.kissanime_proxy.value printDBG(">> " + proxy) 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['cloudflare_params'] = {'domain':self.up.getDomain(baseUrl), 'cookie_file':self.COOKIE_FILE, 'User-Agent':self.USER_AGENT, 'full_url_handle':self.getFullUrl} while True: sts, data = self.cm.getPageCFProtection(baseUrl, addParams, post_data) if sts and 'areyouhuman' in self.cm.meta['url'].lower(): errorMessages = [] formData = '' tmp = self.cm.ph.getAllItemsBeetwenMarkers(data, '<form', '</form>', withMarkers=False, caseSensitive=False) for item in tmp: if 'answerCap' in item: formData = item break messages = [] tmp = self.cm.ph.getAllItemsBeetwenMarkers(formData, '<p', '</p>') for item in tmp: item = self.cleanHtmlStr(item) if item != '': messages.append(item) if len(messages) < 2: errorMessages.append(_('Unknown captcha form! Data: "%s"') % messages) break action = self.cm.ph.getSearchGroups(formData, '''action=['"]([^'^"]+?)['"]''', ignoreCase=True)[0] if action == '': action = '/' action = self.getFullUrl(action) tmp = self.cm.ph.getAllItemsBeetwenMarkers(formData, '<input', '>', False, False) post_data2 = {} for item in tmp: name = self.cm.ph.getSearchGroups(item, '''name=['"]([^'^"]+?)['"]''', ignoreCase=True)[0] value = self.cm.ph.getSearchGroups(item, '''value=['"]([^'^"]+?)['"]''', ignoreCase=True)[0] if name != '': post_data2[name] = value 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', 'jpg', 'png'], 'check_first_bytes':['\xFF\xD8','\xFF\xD9','\x89\x50\x4E\x47'], 'header':header} ) prevMeta = self.cm.meta images = [] tmp = self.cm.ph.getAllItemsBeetwenMarkers(formData, '<img', '>', False, False) for item in tmp: index = self.cm.ph.getSearchGroups(item, '''indexValue=['"]([^'^"]+?)['"]''', ignoreCase=True)[0] imgUrl = self.getFullIconUrl(self.cm.ph.getSearchGroups(item, '''src=['"]([^'^"]+?)['"]''', ignoreCase=True)[0]) if index != '' and imgUrl != '': filePath = GetTmpDir('.iptvplayer_captcha_picture_%s.jpg' % index) rm(filePath) ret = self.cm.saveWebFile(filePath, imgUrl.replace('&', '&'), params) if ret.get('sts'): images.append({'path':filePath, 'id':index}) continue errorMessages.append(_('Download "%s" in to "%s" failed!') % (imgUrl, filePath)) else: errorMessages.append(_('Unknow data in the captcha item!')) errorMessages.append('item: "%s"' % item) break self.cm.meta = prevMeta if 0 == len(errorMessages): printDBG("++++++++++++++++++++++++++++++++++") printDBG('action: %s' % action) printDBG('post_data: %s' % post_data2) printDBG('images: %s' % images) printDBG("++++++++++++++++++++++++++++++++++") message = '\n'.join(messages[1:]) if ' TWO ' in message: maxSelItems = 2 acceptLabel = None else: maxSelItems = None acceptLabel = _('-- OK --') retArg = self.sessionEx.waitForFinishOpen(IPTVMultipleImageSelectorWidget, title='Captcha', message=message, message_height=100, images=images, image_width=160, image_height=160, accep_label=acceptLabel, max_sel_items=maxSelItems) printDBG(retArg) if retArg and len(retArg) and isinstance(retArg[0], list): printDBG(retArg[0]) post_data2['answerCap'] = ','.join(retArg[0]) + ',' addParams2 = dict(addParams) addParams2['header'] = dict(addParams2['header']) addParams2['header']['Referer'] = prevMeta['url'] sts2, data2 = self.cm.getPageCFProtection(action, addParams, post_data2) #printDBG("++++++++++++++++++++++++++++++++++") #printDBG(data2) #printDBG("++++++++++++++++++++++++++++++++++") if sts2: if 'areyouhuman' in self.cm.meta['url'].lower(): printDBG(">>> TRY AGAIN") continue else: sts, data = sts2, data2 else: self.cm.meta = prevMeta break if len(errorMessages): GetIPTVNotify().push('\n'.join(errorMessages), 'error', 10) #printDBG("++++++++++++++++++++++++++++++++++") #printDBG(data) #printDBG("++++++++++++++++++++++++++++++++++") for item in images: rm(item['path']) return sts, data
def tryTologin(self): printDBG('tryTologin start') if None == self.loggedIn or self.login != config.plugins.iptvplayer.allboxtv_login.value or\ self.password != config.plugins.iptvplayer.allboxtv_password.value: self.login = config.plugins.iptvplayer.allboxtv_login.value self.password = config.plugins.iptvplayer.allboxtv_password.value rm(self.COOKIE_FILE) self.loggedIn = False self.loginMessage = '' if '' == self.login.strip() or '' == self.password.strip(): 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, 'info', 10) return False sts, data = self.getPage(self.getMainUrl()) if not sts: return False url = self.getFullUrl('/logowanie') sts, data = self.getPage(url) if not sts: return False sts, data = self.cm.ph.getDataBeetwenNodes( data, ('<form', '>', 'loginForm'), ('</form', '>')) if not sts: return False actionUrl = self.getFullUrl( self.cm.ph.getSearchGroups(data, '''action=['"]([^'^"]+?)['"]''')[0]) if actionUrl == '': actionUrl = url data = self.cm.ph.getAllItemsBeetwenMarkers(data, '<input', '>') post_data = {} for item in data: name = self.cm.ph.getSearchGroups( item, '''name=['"]([^'^"]+?)['"]''')[0] value = self.cm.ph.getSearchGroups( item, '''value=['"]([^'^"]+?)['"]''')[0] post_data[name] = value post_data.update({ 'email': self.login, 'password': self.password, 'form_login_rememberme': 'on' }) httpParams = dict(self.defaultParams) httpParams['header'] = dict(httpParams['header']) httpParams['header']['Referer'] = url sts, data = self.cm.getPage(actionUrl, httpParams, post_data) if sts and '/wyloguj' in data: printDBG('tryTologin OK') self.loggedIn = True data = self.cm.ph.getDataBeetwenNodes( data, ('<', '>', 'mobile-header'), ('</ul', '>'))[1] data = self.cm.ph.getAllItemsBeetwenMarkers( data, '<li', '</li>') self.loginMessage = [] for item in data: item = ph.clean_html(item) if item == '': continue self.loginMessage.append(item) self.loginMessage = '[/br]'.join(self.loginMessage) else: if sts: errMsg = [] tmp = self.cm.ph.getAllItemsBeetwenNodes( data, ('<span', '>', 'required'), ('</span', '>'), False) for it in tmp: errMsg.append(ph.clean_html(it)) else: errMsg = [_('Connection error.')] self.sessionEx.open(MessageBox, _('Login failed.') + '\n' + '\n'.join(errMsg), type=MessageBox.TYPE_ERROR, timeout=10) printDBG('tryTologin failed') return self.loggedIn
def tryTologin(self): printDBG('EuroSportPlayer.tryTologin start') errorMsg = _('Error communicating with the server.') if None == self.loggedIn or self.login != config.plugins.iptvplayer.eurosportplayer_login.value or\ self.password != config.plugins.iptvplayer.eurosportplayer_password.value: self.login = config.plugins.iptvplayer.eurosportplayer_login.value self.password = config.plugins.iptvplayer.eurosportplayer_password.value rm(self.COOKIE_FILE) self.loggedIn = False self.loginMessage = '' if '' == self.login.strip() or '' == self.password.strip(): msg = _( 'The host %s requires subscription.\nPlease fill your login and password in the host configuration - available under blue button.' ) % self.getMainUrl() GetIPTVNotify().push(msg, 'info', 10) return False try: # get token tokenUrl = self.TOKEN_URL sts, data = self.getPage(tokenUrl) printDBG(data) # get config (also with catpcha site-key) sts, data = self.getPage(self.CONFIG_URL) printDBG(data) # solve captcha to login (token, errorMsgTab) = CaptchaHelper().processCaptcha( self.recaptcha_sitekey, self.LOGIN_URL) if not token: printDBG(str(errorMsgTab)) return printDBG('Captcha token :%s' % token) # try to login header = { 'User-Agent': self.USER_AGENT, 'Referer': self.LOGIN_URL, 'x-disco-client': 'WEB:x86_64:WEB_AUTH:1.1.0', 'x-disco-recaptcha-token': token, 'content-type': 'application/json' } postData = { 'credentials': { 'username': self.login, 'password': self.password } } url = "https://eu3-prod-direct.eurosportplayer.com/login" httpParams = { 'header': header, 'with_metadata': True, 'use_cookie': True, 'load_cookie': True, 'save_cookie': True, 'cookiefile': self.COOKIE_FILE, 'raw_post_data': True } sts, data = self.getPage(url, httpParams, post_data=json_dumps(postData)) ''' good login { "data" : { "attributes" : { "lastLoginTime" : "2019-11-01T21:45:15Z", "realm" : "eurosport", "token" : "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJVU0VSSUQ6ZXVyb3Nwb3J0OmI4OGQ0YTBhLWQwZDctNDdkZi1iMzI5LWJjNmM5ZDNiOTRjYyIsImp0aSI6InRva2VuLThkOWYxMDgwLWUwNGEtNDMyZi04NDY1LWUwYTgyNDljMjEwMyIsImFub255bW91cyI6ZmFsc2UsImlhdCI6MTU3MjY4NDk3MX0.DtSAY9kAVfwcJKhPXczRlPW3CACd6ZmZwZvJilIrlv8" }, "id" : "token-8d9f1080-e04a-432f-8465-e0a8249c2103", "type" : "token" }, "meta" : { "site" : { "attributes" : { "brand" : "eurosport", "websiteHostName" : "it.eurosportplayer.com" }, "id" : "IT", "type" : "site" } } } ''' ''' example: wrong password { "errors" : [ { "status" : "401", "code" : "unauthorized", "id" : "ATwRg09NZG", "detail" : "" } ] } ''' if not sts and '401' in str(data): msg = _('Login failed. Invalid email or password.') GetIPTVNotify().push(msg, 'error', 10) return False else: data = json_loads(data) printDBG(str(data)) self.loggedIn = True except Exception: printExc() printDBG('EuroSportPlayer.tryTologin end loggedIn[%s]' % self.loggedIn) return self.loggedIn
def getPage(self, url, params={}, post_data=None): mainParamsUrl = params if mainParamsUrl == {}: mainParamsUrl = dict(self.defaultParams) while True: sts, data = self.cm.getPage(url, mainParamsUrl, post_data) if sts and data.meta.get('status_code', 0) in [410, 404]: tmp = re.sub("<!--[\s\S]*?-->", "", data) if 'sitekey' in tmp: 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) break elif 'captcha' in tmp: paramsUrl = dict(self.defaultParams) paramsUrl['header'] = dict(paramsUrl['header']) cUrl = self.cm.meta['url'] tmp = ph.find(tmp, ('<div', '>', 'footer-404'), '</form>')[1] captchaTitle = self.cleanHtmlStr(tmp.split('<form', 1)[0]) sendLabel = self.cleanHtmlStr( ph.getattr( ph.find(tmp, ('<input', '>', 'Button'), flags=(ph.IGNORECASE | ph.START_E))[1], 'value')) captchaLabel = self.cleanHtmlStr( ph.getattr(tmp, 'placeholder')) captchaLabel = '%s %s' % (sendLabel, captchaLabel) if captchaLabel.strip() == '': captchaLabel = _('Captcha') if captchaTitle == '': captchaTitle = captchaLabel else: captchaTitle = '%s\n\n%s' % (captchaTitle, captchaLabel) sendLabel = _('Send') imgUrl = self.getFullIconUrl( ph.search(tmp, ph.IMAGE_SRC_URI_RE)[1], cUrl) actionUrl = self.getFullUrl(ph.getattr(tmp, 'action'), cUrl) if actionUrl == '': actionUrl = cUrl raw_post = ph.findall(tmp, '<input', '>', flags=ph.IGNORECASE) printDBG(tmp) captcha_post_data = {} for it in raw_post: val = ph.getattr(it, 'value').strip() name = ph.getattr(it, 'name') if name == '': continue captcha_post_data[name] = val 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') rm(filePath) ret = self.cm.saveWebFile(filePath, imgUrl.replace('&', '&'), params) if not ret.get('sts'): errorMsg = _('Fail to get "%s".') % imgUrl SetIPTVPlayerLastHostError(errorMsg) GetIPTVNotify().push(errorMsg, 'error', 10) break params = deepcopy(IPTVMultipleInputBox.DEF_PARAMS) params['accep_label'] = sendLabel params['title'] = captchaLabel params['status_text'] = captchaTitle params['status_text_hight'] = 200 params['with_accept_button'] = True params['list'] = [] item = deepcopy(IPTVMultipleInputBox.DEF_INPUT_PARAMS) item['label_size'] = (660, 110) item['input_size'] = (680, 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]) captcha_post_data['captcha'] = retArg[0][0] paramsUrl['header']['Referer'] = cUrl sts, tmp = self.cm.getPage(actionUrl, paramsUrl, captcha_post_data) printDBG(tmp) else: break break return sts, data
msg2 = _("Last error:\n%s" % str(e)) GetIPTVNotify().push('%s\n\n%s' % (msg1, msg2), 'error', 20) out_data = data if params.get('use_cookie', False) and params.get( 'save_cookie', False): try: cj.save(params['cookiefile'], ignore_discard=True) except Exception as e: printExc() msg1 = _("Critical Error – cookie can't be saved!") msg2 = _("Last error:\n%s" % str(e)) msg3 = _( "Please make sure that the folder for cache data (set in the configuration) is writable." ) GetIPTVNotify().push('%s\n\n%s\n\n%s' % (msg1, msg2, msg3), 'error', 20) SetTmpCookieDir() raise e if params.get('return_data', False) and params.get( 'convert_charset', True): encoding = '' if 'content-type' in metadata: encoding = self.ph.getSearchGroups( metadata['content-type'], '''charset=([A-Za-z0-9\-]+)''', 1, True)[0].strip().upper() if encoding == '' and params.get('search_charset', False): encoding = self.ph.getSearchGroups( out_data, '''(<meta[^>]+?Content-Type[^>]+?>)''',
def getLinksForVideo(self, cItem): printDBG("Ekstraklasa.getLinksForVideo '%s'" % cItem) url = cItem.get('url', '') if not url: scheduleDate = cItem.get('schedule_date', '') if scheduleDate: msg = _("Stream starts from %s") % scheduleDate GetIPTVNotify().push(msg, 'info', 10) return [] if not self.loggedIn: # need to login to view videos self.TryToLogin() if not self.loggedIn: return [] headers = { 'User-Agent': "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36", 'Accept': 'application/json', 'Accept-Language': 'pl,en-US;q=0.7,en;q=0.3', 'Referer': 'https://www.ekstraklasa.tv/', 'Content-Type': 'application/json', 'Authorization': 'Bearer %s' % self.token, 'Origin': 'https://www.ekstraklasa.tv', 'DNT': '1', } linksTab = [] sts, data = self.cm.getPage(url, {'header': headers}) if sts: printDBG("*********************") printDBG(data) printDBG("*********************") response = json_loads(data) url = response['data']['url'] playlist = getDirectM3U8Playlist(url, checkExt=False, variantCheck=True, checkContent=True, sortWithMaxBitrate=99999999) if (config.plugins.iptvplayer.ekstraklasa_defaultres.value == None ) or (config.plugins.iptvplayer.ekstraklasa_defaultres.value == '') or (config.plugins.iptvplayer. ekstraklasa_defaultres.value == "0"): linksTab.extend(playlist) else: def_res = int( config.plugins.iptvplayer.ekstraklasa_defaultres.value) printDBG(json_dumps(playlist)) for track in playlist: if int(track.get("bitrate", "0")) < (def_res * 1000): linksTab.append(track) break else: msg = _("You are not allowed to play this video") GetIPTVNotify().push(msg, 'info', 10) return linksTab
def exploreItem(self, cItem, nextCategory): printDBG("SerijeOnline.exploreItem [%s]" % cItem) self.cm.clearCookie(self.COOKIE_FILE, ['PHPSESSID', '__cfduid', 'cf_clearance']) sts, data = self.getPage(cItem['url']) if not sts: return desc = '' #desc = self.cleanHtmlStr(self.cm.ph.getDataBeetwenNodes(data, ('<h2', '>', 'upper-blue'), ('</div', '>'))[1]) if desc == '': desc = cItem.get('desc', '') tmp = self.cm.ph.getDataBeetwenNodes(data, ('<div', '>', 'pm-submit-data'), ('</div', '>'))[1] tmp = self.cm.ph.getAllItemsBeetwenMarkers(tmp, '<a', '</a>') if len(tmp) > 1: catUrl = self.getFullUrl(self.cm.ph.getSearchGroups(tmp[-1], '''href=['"]([^'^"]+?)['"]''')[0]) catTitle = self.cleanHtmlStr(tmp[-1]) else: catUrl = '' catTitle = '' printDBG("################# catUrl[%s] catTitle[%s]" % (catUrl, catTitle)) num = 0 tmp = self.cm.ph.getDataBeetwenNodes(data, ('<div', '>', 'Playerholder'), ('</div', '>'))[1] if tmp == '': printDBG("#################") data = self.cm.ph.getAllItemsBeetwenMarkers(data, 'data:', '}', False) printDBG(data) for item in data: if 'getplayer' in item: try: query = byteify(json.loads(item + '}'), '', True) query = urllib.urlencode(query) url = self.getFullUrl("/ajax.php") + '?' + query sts, data = self.getPage(url) printDBG("---------------") printDBG(data) if sts: if 'Playerholder' in data: tmp = data else: msg = self.cleanHtmlStr(self.cm.ph.getDataBeetwenNodes(data, ('<div', '>', 'restricted-video'), ('</h2', '>'))[1]) if msg != '': GetIPTVNotify().push(msg, 'error', 10) except Exception: printExc() break printDBG(tmp) data = re.compile('''<iframe[^>]+?src=['"]([^"^']+?)['"]''', re.IGNORECASE).findall(tmp) for url in data: url = self.getFullUrl(url) #if 1 != self.up.checkHostSupport(url): continue if not self.cm.isValidUrl(url): continue num += 1 if len(data) > 1: title = '%s. %s' % (num, cItem['title']) else: title = cItem['title'] params = dict(cItem) params.update({'good_for_fav': False, 'title': title, 'desc': desc, 'url': url}) self.addVideo(params) if self.cm.isValidUrl(catUrl) and catUrl != cItem['url'] and catUrl != cItem.get('cat_url', ''): params = dict(cItem) params.update({'good_for_fav': True, 'category': nextCategory, 'title': catTitle, 'url': catUrl, 'cat_url': catUrl, 'desc': ''}) self.addDir(params)
def tryTologin(self): printDBG('BBCSport.tryTologin start') netErrorMsg = _('Error communicating with the server.') datErrorMsg = _('Data mismatch.') if config.plugins.iptvplayer.bbc_use_web_proxy.value: if False != self.loggedIn: rm(self.COOKIE_FILE) self.loggedIn = False return False if None == self.loggedIn or self.login != config.plugins.iptvplayer.bbc_login.value or\ self.password != config.plugins.iptvplayer.bbc_password.value: self.login = config.plugins.iptvplayer.bbc_login.value self.password = config.plugins.iptvplayer.bbc_password.value rm(self.COOKIE_FILE) self.loggedIn = False self.loginMessage = '' if '' == self.login.strip() or '' == self.password.strip(): #msg = _('You now need to sign in to watch.\nPlease fill your login and password in the host configuration - available under blue button.') #GetIPTVNotify().push(msg, 'info', 10) return False sts, data = self.getPage(self.getFullUrl('/sport')) if not sts: msg = _(netErrorMsg) + _('\nError[1].') GetIPTVNotify().push(msg, 'error', 10) return False cUrl = data.meta['url'] self.setMainUrl(cUrl) try: url = self.sessionUrl + '?ptrt=' + urllib.quote( cUrl.split('?', 1)[0]) + '&userOrigin=sport&context=sport' sts, data = self.getPage(url) if not sts: msg = _(netErrorMsg) + _('\nError[2].') GetIPTVNotify().push(msg, 'error', 10) return False cUrl = data.meta['url'] sts, data = self.cm.ph.getDataBeetwenNodes( data, ('<form', '>'), ('</form', '>')) if not sts: msg = _(datErrorMsg) + _('\nError[3].') GetIPTVNotify().push(msg, 'error', 10) return False actionUrl = self.cm.getFullUrl( self.cm.ph.getSearchGroups( data, '''action=['"]([^'^"]+?)['"]''')[0].replace( '&', '&'), self.cm.getBaseUrl(cUrl)) if actionUrl == '': actionUrl = cUrl formData = self.cm.ph.getAllItemsBeetwenMarkers( data, '<input', '>') post_data = {} for item in formData: name = self.cm.ph.getSearchGroups( item, '''name=['"]([^'^"]+?)['"]''')[0] value = self.cm.ph.getSearchGroups( item, '''value=['"]([^'^"]+?)['"]''')[0] post_data[name] = value post_data.update({ 'username': self.login, 'password': self.password }) httpParams = dict(self.defaultParams) httpParams['header'] = dict(httpParams['header']) httpParams['header']['Referer'] = self.getMainUrl() sts, data = self.cm.getPage(actionUrl, httpParams, post_data) if sts: printDBG('tryTologin OK') if '/signin' in data.meta['url']: msg = self.cleanHtmlStr( self.cm.ph.getDataBeetwenNodes( data, ('<p', '>', 'form-message'), ('</p', '>'))[1]) GetIPTVNotify().push( _('Login failed.') + '\n' + msg, 'error', 10) return False self.loggedIn = True msg = _( "A TV License is required to watch BBC iPlayer streams, see the BBC website for more information: https://www.bbc.co.uk/iplayer/help/tvlicence" ) GetIPTVNotify().push(msg, 'info', 5) self.loginMessage = msg else: msg = _(netErrorMsg) + _('\nError[4].') GetIPTVNotify().push(msg, 'error', 10) return False except Exception: printExc() printDBG('EuroSportPlayer.tryTologin end loggedIn[%s]' % self.loggedIn) return self.loggedIn
def tryTologin(self): printDBG('BBCSport.tryTologin start') netErrorMsg = _('Error communicating with the server.') datErrorMsg = _('Data mismatch.') if config.plugins.iptvplayer.bbc_use_web_proxy.value: if False != self.loggedIn: rm(self.COOKIE_FILE) self.loggedIn = False return False elif None == self.loggedIn or self.login != config.plugins.iptvplayer.bbc_login.value or self.password != config.plugins.iptvplayer.bbc_password.value: self.login = config.plugins.iptvplayer.bbc_login.value self.password = config.plugins.iptvplayer.bbc_password.value rm(self.COOKIE_FILE) self.loggedIn = False self.loginMessage = '' if '' == self.login.strip() or '' == self.password.strip(): return False sts, data = self.getPage(self.getFullUrl('/sport')) if not sts: msg = _(netErrorMsg) + _('\nError[1].') GetIPTVNotify().push(msg, 'error', 10) return False cUrl = data.meta['url'] self.setMainUrl(cUrl) try: url = self.sessionUrl + '?ptrt=' + urllib.quote(cUrl.split('?', 1)[0]) + '&userOrigin=sport&context=sport' sts, data = self.getPage(url) if not sts: msg = _(netErrorMsg) + _('\nError[2].') GetIPTVNotify().push(msg, 'error', 10) return False cUrl = data.meta['url'] sts, data = ph.find(data, ('<form', '>'), '</form>') if not sts: msg = _(datErrorMsg) + _('\nError[3].') GetIPTVNotify().push(msg, 'error', 10) return False actionUrl = self.cm.getFullUrl(ph.getattr(data, 'action')[0].replace('&', '&'), cUrl) if actionUrl == '': actionUrl = cUrl formData = ph.findall(data, '<input', '>') post_data = {} for item in formData: name = ph.getattr(item, 'name') value = ph.getattr(item, 'value') post_data[name] = value post_data.update({'username': self.login, 'password': self.password}) httpParams = dict(self.defaultParams) httpParams['header'] = MergeDicts(httpParams['header'], {'Referer': self.getMainUrl()}) sts, data = self.cm.getPage(actionUrl, httpParams, post_data) if sts: printDBG('tryTologin OK') if '/signin' in data.meta['url']: msg = ph.clean_html(ph.find(data, ('<p', '>', 'form-message'), '</p>', flags=0)[1]) GetIPTVNotify().push(_('Login failed.') + '\n' + msg, 'error', 10) return False self.loggedIn = True msg = _('A TV License is required to watch BBC iPlayer streams, see the BBC website for more information: https://www.bbc.co.uk/iplayer/help/tvlicence') GetIPTVNotify().push(msg, 'info', 5) self.loginMessage = msg else: msg = _(netErrorMsg) + _('\nError[4].') GetIPTVNotify().push(msg, 'error', 10) return False except Exception: printExc() printDBG('EuroSportPlayer.tryTologin end loggedIn[%s]' % self.loggedIn) return self.loggedIn else: return