Exemple #1
0
    def __init__(self):
        self.MAIN_URL = 'http://pierwsza.tv/'
        self.HTTP_HEADER = {
            'User-Agent':
            'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/37.0.2062.120 Chrome/37.0.2062.120 Safari/537.36',
            'Referer': self.MAIN_URL
        }

        self.COOKIE_FILE = GetCookieDir('pierwszatv.cookie')
        self.COOKIE_FILE2 = GetCookieDir('pierwszatv2.cookie')
        self.COOKIE_FILE3 = GetCookieDir('pierwszatv3.cookie')
        self.sessionEx = MainSessionWrapper()
        self.cm = common()
        self.up = urlparser()
        self.http_params = {
            'header': dict(self.HTTP_HEADER),
            'save_cookie': True,
            'load_cookie': True,
            'cookiefile': self.COOKIE_FILE
        }
        self.http_params2 = {
            'header': dict(self.HTTP_HEADER),
            'save_cookie': True,
            'load_cookie': True,
            'cookiefile': self.COOKIE_FILE2
        }
        self.http_params3 = {
            'header': dict(self.HTTP_HEADER),
            'save_cookie': True,
            'load_cookie': True,
            'cookiefile': self.COOKIE_FILE3
        }
        self.cacheList = {}

        self.mainConnectData = {}
Exemple #2
0
 def __init__(self):
     self.cm = common()
     self.up = urlparser()
     self.sessionEx = MainSessionWrapper()
     self.cookiePath = GetCookieDir('ustvnow.cookie')
     self.token = ''
     self.passkey = ''
     
     HTTP_HEADER= dict(self.HTTP_HEADER)
     HTTP_HEADER.update( {'Content-Type':'application/x-www-form-urlencoded'} )
     self.defParams = {'header':HTTP_HEADER, 'cookiefile': self.cookiePath, 'use_cookie': True, 'load_cookie':True, 'save_cookie':True}
Exemple #3
0
 def __init__(self, lang='en'):
     self.HTTP_HEADER = {
         'Accept-Language':
         lang,
         'Referer':
         'https://www.google.com/recaptcha/api2/demo',
         'User-Agent':
         'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.18) Gecko/20110621 Mandriva Linux/1.9.2.18-0.1mdv2010.2 (2010.2) Firefox/3.6.18'
     }
     self.cm = common()
     self.sessionEx = MainSessionWrapper()
     self.COOKIE_FILE = GetCookieDir('google.cookie')
 def __init__(self):
     self.COOKIE_FILE = GetCookieDir('goldvodtv.cookie')
     self.sessionEx = MainSessionWrapper()
     self.cm = common()
     self.up = urlparser()
     self.http_params = {}
     self.http_params.update({
         'save_cookie': True,
         'load_cookie': True,
         'cookiefile': self.COOKIE_FILE
     })
     self.cacheList = {}
     self.loggedIn = False
    def __init__(self):
        CBaseHostClass.__init__(self)
        self.sessionEx = MainSessionWrapper()
        self.MAIN_URL = 'http://www.wagasworld.com/'
        self.HTTP_HEADER = {
            'User-Agent':
            'Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:12.0) Gecko/20100101 Firefox/12.0',
            'Referer': self.MAIN_URL
        }

        self.COOKIE_FILE = GetCookieDir('wagasworld.cookie')
        self.http_params = {
            'header': dict(self.HTTP_HEADER),
            'save_cookie': True,
            'load_cookie': True,
            'cookiefile': self.COOKIE_FILE
        }
    def getVideoLink(self, url):
        printDBG("WeebTvApi.getVideoLink")
        rtmp = ''
        channel = url
        premium = 0
        if 0 == len(channel): return ''
        try:
            if config.plugins.iptvplayer.weebtv_premium.value:
                username = config.plugins.iptvplayer.weebtv_login.value
                password = config.plugins.iptvplayer.weebtv_password.value
                postdata = {'username': username, 'userpassword': password}
            else:
                postdata = {'username': '', 'userpassword': ''}
            postdata['channel'] = channel
            postdata['platform'] = WeebTvApi.HOST

            sts, data = self.cm.getPage(WeebTvApi.PLAYERURL,
                                        WeebTvApi.DEFPARAMS, postdata)
            if sts:
                printDBG("||||||||||||||||||||||||||||| " + data)
                parser = UrlParser()
                params = parser.getParams(data)
                status = parser.getParam(params, '0')
                premium = parser.getIntParam(params, '5')
                imgLink = parser.getParam(params, '8')
                rtmpLink = parser.getParam(params, '10')
                playPath = parser.getParam(params, '11')
                bitrate = parser.getIntParam(params, '20')
                token = parser.getParam(params, '73')
                title = parser.getParam(params, '6')

                if title == '':
                    title = parser.getParam(params, '7')

                video_quality = config.plugins.iptvplayer.weebtv_videoquality.value
                if video_quality == '2' and bitrate == 1:
                    playPath = playPath + 'HI'
                elif video_quality == '0' and bitrate == 2:
                    playPath = playPath + 'LOW'

                rtmp = str(rtmpLink) + '/' + str(
                    playPath
                ) + ' live=1 token=fake pageUrl=token swfUrl=' + str(token)
                printDBG("||||||||||||||||||||||||||||| " + rtmp)
        except Exception:
            printExc()

        if rtmp.startswith('rtmp'):
            if 0 == premium:
                MainSessionWrapper().waitForFinishOpen(
                    MessageBox,
                    _("You do not have a premium account. Starting a sponsored broadcast."
                      ),
                    type=MessageBox.TYPE_INFO,
                    timeout=5)
            return rtmp
        else:
            return ''
Exemple #7
0
    def __init__(self, params={}):
        self.TMP_FILE_NAME = '.iptv_subtitles.file'
        self.TMP_DIR_NAME  = '/.iptv_subtitles.dir/'
        self.sessionEx = MainSessionWrapper(mainThreadIdx=1) 
        
        proxyURL = params.get('proxyURL', '')
        useProxy = params.get('useProxy', False)
        if 'MozillaCookieJar' == params.get('cookie_type', ''):
            self.cm = common(proxyURL, useProxy, True)
        else:
            self.cm = common(proxyURL, useProxy)

        self.currList = []
        self.currItem = {}
        if '' != params.get('cookie', ''):
            self.COOKIE_FILE = GetCookieDir(params['cookie'])
        self.moreMode = False
        self.params = params
        self.minPyVer = params.get('min_py_ver', 0)
Exemple #8
0
 def __init__(self):
     self.MAIN_URL = 'https://edem.tv/'
     self.HTTP_HEADER = {
         'User-Agent':
         'Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:12.0) Gecko/20100101 Firefox/12.0',
         'Referer': self.MAIN_URL
     }
     self.COOKIE_FILE = GetCookieDir('edemtv.cookie')
     self.cm = common()
     self.up = urlparser()
     self.http_params = {}
     self.http_params.update({
         'header': self.HTTP_HEADER,
         'save_cookie': True,
         'load_cookie': True,
         'cookiefile': self.COOKIE_FILE
     })
     self.cacheChannels = {}
     self.sessionEx = MainSessionWrapper()
Exemple #9
0
    def __init__(self, params={}):
        self.sessionEx = MainSessionWrapper()
        self.up = urlparser()

        proxyURL = params.get('proxyURL', '')
        useProxy = params.get('useProxy', False)
        if 'MozillaCookieJar' == params.get('cookie_type', ''):
            self.cm = common(proxyURL, useProxy, True)
        else:
            self.cm = common(proxyURL, useProxy)

        self.currList = []
        self.currItem = {}
        if '' != params.get('history', ''):
            self.history = CSearchHistoryHelper(
                params['history'], params.get('history_store_type', False))
        if '' != params.get('cookie', ''):
            self.COOKIE_FILE = GetCookieDir(params['cookie'])
        self.moreMode = False
        self.minPyVer = params.get('min_py_ver', 0)
Exemple #10
0
class CBaseHostClass:
    def __init__(self, params={}):
        self.sessionEx = MainSessionWrapper()
        self.up = urlparser()

        proxyURL = params.get('proxyURL', '')
        useProxy = params.get('useProxy', False)
        if 'MozillaCookieJar' == params.get('cookie_type', ''):
            self.cm = common(proxyURL, useProxy, True)
        else:
            self.cm = common(proxyURL, useProxy)

        self.currList = []
        self.currItem = {}
        if '' != params.get('history', ''):
            self.history = CSearchHistoryHelper(
                params['history'], params.get('history_store_type', False))
        if '' != params.get('cookie', ''):
            self.COOKIE_FILE = GetCookieDir(params['cookie'])
        self.moreMode = False
        self.minPyVer = params.get('min_py_ver', 0)

    def checkPythonVersion(self, pyVer):
        try:
            from Screens.MessageBox import MessageBox
            import sys
            if sys.version_info < pyVer:
                hasSNI = False
                try:
                    from ssl import wrap_socket
                    from inspect import getargspec
                    if 'server_hostname' in '%s' % [getargspec(wrap_socket)]:
                        hasSNI = True
                except Exception:
                    pass
                if not hasSNI:
                    message = _(
                        'This service requires a new Enigma2 image with a Python version %s or later.'
                    ) % ('.'.join(str(x) for x in pyVer))
                    message += '\n' + _(
                        'You can also install SNI patch for you python if available.'
                    )
                    self.sessionEx.waitForFinishOpen(MessageBox,
                                                     message,
                                                     type=MessageBox.TYPE_INFO,
                                                     timeout=10)
        except Exception:
            printExc()

    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 = byteify(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 listsTab(self, tab, cItem, type='dir'):
        defaultType = type
        for item in tab:
            params = dict(cItem)
            params.update(item)
            params['name'] = 'category'
            type = item.get('type', defaultType)
            if type == 'dir': self.addDir(params)
            elif type == 'marker': self.addMarker(params)
            else: self.addVideo(params)

    def listToDir(self, cList, idx):
        return self.cm.ph.listToDir(cList, idx)

    def getMainUrl(self):
        return self.MAIN_URL

    def setMainUrl(self, url):
        if self.cm.isValidUrl(url):
            self.MAIN_URL = self.cm.getBaseUrl(url)
            return True
        return False

    def getFullUrl(self, url, currUrl=None):
        if url.startswith('./'):
            url = url[1:]

        if currUrl == None or not self.cm.isValidUrl(currUrl):
            try:
                mainUrl = self.getMainUrl()
            except Exception:
                mainUrl = 'http://fake'
        else:
            mainUrl = self.cm.getBaseUrl(currUrl)

        if url.startswith('//'):
            proto = mainUrl.split('://', 1)[0]
            url = proto + ':' + url
        elif url.startswith('://'):
            proto = mainUrl.split('://', 1)[0]
            url = proto + url
        elif url.startswith('/'):
            url = mainUrl + url[1:]
        elif 0 < len(url) and '://' not in url:
            if currUrl == None or not self.cm.isValidUrl(currUrl):
                url = mainUrl + url
            else:
                url = urljoin(currUrl, url)
        return url

    def getFullIconUrl(self, url, currUrl=None):
        if currUrl != None: return self.getFullUrl(url, currUrl)
        else: return self.getFullUrl(url)

    def getDefaulIcon(self, cItem=None):
        try:
            return self.DEFAULT_ICON_URL
        except Exception:
            pass
        return ''

    @staticmethod
    def cleanHtmlStr(str):
        str = str.replace('<', ' <')
        str = str.replace('&nbsp;', ' ')
        str = str.replace('&nbsp', ' ')
        str = clean_html(str)
        str = str.replace('\n', ' ').replace('\r', ' ').replace('\t', ' ')
        return CParsingHelper.removeDoubles(str, ' ').strip()

    @staticmethod
    def getStr(v, default=''):
        if type(v) == type(u''): return v.encode('utf-8')
        elif type(v) == type(''): return v
        return default

    def getCurrList(self):
        return self.currList

    def setCurrList(self, list):
        self.currList = list

    def getCurrItem(self):
        return self.currItem

    def setCurrItem(self, item):
        self.currItem = item

    def addDir(self, params):
        params['type'] = 'category'
        self.currList.append(params)
        return

    def addMore(self, params):
        params['type'] = 'more'
        self.currList.append(params)
        return

    def addVideo(self, params):
        params['type'] = 'video'
        self.currList.append(params)
        return

    def addAudio(self, params):
        params['type'] = 'audio'
        self.currList.append(params)
        return

    def addPicture(self, params):
        params['type'] = 'picture'
        self.currList.append(params)
        return

    def addData(self, params):
        params['type'] = 'data'
        self.currList.append(params)
        return

    def addArticle(self, params):
        params['type'] = 'article'
        self.currList.append(params)
        return

    def addMarker(self, params):
        params['type'] = 'marker'
        self.currList.append(params)
        return

    def listsHistory(self,
                     baseItem={
                         'name': 'history',
                         'category': 'Wyszukaj'
                     },
                     desc_key='plot',
                     desc_base=(_("Type: "))):
        list = self.history.getHistoryList()
        for histItem in list:
            plot = ''
            try:
                if type(histItem) == type({}):
                    pattern = histItem.get('pattern', '')
                    search_type = histItem.get('type', '')
                    if '' != search_type: plot = desc_base + _(search_type)
                else:
                    pattern = histItem
                    search_type = None
                params = dict(baseItem)
                params.update({
                    'title': pattern,
                    'search_type': search_type,
                    desc_key: plot
                })
                self.addDir(params)
            except Exception:
                printExc()

    def getFavouriteData(self, cItem):
        try:
            return json.dumps(cItem)
        except Exception:
            printExc()
        return ''

    def getLinksForFavourite(self, fav_data):
        try:
            if self.MAIN_URL == None:
                self.selectDomain()
        except Exception:
            printExc()
        links = []
        try:
            cItem = byteify(json.loads(fav_data))
            links = self.getLinksForItem(cItem)
        except Exception:
            printExc()
        return links

    def setInitListFromFavouriteItem(self, fav_data):
        try:
            if self.MAIN_URL == None:
                self.selectDomain()
        except Exception:
            printExc()
        try:
            params = byteify(json.loads(fav_data))
        except Exception:
            params = {}
            printExc()
            return False
        self.currList.append(params)
        return True

    def getLinksForItem(self, cItem):
        return self.getLinksForVideo(cItem)

    def handleService(self, index, refresh=0, searchPattern='', searchType=''):
        if self.minPyVer > 0:
            self.checkPythonVersion(self.minPyVer)
            self.minPyVer = 0  # inform only once

        self.moreMode = False
        if 0 == refresh:
            if len(self.currList) <= index:
                return
            if -1 == index:
                self.currItem = {"name": None}
            else:
                self.currItem = self.currList[index]
        if 2 == refresh:  # refresh for more items
            printDBG(
                ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> endHandleService index[%s]"
                % index)
            # remove item more and store items before and after item more
            self.beforeMoreItemList = self.currList[0:index]
            self.afterMoreItemList = self.currList[index + 1:]
            self.moreMode = True
            if -1 == index:
                self.currItem = {"name": None}
            else:
                self.currItem = self.currList[index]

    def endHandleService(self, index, refresh):
        if 2 == refresh:  # refresh for more items
            currList = self.currList
            self.currList = self.beforeMoreItemList
            for item in currList:
                if 'more' == item['type'] or (
                        item not in self.beforeMoreItemList
                        and item not in self.afterMoreItemList):
                    self.currList.append(item)
            self.currList.extend(self.afterMoreItemList)
            self.beforeMoreItemList = []
            self.afterMoreItemList = []
        self.moreMode = False
Exemple #11
0
 def __init__(self, lang='en'):
     self.cm = common()
     self.sessionEx = MainSessionWrapper()
     self.MAIN_URL = 'https://2captcha.com/'
Exemple #12
0
class UnCaptchaReCaptcha:
    def __init__(self, lang='en'):
        self.cm = common()
        self.sessionEx = MainSessionWrapper()
        self.MAIN_URL = 'https://2captcha.com/'

    def getMainUrl(self):
        return self.MAIN_URL

    def getFullUrl(self, url, mainUrl=None):
        if mainUrl == None: mainUrl = self.getMainUrl()
        return self.cm.getFullUrl(url, mainUrl)

    def processCaptcha(self, sitekey, referer=''):
        sleepObj = None
        token = ''
        errorMsgTab = []
        apiKey = config.plugins.iptvplayer.api_key_2captcha.value
        apiUrl = self.getFullUrl(
            '/in.php?key='
        ) + apiKey + '&method=userrecaptcha&invisible=1&googlekey=' + sitekey + '&json=1&pageurl=' + urllib.quote(
            referer)
        try:
            token = ''
            sts, data = self.cm.getPage(apiUrl)
            if sts:
                printDBG('API DATA:\n%s\n' % data)
                data = byteify(json.loads(data), '', True)
                if data['status'] == '1':
                    captchaid = data['request']
                    sleepObj = GetIPTVSleep()
                    sleepObj.Sleep(300, False)
                    tries = 0
                    while True:
                        tries += 1
                        timeout = sleepObj.getTimeout()
                        if tries == 1:
                            timeout = 10
                        elif timeout > 10:
                            timeout = 5
                        time.sleep(timeout)

                        apiUrl = self.getFullUrl(
                            '/res.php?key='
                        ) + apiKey + '&action=get&json=1&id=' + captchaid
                        sts, data = self.cm.getPage(apiUrl)
                        if not sts:
                            continue
                            # maybe simple continue here ?
                            errorMsgTab.append(_('Network failed %s.') % '2')
                            break
                        else:
                            printDBG('API DATA:\n%s\n' % data)
                            data = byteify(json.loads(data), '', True)
                            if data['status'] == '1' and data['request'] != '':
                                token = data['request']
                                break
                        if sleepObj.getTimeout() == 0:
                            errorMsgTab.append(
                                _('%s timeout.') % self.getMainUrl())
                            break
                else:
                    errorMsgTab.append(data['request'])
            else:
                errorMsgTab.append(_('Network failed %s.') % '1')
        except Exception as e:
            errorMsgTab.append(str(e))
            printExc()

        if sleepObj != None:
            sleepObj.Reset()

        if token == '':
            self.sessionEx.waitForFinishOpen(
                MessageBox,
                (_('Resolving reCaptcha with %s failed!\n\n') %
                 self.getMainUrl()) + '\n'.join(errorMsgTab),
                type=MessageBox.TYPE_ERROR,
                timeout=10)
        return token
Exemple #13
0
class CBaseSubProviderClass:
    
    def __init__(self, params={}):
        self.TMP_FILE_NAME = '.iptv_subtitles.file'
        self.TMP_DIR_NAME  = '/.iptv_subtitles.dir/'
        self.sessionEx = MainSessionWrapper(mainThreadIdx=1) 
        
        proxyURL = params.get('proxyURL', '')
        useProxy = params.get('useProxy', False)
        if 'MozillaCookieJar' == params.get('cookie_type', ''):
            self.cm = common(proxyURL, useProxy, True)
        else:
            self.cm = common(proxyURL, useProxy)

        self.currList = []
        self.currItem = {}
        if '' != params.get('cookie', ''):
            self.COOKIE_FILE = GetCookieDir(params['cookie'])
        self.moreMode = False
        self.params = params
        self.minPyVer = params.get('min_py_ver', 0)
        
    def checkPythonVersion(self, pyVer):
        try:
            from Screens.MessageBox import MessageBox
            import sys
            if sys.version_info < pyVer:
                message = _('This service requires a new Enigma2 image with a Python version %s or later.') % ('.'.join(str(x) for x in pyVer))
                self.sessionEx.waitForFinishOpen(MessageBox, message, type = MessageBox.TYPE_INFO, timeout = 10)
        except Exception:
            printExc()
        
    def getSupportedFormats(self, all=False):
        if all:
            ret = list(IPTVSubtitlesHandler.getSupportedFormats())
        else:
            ret = list(IPTVSubtitlesHandler.SUPPORTED_FORMATS)
        return ret
        
    def getMaxFileSize(self):
        return 1024 * 1024 * 5 # 5MB, max size of sub file to be download
        
    def getMaxItemsInDir(self):
        return 500
        
    def listsTab(self, tab, cItem):
        for item in tab:
            params = dict(cItem)
            params.update(item)
            params['name']  = 'category'
            self.addDir(params)
            
    def iptv_execute(self, cmd):
        printDBG("iptv_execute cmd_exec [%s]" % cmd)
        ret = iptv_execute(1)(cmd)
        printDBG("iptv_execute cmd_ret sts[%s] code[%s] data[%s]" % (ret.get('sts', ''), ret.get('code', ''), ret.get('data', '')))
        return ret
        
    @staticmethod 
    def cleanHtmlStr(str):
        str = str.replace('<', ' <')
        str = str.replace('&nbsp;', ' ')
        str = clean_html(str)
        str = str.replace('\n', ' ').replace('\r', ' ').replace('\t', ' ')
        return CParsingHelper.removeDoubles(str, ' ').strip()

    @staticmethod 
    def getStr(v, default=''):
        if type(v) == type(u''): return v.encode('utf-8')
        elif type(v) == type(''):  return v
        return default
            
    def getCurrList(self):
        return self.currList

    def setCurrList(self, list):
        self.currList = list
        
    def getCurrItem(self):
        return self.currItem

    def setCurrItem(self, item):
        self.currItem = item

    def addDir(self, params, atTheEnd=True):
        params['type'] = 'category'
        if atTheEnd: self.currList.append(params)
        else: self.currList.insert(0, params)
        return
        
    def addMore(self, params, atTheEnd=True):
        params['type'] = 'more'
        if atTheEnd: self.currList.append(params)
        else: self.currList.insert(0, params)
        return
  
    def addSubtitle(self, params, atTheEnd=True):
        params['type'] = 'subtitle'
        if atTheEnd: self.currList.append(params)
        else: self.currList.insert(0, params)
        return
        
    def getMainUrl(self):
        return self.MAIN_URL
        
    #def getFullUrl(self, url):
    #    if url.startswith('//'):
    #        url = 'http:' + url
    #    elif url.startswith('://'):
    #        url = 'http' + url
    #    elif url.startswith('/'):
    #        url = self.getMainUrl() + url[1:]
    #    elif 0 < len(url) and '://' not in url:
    #        url =  self.getMainUrl() + url
    #    return url
        
    def getFullUrl(self, url, currUrl=None):
        if url.startswith('./'):
            url = url[1:]
        
        if currUrl == None or not self.cm.isValidUrl(currUrl):
            try: mainUrl = self.getMainUrl()
            except Exception: mainUrl = 'http://fake'
        else:
            mainUrl = self.cm.getBaseUrl(currUrl)
        
        if url.startswith('//'):
            proto = mainUrl.split('://', 1)[0]
            url = proto + ':' + url
        elif url.startswith('://'):
            proto = mainUrl.split('://', 1)[0]
            url = proto + url
        elif url.startswith('/'):
            url = mainUrl + url[1:]
        elif 0 < len(url) and '://' not in url:
            if currUrl == None or not self.cm.isValidUrl(currUrl):
                url =  mainUrl + url
            else:
                url = urljoin(currUrl, url)
        return url
    
    def handleService(self, index, refresh=0):
        if self.minPyVer > 0:
            self.checkPythonVersion(self.minPyVer)
            self.minPyVer = 0 # inform only once
    
        self.moreMode = False
        if 0 == refresh:
            if len(self.currList) <= index:
                return
            if -1 == index:
                self.currItem = { "name": None }
            else:
                self.currItem = self.currList[index]
        if 2 == refresh: # refresh for more items
            printDBG("CBaseSubProviderClass endHandleService index[%s]" % index)
            # remove item more and store items before and after item more
            self.beforeMoreItemList = self.currList[0:index]
            self.afterMoreItemList = self.currList[index+1:]
            self.moreMode = True
            if -1 == index:
                self.currItem = { "name": None }
            else:
                self.currItem = self.currList[index]
    
    def endHandleService(self, index, refresh):
        if 2 == refresh: # refresh for more items
            currList = self.currList
            self.currList = self.beforeMoreItemList
            for item in currList:
                if 'more' == item['type'] or (item not in self.beforeMoreItemList and item not in self.afterMoreItemList):
                    self.currList.append(item)
            self.currList.extend(self.afterMoreItemList)
            self.beforeMoreItemList = []
            self.afterMoreItemList  = []
        self.moreMode = False
        
    def imdbGetSeasons(self, imdbid, promSeason=None):
        printDBG('CBaseSubProviderClass.imdbGetSeasons imdbid[%s]' % imdbid)
        promotItem = None
        list = []
        # get all seasons
        sts, data = self.cm.getPage("http://www.imdb.com/title/tt%s/episodes" % imdbid)
        if not sts: return False, []
        data = self.cm.ph.getDataBeetwenMarkers(data, '<select id="bySeason"', '</select>', False)[1]
        seasons = re.compile('value="([0-9]+?)"').findall(data)
        for season in seasons:
            if None != promSeason and  season == str(promSeason):
                promotItem = season
            else:
                list.append(season)
            
        if promotItem != None:
            list.insert(0, promotItem)
        
        return True, list
        
    def imdbGetEpisodesForSeason(self, imdbid, season, promEpisode=None):
        printDBG('CBaseSubProviderClass.imdbGetEpisodesForSeason imdbid[%s] season[%s]' % (imdbid, season))
        promotItem = None
        list = []
        
        # get episodes for season
        sts, data = self.cm.getPage("http://www.imdb.com/title/tt%s/episodes/_ajax?season=%s" % (imdbid, season))
        if not sts: return False, []
        
        data = self.cm.ph.getDataBeetwenMarkers(data, '<div class="list detail eplist">', '<hr>', False)[1]
        data = data.split('<div class="clear">')
        if len(data): del data[-1]
        for item in data:
            episodeTitle = self.cm.ph.getSearchGroups(item, 'title="([^"]+?)"')[0]
            eimdbid = self.cm.ph.getSearchGroups(item, 'data-const="tt([0-9]+?)"')[0]
            episode = self.cm.ph.getSearchGroups(item, 'content="([0-9]+?)"')[0]
            params = {"episode_title":episodeTitle, "episode":episode, "eimdbid":eimdbid}
            
            if None != promEpisode and  episode == str(promEpisode):
                promotItem = params
            else:
                list.append(params)
        
        if promotItem != None:
            list.insert(0, promotItem)
        return True, list
        
    def imdbGetMoviesByTitle(self, title):
        printDBG('CBaseSubProviderClass.imdbGetMoviesByTitle title[%s]' % (title))
        
        sts, data = self.cm.getPage("http://www.imdb.com/find?ref_=nv_sr_fn&q=%s&s=tt" % urllib.quote_plus(title))
        if not sts: return False, []
        list = []
        data = self.cm.ph.getDataBeetwenMarkers(data, '<table class="findList">', '</table>', False)[1]
        data = data.split('</tr>')
        if len(data): del data[-1]
        for item in data:
            item = item.split('<a ')
            item = '<a ' + item[2]
            if '(Video Game)' in item: continue
            imdbid = self.cm.ph.getSearchGroups(item, '/tt([0-9]+?)/')[0]
            baseTtitle = ' '.join( self.cm.ph.getAllItemsBeetwenMarkers(item, '<a ', '</a>') )
            #title = title.split('<br/>')[0]
            title = self.cleanHtmlStr(item)
            year = self.cm.ph.getSearchGroups(item, '\((20[0-9]{2})\)')[0]
            if '' == year: year = self.cm.ph.getSearchGroups(item, '\((20[0-9]{2})\)')[0]
            if title.endswith('-'): title = title[:-1].strip()
            list.append({'title':title, 'base_title':self.cleanHtmlStr(baseTtitle), 'year':year, 'imdbid':imdbid})
        return True, list
        
    def imdbGetOrginalByTitle(self, imdbid):
        printDBG('CBaseSubProviderClass.imdbGetOrginalByTitle imdbid[%s]' % (imdbid))
        
        if not imdbid.startswith('tt'): imdbid = 'tt' + imdbid
        sts, data = self.cm.getPage('http://www.imdb.com/title/' + imdbid)
        if not sts: return False, {}
        title = self.cm.ph.getSearchGroups(data, '''<meta property='og:title' content="([^\(^"]+?)["\(]''')[0].strip()
        return True, {'title':title}
        
        
    def getTypeFromThemoviedb(self, imdbid, title):
        if '(TV Series)' in title:
            return 'series'
        itemType = 'movie'
        try:
            # lazy import
            import base64
            try:    import json
            except Exception: import simplejson as json
            from Plugins.Extensions.IPTVPlayer.dToolsSet.iptvtools import byteify
            
            url = "https://api.themoviedb.org/3/find/tt{0}?api_key={1}&external_source=imdb_id".format(imdbid, base64.b64decode('NjMxMWY4MmQ1MjAxNDI2NWQ3NjVkMzk4MDJhYWZhYTc='))
            sts, data = self.cm.getPage(url)
            if not sts: return itemType
            data = byteify(json.loads(data))
            if len(data["tv_results"]):
                itemType = 'series'
        except Exception:
            printExc()
        return itemType
    
    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
    
    def downloadFileData(self, url, params={}, post_data=None):
        printDBG('CBaseSubProviderClass.downloadFileData url[%s]' % url)
        urlParams = dict(params)
        urlParams['return_data'] = False
        try:
            fileSize = self.getMaxFileSize()
            sts, response = self.cm.getPage(url, urlParams, post_data)
            fileName = response.info().get('Content-Disposition', '')
            if fileName != '':
                tmpFileName = self.cm.ph.getSearchGroups(fileName.lower(), '''filename=['"]([^'^"]+?)['"]''')[0]
                if tmpFileName != '': 
                    printDBG("downloadFileData: replace fileName[%s] with [%s]" % (fileName, tmpFileName))
                    fileName = tmpFileName
            else:
                fileName = urllib.unquote(response.geturl().split('/')[-1])
            data = response.read(fileSize)
            response.close()
            return data, fileName
        except Exception:
            printExc()
        return None, ''
        
    def writeFile(self, filePath, data):
        printDBG('CBaseSubProviderClass.writeFile path[%s]' % filePath)
        try:
            with open(filePath, 'w') as f:
                f.write(data)
            return True
        except Exception:
            printExc()
            SetIPTVPlayerLastHostError(_('Failed to write file "%s".') % filePath)
        return False
        
    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
        
    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
        
    def listSupportedFilesFromPath(self, cItem, subExt=['srt'], archExt=['rar', 'zip'], dirCategory=None):
        printDBG('CBaseSubProviderClass.listSupportedFilesFromPath')
        maxItems = self.getMaxItemsInDir()
        numItems = 0
        # list files
        for file in os_listdir(cItem['path']):
            numItems += 1
            filePath = os_path.join(cItem['path'], file)
            params = dict(cItem)
            if os_path.isfile(filePath):
                ext = file.rsplit('.', 1)[-1].lower()
                params.update({'file_path':filePath, 'title':os_path.splitext(file)[0]})
                if ext in subExt:
                    params['ext'] = ext
                    self.addSubtitle(params)
                elif ext in archExt:
                    self.addDir(params)
            elif dirCategory != None and os_path.isdir(filePath):
                params.update({'category':dirCategory, 'path':filePath, 'title':file})
                self.addDir(params)
            if numItems >= maxItems:
                break
        self.currList.sort(key=lambda k: k['title'])
    
    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
class GoldVodTVApi:
    MAIN_URL = 'http://goldvod.tv/'
    HTTP_HEADER = {
        'User-Agent':
        'Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:12.0) Gecko/20100101 Firefox/12.0',
        'Referer': MAIN_URL
    }

    def __init__(self):
        self.COOKIE_FILE = GetCookieDir('goldvodtv.cookie')
        self.sessionEx = MainSessionWrapper()
        self.cm = common()
        self.up = urlparser()
        self.http_params = {}
        self.http_params.update({
            'save_cookie': True,
            'load_cookie': True,
            'cookiefile': self.COOKIE_FILE
        })
        self.cacheList = {}
        self.loggedIn = False

    def getFullUrl(self, url):
        if url.startswith('http'):
            return url
        elif url.startswith('/'):
            return self.MAIN_URL + url[1:]
        else:
            return self.MAIN_URL + url
        return url

    def cleanHtmlStr(self, str):
        return CBaseHostClass.cleanHtmlStr(str)

    def getChannelsList(self, cItem):
        printDBG("TelewizjadaNetApi.getChannelsList")

        login = config.plugins.iptvplayer.goldvodtv_login.value
        password = config.plugins.iptvplayer.goldvodtv_password.value
        if login != '' and password != '':
            if self.doLogin(login, password):
                self.loggedIn = True
                self.http_params.update({
                    'save_cookie': True,
                    'load_cookie': True,
                    'cookiefile': self.COOKIE_FILE
                })
            else:
                self.sessionEx.open(
                    MessageBox,
                    _('Problem z zalogowanie użytkownika "%s. Sprawdź dane do logowania w konfiguracji hosta."'
                      ) % login,
                    type=MessageBox.TYPE_INFO,
                    timeout=10)
                self.loggedIn = False

        channelsTab = []

        sts, data = self.cm.getPage(self.MAIN_URL + 'channels.html?show=on',
                                    self.http_params)
        if not sts: return []

        sts, data = self.cm.ph.getDataBeetwenMarkers(data, '<div class="row">',
                                                     "<div id='footer'>")
        data = self.cm.ph.getAllItemsBeetwenMarkers(data, '<a ', '</a>')
        for item in data:
            printDBG("item [%r]" % item)
            url = self.cm.ph.getSearchGroups(item,
                                             '''href=['"]([^"^']+?)['"]''')[0]
            icon = self.cm.ph.getSearchGroups(item,
                                              '''src=['"]([^"^']+?)['"]''')[0]
            id = self.cm.ph.getSearchGroups(url,
                                            '''[^0-9]([0-9]+?)[^0-9]''')[0]
            if '' != url:
                params = dict(cItem)
                params['url'] = self.getFullUrl(url)
                params['icon'] = self.getFullUrl(icon)
                params['title'] = self.cm.ph.getSearchGroups(
                    item, '''title=['"]([^"^']+?)['"]''')[0]
                if '' == params['title']:
                    params['title'] = self.cm.ph.getSearchGroups(
                        item, '''alt=['"]([^"^']+?)['"]''')[0]
                if '' == params['title']:
                    params['title'] = url.replace('.html',
                                                  '').replace(',',
                                                              ' ').title()
                params['desc'] = params['url']
                channelsTab.append(params)

        return channelsTab

    def getVideoLink(self, cItem):
        printDBG("GoldVodTVApi.getVideoLink")
        if self.loggedIn:
            url = strwithmeta(cItem['url'], {'params': {'load_cookie': True}})
        else:
            url = cItem['url']
        return self.up.getVideoLinkExt(url)

    def doLogin(self, login, password):
        logged = False
        loginUrl = self.MAIN_URL + 'login.html'

        params = dict(self.http_params)
        params['load_cookie'] = False
        sts, data = self.cm.getPage(loginUrl, params)
        if not sts: return False

        HTTP_HEADER = dict(GoldVodTVApi.HTTP_HEADER)
        HTTP_HEADER.update({'Referer': loginUrl})

        post_data = {
            'login': login,
            'pass': password,
            'remember': 1,
            'logged': ''
        }
        params = {
            'header': HTTP_HEADER,
            'cookiefile': self.COOKIE_FILE,
            'save_cookie': True,
            'load_cookie': True
        }
        sts, data = self.cm.getPage(loginUrl, params, post_data)
        if sts:
            if os_path.isfile(self.COOKIE_FILE):
                if 'logout.html' in data:
                    printDBG('GoldVodTVApi.doLogin login as [%s]' % login)
                    logged = True
                else:
                    printDBG(
                        'GoldVodTVApi.doLogin login failed - wrong user or password?'
                    )
            else:
                printDBG(
                    'GoldVodTVApi.doLogin there is no cookie file after login')
        return logged
 def __init__(self, lang='en'):
     self.cm = common()
     self.sessionEx = MainSessionWrapper()
     self.MAIN_URL = 'https://www.9kw.eu/'
Exemple #16
0
class PierwszaTVApi:
    def __init__(self):
        self.MAIN_URL = 'http://pierwsza.tv/'
        self.HTTP_HEADER = {
            'User-Agent':
            'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/37.0.2062.120 Chrome/37.0.2062.120 Safari/537.36',
            'Referer': self.MAIN_URL
        }

        self.COOKIE_FILE = GetCookieDir('pierwszatv.cookie')
        self.COOKIE_FILE2 = GetCookieDir('pierwszatv2.cookie')
        self.COOKIE_FILE3 = GetCookieDir('pierwszatv3.cookie')
        self.sessionEx = MainSessionWrapper()
        self.cm = common()
        self.up = urlparser()
        self.http_params = {
            'header': dict(self.HTTP_HEADER),
            'save_cookie': True,
            'load_cookie': True,
            'cookiefile': self.COOKIE_FILE
        }
        self.http_params2 = {
            'header': dict(self.HTTP_HEADER),
            'save_cookie': True,
            'load_cookie': True,
            'cookiefile': self.COOKIE_FILE2
        }
        self.http_params3 = {
            'header': dict(self.HTTP_HEADER),
            'save_cookie': True,
            'load_cookie': True,
            'cookiefile': self.COOKIE_FILE3
        }
        self.cacheList = {}

        self.mainConnectData = {}

    def getWindowDict(self, varData):
        printDBG("PierwszaTVApi.fillMainConnectData")
        window = {
            'isPromoMode': '',
            'utype': '',
            'u0td': '',
            'u1td': '',
            'uTypeRoute': ''
        }
        for key in window:
            val = self.cm.ph.getSearchGroups(
                varData, '''window\.%s[^'^"]*?=([^;]+?);''' % key, 1,
                True)[0].strip()
            if val.startswith("'") and val.endswith("'"):
                val = val[1:-1]
            if val.startswith('"') and val.endswith('"'):
                val = val[1:-1]
            window[key] = val
        return window

    def fillMainConnectData(self):
        printDBG("PierwszaTVApi.fillMainConnectData")
        self.mainConnectData = {}

        sts, data = self.cm.getPage(self.MAIN_URL, self.http_params)
        if not sts: return False

        self.mainConnectData = self.getWindowDict(data)

        tmp = self.cm.ph.getDataBeetwenMarkers(data, 'connectToLive(', ')',
                                               False)[1]
        tmp = self.cm.ph.getSearchGroups(
            tmp, '''['"]([^'^"]+?)['"][^'^"]+?['"]([^'^"]+?)['"]''', 2, True)
        self.mainConnectData['connect_to_live_url'] = tmp[0]
        self.mainConnectData['connect_to_live_token'] = tmp[1]

        tmp = self.cm.ph.getDataBeetwenMarkers(data, 'setItem(', ')', False)[1]
        tmp = self.cm.ph.getSearchGroups(
            tmp, '''['"]([^'^"]+?)['"][^'^"]+?['"]([^'^"]+?)['"]''', 2, True)
        self.mainConnectData[tmp[0]] = tmp[1]

        jsUrl = self.getFullUrl(
            self.cm.ph.getSearchGroups(
                data,
                '''<script[^>]+?src=['"]([^'^"]*?/build/[^'^"]+?\.js)['"]''')
            [0])
        sts, data = self.cm.getPage(jsUrl, self.http_params)
        if not sts:
            self.mainConnectData['api_path'] = ''
        else:
            self.mainConnectData['api_path'] = self.cm.ph.getSearchGroups(
                data, '''['"]?apiPath['"]?\s*:\s*["'](http[^'^"]+?)["']''')[0]

        printDBG(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> fillMainConnectData start")
        printDBG(self.mainConnectData)
        printDBG("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< fillMainConnectData end")

    def cryptoJS_AES_decrypt(self, encrypted, password, salt):
        def derive_key_and_iv(password, salt, key_length, iv_length):
            d = d_i = ''
            while len(d) < key_length + iv_length:
                d_i = md5(d_i + password + salt).digest()
                d += d_i
            return d[:key_length], d[key_length:key_length + iv_length]

        bs = 16
        key, iv = derive_key_and_iv(password, salt, 32, 16)
        cipher = AES_CBC(key=key, keySize=32)
        return cipher.decrypt(encrypted, iv)

    def getTimestamp(self, t, s=64):
        a = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_"
        e = ""
        t = int(t)
        while t > 0:
            e = a[t % s] + e
            t = int(t / s)
        return e

    def getFullUrl(self, url):
        if url.strip() == '':
            return ''
        elif self.cm.isValidUrl(url):
            return url
        elif url.startswith('//'):
            return 'http:' + url
        elif url.startswith('/'):
            return self.MAIN_URL + url[1:]
        return self.MAIN_URL + url

    def cleanHtmlStr(self, str):
        return CBaseHostClass.cleanHtmlStr(str)

    def getChannelsList(self, cItem):
        printDBG("TelewizjadaNetApi.getChannelsList")

        login = config.plugins.iptvplayer.pierwszatv_login.value
        password = config.plugins.iptvplayer.pierwszatv_password.value
        if login != '' and password != '':
            if self.doLogin(login, password):
                self.loggedIn = True
                self.http_params.update({
                    'save_cookie': True,
                    'load_cookie': True,
                    'cookiefile': self.COOKIE_FILE
                })
            else:
                self.sessionEx.open(
                    MessageBox,
                    _('Problem z zalogowanie użytkownika "%s. Sprawdź dane do logowania w konfiguracji hosta."'
                      ) % login,
                    type=MessageBox.TYPE_INFO,
                    timeout=10)

        self.fillMainConnectData()

        liveChannelsTab = []
        sts, data = self.cm.getPage(
            self.getFullUrl('player/watch?show=active'), self.http_params)
        if not sts: return []

        url = self.mainConnectData.get(
            'api_path',
            '') + "/sources?watchToken=" + self.mainConnectData.get('wt', '')
        sts, data = self.cm.getPage(url, self.http_params2)
        if not sts: return []

        scheduledChannelsTab = []
        try:
            data = byteify(json.loads(data))['sources']
            for idx in range(200):
                try:
                    if isinstance(data, list):
                        item = data[idx]
                    else:
                        item = data[str(idx)]
                except Exception:
                    continue
                #printDBG(item)
                #printDBG("===============================================")
                url = strwithmeta(
                    self.getFullUrl('player/watch/{0}'.format(item['id'])),
                    {'id': item['id']})
                icon = ''
                icon = item.get('thumbUrl', '')
                if icon == None: icon = ''

                title = self.cleanHtmlStr(item['name'])
                desc = []
                try:
                    if 'scheduleStartIn' in item:
                        d = item['scheduleStartIn']
                        desc.append('Start za: %s:%s:%s' %
                                    (str(d['hours']).zfill(2), str(
                                        d['minutes']).zfill(2),
                                     str(d['seconds']).zfill(2)))
                except Exception:
                    printExc()
                for d in ['author',
                          'updated_at']:  #, 'scheduleStartAt', 'scheduleEndAt'
                    if item.get(d, None) != None: desc.append(str(item[d]))

                params = dict(cItem)
                params.update({
                    'title': title,
                    'url': url,
                    'icon': self.getFullUrl(icon),
                    'desc': '[/br]'.join(desc)
                })

                if item.get('transmiting',
                            False) and not item.get('isScheduled', False):
                    liveChannelsTab.append(params)
                elif item.get('isScheduled', False):
                    scheduledChannelsTab.append(params)
        except Exception:
            SetIPTVPlayerLastHostError('Błąd w parsowaniu danych z serwera.')
            printExc()
        liveChannelsTab.extend(scheduledChannelsTab)
        return liveChannelsTab

    def getVideoLink(self, cItem):
        printDBG("TelewizjadaNetApi.getVideoLink")
        url = cItem['url']
        sourceId = str(url.meta['id'])

        mainCon = {
            'url': self.mainConnectData.get('connect_to_live_url', ''),
            'token': self.mainConnectData.get('connect_to_live_token', '')
        }

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

        params = dict(self.http_params)
        params['header'] = dict(params['header'])
        params['header']['Referer'] = cItem['url']
        params['header']['Origin'] = self.MAIN_URL[:-1]

        liveCon = {}
        url = self.mainConnectData.get(
            'api_path', '') + '/live?wt=' + self.mainConnectData.get('wt', '')
        sts, data = self.cm.getPage(url, self.http_params2)
        if not sts: return []
        try:
            liveCon = byteify(json.loads(data))
        except Exception:
            printExc()
            return []

        url = self.mainConnectData.get(
            'api_path', '') + "/play?id=%swatchToken=%s" % (
                sourceId, self.mainConnectData.get('wt', ''))
        sts, data = self.cm.getPage(url, self.http_params2)
        if not sts: return []

        try:

            def to_byte_array(inArray):
                import struct
                outArray = []
                for item in inArray:
                    outArray.append(struct.pack('>l', item))
                return ''.join(outArray)

            data = byteify(json.loads(data))
            ciphertext = to_byte_array(
                data['window']['encServers']['ciphertext']['words'])
            iv = to_byte_array(data['window']['encServers']['iv']['words'])
            key = to_byte_array(data['window']['encServers']['key']['words'])
            salt = to_byte_array(data['window']['encServers']['salt']['words'])

            tmp = self.cryptoJS_AES_decrypt(ciphertext, 'number-one', salt)
            printDBG(tmp)
            tmp = byteify(json.loads(tmp))

        except Exception:
            printExc()
            return []

        urlsTab = []
        try:
            if isinstance(tmp, list):
                tmp = tmp[0]

            if isinstance(tmp, dict):
                baseUrl1 = liveCon['url']
                streamToken1 = liveCon['token']
                baseUrl2 = tmp['server']
                streamToken2 = tmp['token']

                serverId = str(tmp['id'])

                printDBG(
                    "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
                )
                printDBG(tmp)
                printDBG(
                    "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
                )

                #def _getSocketIoUrl1(baseUrl, params):
                #    t1 = self.getTimestamp(time()*1000)

                t1 = self.getTimestamp(time() * 1000)
                url = baseUrl1 + '/socket.io/?EIO=3&transport=polling&t=' + t1
                sts, data = self.cm.getPage(url, self.http_params2)
                if sts:
                    baseParams1 = data[data.find('{'):]
                    baseParams1 = byteify(json.loads(baseParams1))
                    printDBG(
                        "========================================================="
                    )
                    printDBG([data])
                else:
                    baseParams1 = {'sid': ''}
                printDBG(baseParams1)
                printDBG(
                    "========================================================="
                )

                t2 = self.getTimestamp(time() * 1000)
                url = baseUrl2.replace(
                    ":8000",
                    ":8004") + '/socket.io/?EIO=3&transport=polling&t=' + t2
                sts, data = self.cm.getPage(url, self.http_params3)
                baseParams2 = data[data.find('{'):]
                baseParams2 = byteify(json.loads(baseParams2))
                printDBG(
                    "========================================================="
                )
                printDBG([data])
                printDBG(baseParams2)
                printDBG(
                    "========================================================="
                )

                #=====================
                t1 = self.getTimestamp(time() * 1000)
                url = baseUrl1 + '/socket.io/?EIO=3&transport=polling&t={0}&sid={1}'.format(
                    t1, baseParams1['sid'])
                sts, data = self.cm.getPage(url, self.http_params2)
                if sts:
                    printDBG(
                        "========================================================="
                    )
                    printDBG(data.split('\x00\x02\xff'))
                    printDBG(
                        "========================================================="
                    )

                t2 = self.getTimestamp(time() * 1000)
                url = baseUrl2.replace(
                    ":8000", ":8004"
                ) + '/socket.io/?EIO=3&transport=polling&t={0}&sid={1}'.format(
                    t2, baseParams2['sid'])
                sts, data = self.cm.getPage(url, self.http_params3)
                printDBG(
                    "========================================================="
                )
                printDBG(data.split('\x00\x02\xff'))
                printDBG(
                    "========================================================="
                )

                #=====================
                #raw_post_data
                t1 = self.getTimestamp(time() * 1000)
                url = baseUrl1 + '/socket.io/?EIO=3&transport=polling&t={0}&sid={1}'.format(
                    t1, baseParams1['sid'])
                self.http_params2['raw_post_data'] = True
                sts, data = self.cm.getPage(
                    url, self.http_params2,
                    '92:42["authorize",{"token":"%s"}]' % streamToken1)
                printDBG(
                    "========================================================="
                )
                printDBG([data])
                printDBG(
                    "========================================================="
                )

                if 0:
                    t1 = self.getTimestamp(time() * 1000)
                    url = baseUrl1 + '/socket.io/?EIO=3&transport=polling&t={0}&sid={1}'.format(
                        t1, baseParams1['sid'])
                    sts, data = self.cm.getPage(url, self.http_params2)
                    printDBG(
                        "========================================================="
                    )
                    printDBG([data])
                    printDBG(
                        "========================================================="
                    )

                #+++++
                t2 = self.getTimestamp(time() * 1000)
                url = baseUrl2.replace(
                    ":8000", ":8004"
                ) + '/socket.io/?EIO=3&transport=polling&t={0}&sid={1}'.format(
                    t2, baseParams2['sid'])
                self.http_params3['raw_post_data'] = True
                sts, data = self.cm.getPage(
                    url, self.http_params3,
                    '82:42["authorize","%s"]' % streamToken2)
                printDBG(
                    "========================================================="
                )
                printDBG([data])
                printDBG(
                    "========================================================="
                )

                t2 = self.getTimestamp(time() * 1000)
                url = baseUrl2.replace(
                    ":8000", ":8004"
                ) + '/socket.io/?EIO=3&transport=polling&t={0}&sid={1}'.format(
                    t2, baseParams2['sid'])
                sts, data = self.cm.getPage(url, self.http_params3)
                data = byteify(json.loads(data[data.find('42') + 2:]))
                stoken = data[1]['stoken']
                printDBG(
                    "========================================================="
                )
                printDBG([data])
                printDBG(
                    "========================================================="
                )

                n = sha256(serverId + '_' + sourceId + '_' + stoken +
                           '_rabbit_foot').hexdigest()
                url = self.mainConnectData[
                    'api_path'] + '/request-stream' + "?token=" + streamToken2 + "&server=" + serverId + "&source=" + sourceId + "&cs=" + n
                sts, data = self.cm.getPage(url, self.http_params)
                data = byteify(json.loads(data))
                streamId = str(data['id'])

                if 0:
                    t2 = self.getTimestamp(time() * 1000)
                    url = baseUrl2.replace(
                        ":8000", ":8004"
                    ) + '/socket.io/?EIO=3&transport=polling&t={0}&sid={1}'.format(
                        t2, baseParams2['sid'])
                    self.http_params3['raw_post_data'] = True
                    sts, data = self.cm.getPage(
                        url, self.http_params3,
                        '84:42["subscribe","%s"]' % streamId)

                wsUrl2 = baseUrl2.replace(":8000", ":8004").replace(
                    'http://', 'ws://'
                ) + '/socket.io/?EIO=3&transport=websocket&sid={0}'.format(
                    baseParams2['sid'])
                wsUrl1 = baseUrl1.replace(
                    'http://', 'ws://'
                ) + '/socket.io/?EIO=3&transport=websocket&sid={0}'.format(
                    baseParams1['sid'])

                libsPath = GetPluginDir('libs/')

                pyCmd = GetPyScriptCmd(
                    'pierwszatv'
                ) + ' "%s" "%s" "%s" "%s" "%s" "%s" "%s" "%s" ' % (
                    self.http_params['header']['User-Agent'], baseUrl2, wsUrl2,
                    wsUrl1, stoken, streamId, libsPath, baseParams2['sid'])
                vidUrl = strwithmeta(
                    "ext://url/" + cItem['url'], {
                        'iptv_proto': 'em3u8',
                        'iptv_refresh_cmd': pyCmd,
                        'Referer': cItem['url'],
                        'User-Agent': self.http_params['header']['User-Agent']
                    })

                printDBG(
                    "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
                )
                printDBG(pyCmd)
                printDBG(
                    "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
                )
                #return []
                return [{'name': 'pierwsza_hls', 'url': vidUrl}]

        except Exception:
            printExc()
            return []

        return urlsTab

    def doLogin(self, login, password):
        logged = False
        loginUrl = self.MAIN_URL + 'account/log-in'

        params = dict(self.http_params)
        params['load_cookie'] = False
        sts, data = self.cm.getPage(loginUrl, params)
        if not sts: return False

        _token = self.cm.ph.getSearchGroups(
            data, '''_token"[\s]*?value="([^"]+?)"''', 1, True)[0]

        HTTP_HEADER = dict(self.HTTP_HEADER)
        HTTP_HEADER.update({'Referer': loginUrl})

        post_data = {
            'email': login,
            'password': password,
            '_token': _token,
            'remember_me': 'on'
        }
        params = {
            'header': HTTP_HEADER,
            'cookiefile': self.COOKIE_FILE,
            'save_cookie': True,
            'load_cookie': True
        }
        sts, data = self.cm.getPage(loginUrl, params, post_data)
        if sts:
            if os_path.isfile(self.COOKIE_FILE):
                if 'dashboard/logout' in data:
                    printDBG('PierwszaTVApi.doLogin login as [%s]' % login)
                    logged = True
                else:
                    printDBG(
                        'PierwszaTVApi.doLogin login failed - wrong user or password?'
                    )
            else:
                printDBG(
                    'PierwszaTVApi.doLogin there is no cookie file after login'
                )
        return logged
Exemple #17
0
class UstvnowApi:
    MAIN_URL = 'http://m.ustvnow.com/'
    LIVE_URL = MAIN_URL + 'iphone/1/live/playingnow?pgonly=true'
    HTTP_HEADER  = { 'User-Agent': 'Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10', 'Referer': MAIN_URL }

    def __init__(self):
        self.cm = common()
        self.up = urlparser()
        self.sessionEx = MainSessionWrapper()
        self.cookiePath = GetCookieDir('ustvnow.cookie')
        self.token = ''
        self.passkey = ''
        
        HTTP_HEADER= dict(self.HTTP_HEADER)
        HTTP_HEADER.update( {'Content-Type':'application/x-www-form-urlencoded'} )
        self.defParams = {'header':HTTP_HEADER, 'cookiefile': self.cookiePath, 'use_cookie': True, 'load_cookie':True, 'save_cookie':True}
        
    def getFullUrl(self, url):
        if url.startswith('//'):
            return 'http:' + url
        if url.startswith('/'):
            url = url[1:]
        if 0 < len(url) and not url.startswith('http'):
            url =  self.MAIN_URL + url
        if not self.MAIN_URL.startswith('https://'):
            url = url.replace('https://', 'http://')
        return url
        
    def cleanHtmlStr(self, str):
        return CBaseHostClass.cleanHtmlStr(str)
        
    def _getChannelsNames(self):
        printDBG("UstvnowApi._getChannelsNames")
        url = 'http://m.ustvnow.com/gtv/1/live/listchannels?%s' % urllib.urlencode({'token': self.token})
        sts, data = self.cm.getPage(url)
        if not sts: return []
        
        channelList = []
        try:
            data = byteify(json.loads(data))
            for item in data['results']['streamnames']:
                params = {}
                params['sname']         = item['sname']
                params['img']           = item['img']
                params['scode']         = item['scode']
                params['t']             = item['t']
                params['callsign']      = item['callsign']
                params['prgsvcid']      = item['prgsvcid']
                params['data_provider'] = item['data_provider']
                params['lang']          = item['lang']
                params['af']            = item['af']
                channelList.append(params)
                
            printDBG(channelList)
                
        except Exception:
            printExc()
        return channelList
    
    def getChannelsList(self, cItem):
        printDBG("UstvnowApi.getChannelsList")
        
        login  = config.plugins.iptvplayer.ustvnow_login.value
        passwd = config.plugins.iptvplayer.ustvnow_password.value

        if '' != login.strip() and '' != passwd.strip():
            self.token = self.doLogin(login, passwd)
            self.passkey = self.getPasskey()
            if self.token == '' or self.passkey == '':
                self.sessionEx.open(MessageBox, _('An error occurred when try to sign in the user "%s.\nPlease check your login credentials and try again later..."') % login, type = MessageBox.TYPE_INFO, timeout = 10 )
                return []
        else:
            self.sessionEx.open(MessageBox, _('You need to enter email and password in configuration.'), type = MessageBox.TYPE_INFO, timeout = 10 )
            return []
            
    
        sts, data = self.cm.getPage(self.LIVE_URL, self.defParams)
        if not sts: return []
        
        channelsNames = self._getChannelsNames()
        channelsTab = []
        data = self.cm.ph.getDataBeetwenMarkers(data, '<div data-role="content" data-theme="c">', '</ul>', False)[1]
        data = data.split('</li>')
        prgsvcidMap = {}
        for item in data:
            url  = self.cm.ph.getSearchGroups(item, 'href="([^"]+?)"')[0]
            ui   = url.split('ui-page=')[-1]
            icon = self.cm.ph.getSearchGroups(item, 'src="([^"]+?)"')[0]
            desc = self.cleanHtmlStr(item)
            params = dict(cItem)
            params.pop('url')
            params.update({'priv_url':self.getFullUrl(url), 'ui_page':ui, 'icon':icon, 'desc':desc})
            
            for nameItem in channelsNames:
                if nameItem['img'] in icon:
                    if config.plugins.iptvplayer.ustvnow_only_available.value and 0 == nameItem['t']:
                        break
                    params['title']    = nameItem['sname'] + ' [%s]' % nameItem['t']
                    params['prgsvcid'] = nameItem['prgsvcid']
                    params['scode']    = nameItem['scode']
                    prgsvcidMap[params['prgsvcid']] = len(channelsTab)
                    channelsTab.append(params)
                    break
        
        # calculate time difference from utcnow and the local system time reported by OS
        OFFSET = datetime.now() - datetime.utcnow()
        if config.plugins.iptvplayer.ustvnow_epg.value:
            sts, data = self.cm.getPage(self.MAIN_URL + 'gtv/1/live/channelguide', self.defParams)
            if sts:
                try:
                    data = byteify(json.loads(data))
                    for item in data['results']:
                        if item['prgsvcid'] in prgsvcidMap:
                            idx = prgsvcidMap[item['prgsvcid']]
                            utc_date = datetime.strptime(item.get('event_date', '') + ' ' + item.get('event_time', ''), '%Y-%m-%d %H:%M:%S')
                            utc_date = utc_date + OFFSET
                            if utc_date.time().second == 59:
                                utc_date = utc_date + timedelta(0,1)
                            channelsTab[idx]['desc'] += '[/br][/br] [%s][/br]%s[/br]%s[/br]%s[/br]%s' % (utc_date.strftime('%Y-%m-%d %H:%M:%S'), item.get('title', ''), item.get('synopsis', ''), item.get('description', ''), item.get('episode_title', ''))
                except Exception:
                    printExc()
            
        return channelsTab
        
    def doLogin(self, login, password):
        printDBG("UstvnowApi.doLogin")
        rm(self.cookiePath)
        token = ''
        
        sts, data = self.cm.getPage(self.getFullUrl('iphone/1/live/settings'), self.defParams)
        if not sts: return token
        
        printDBG("=================================================================")
        printDBG(data)
        printDBG("=================================================================")
        
        url = self.getFullUrl(self.cm.ph.getSearchGroups(data, '''action=['"]([^'^"]+?)['"]''')[0])
        if not self.cm.isValidUrl(url): return token
        
        post_data = {'username':login, 'password':password, 'device':'iphone'}
        sts, data = self.cm.getPage(url, self.defParams, post_data)
        if sts:
            token = self.cm.getCookieItem(self.cookiePath, 'token')
        return token
        
    def getPasskey(self):

        url = 'http://m.ustvnow.com/gtv/1/live/viewdvrlist?%s' % urllib.urlencode({'token': self.token})
        sts, data = self.cm.getPage(url)
        if not sts: return ''
        
        try:
            data = byteify(json.loads(data))
            return data['globalparams']['passkey']
        except Exception:
            return ''
        
    def getVideoLink(self, cItem):
        printDBG("UstvnowApi.getVideoLink %s" % cItem)
        
        ########################
        #url = 'http://lv2.ustvnow.com/iphone_ajax?tab=iphone_playingnow&token=' + self.token
        #sts, data = self.cm.getPage(url, self.defParams)
        #return 
        #printDBG(data)
        ########################
        #sts, data = self.cm.getPage('https://watch.ustvnow.com/account/signin')
        #printDBG(data)
        #return []
        
        urlsTab = []
        cookieParams = {'cookiefile': self.cookiePath, 'use_cookie': True, 'load_cookie':True, 'save_cookie':True}
        
        sts, data = self.cm.getPage('http://m-api.ustvnow.com/stream/1/live/view?scode=%s&token=%s&key=%s' % (cItem.get('scode', ''), self.token, self.passkey), self.defParams)
        if sts:
            try:
                data = byteify(json.loads(data))
                
                tmp = getDirectM3U8Playlist(strwithmeta(data['stream'], {'User-Agent':self.HTTP_HEADER['User-Agent']}), cookieParams=cookieParams, checkContent=True)
                cookieValue = self.cm.getCookieHeader(self.cookiePath)
                
                for item in tmp:
                    vidUrl = item['url']#.replace('/smil:', '/mp4:').replace('USTVNOW/', 'USTVNOW1/')
                    
                    item['url'] = urlparser.decorateUrl(vidUrl, {'User-Agent':self.HTTP_HEADER['User-Agent'], 'Cookie':cookieValue})
                    urlsTab.append(item)
                if len(urlsTab):
                    return urlsTab
            except Exception:
                printExc()
        
        #sts, data = self.cm.getPage(cItem['priv_url'], self.defParams)
        sts, data = self.cm.getPage(self.LIVE_URL, self.defParams)
        if not sts: return []
        
        url = self.cm.ph.getSearchGroups(data, 'for="popup-%s"[^>]*?href="([^"]+?)"[^>]*?>' % cItem['ui_page'])[0]
        url = self.getFullUrl(url)
        
        sts, data = self.cm.getPage(url, self.defParams)
        if not sts: return []
        
        url = self.cm.ph.getSearchGroups(data, 'src="([^"]+?)"')[0]
        tmp = getDirectM3U8Playlist(strwithmeta(url, {'User-Agent':self.HTTP_HEADER['User-Agent']}), cookieParams=cookieParams, checkContent=True)
        cookieValue = self.cm.getCookieHeader(self.cookiePath)
        
        for item in tmp:
            vidUrl = item['url']#.replace('/smil:', '/mp4:').replace('USTVNOW/', 'USTVNOW1/')
            
            item['url'] = urlparser.decorateUrl(vidUrl, {'User-Agent':self.HTTP_HEADER['User-Agent'], 'Cookie':cookieValue})
            urlsTab.append(item)
        
        return urlsTab
class WagasWorldApi(CBaseHostClass):
    def __init__(self):
        CBaseHostClass.__init__(self)
        self.sessionEx = MainSessionWrapper()
        self.MAIN_URL = 'http://www.wagasworld.com/'
        self.HTTP_HEADER = {
            'User-Agent':
            'Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:12.0) Gecko/20100101 Firefox/12.0',
            'Referer': self.MAIN_URL
        }

        self.COOKIE_FILE = GetCookieDir('wagasworld.cookie')
        self.http_params = {
            'header': dict(self.HTTP_HEADER),
            'save_cookie': True,
            'load_cookie': True,
            'cookiefile': self.COOKIE_FILE
        }

    def _getFullUrl(self, url):
        if url.startswith('//'):
            url = 'http:' + url
        elif 0 < len(url) and not url.startswith('http'):
            url = self.MAIN_URL + url

        if self.MAIN_URL.startswith('https://'):
            url = url.replace('https://', 'http://')
        return url.replace('&amp;', '&')

    def getMainCategories(self, cItem):
        printDBG("WagasWorldApi.getMainCategories")
        list = []
        list.append({
            'type': 'waga_cat',
            'waga_cat': 'groups',
            'title': _('Channel'),
            'url': self.MAIN_URL + 'channel'
        })
        list.append({
            'type': 'waga_cat',
            'waga_cat': 'groups',
            'title': _('LiveTv'),
            'url': self.MAIN_URL + 'LiveTv'
        })
        return list

    def getGroups(self, cItem):
        printDBG("WagasWorldApi.getGroups")
        list = []
        sts, data = self.cm.getPage(cItem['url'], self.http_params)
        if not sts: return list
        data = self.cm.ph.getDataBeetwenMarkers(data,
                                                '<div class="form-item">',
                                                '<select', True)[1]
        data = re.compile(
            '<a[^>]+?href="([^"]+?)"[^>]*?>([^<]+?)</a>').findall(data)
        for item in data:
            list.append({
                'type': 'waga_cat',
                'waga_cat': 'items',
                'title': item[1],
                'url': self._getFullUrl(item[0])
            })
        return list

    def getItems(self, cItem):
        printDBG("WagasWorldApi.getItems")
        list = []
        page = cItem.get('page', 0)
        url = cItem['url']
        if page > 0:
            if '?' in url: url += '&'
            else: url += '?'
            url += 'page={0}'.format(page)
        sts, data = self.cm.getPage(url, self.http_params)
        if not sts: return list

        nextPage = False
        if '&amp;page={0}"'.format(page + 1) in data:
            nextPage = True
        data = self.cm.ph.getDataBeetwenMarkers(data,
                                                '<div class="view-content">',
                                                '</section>', True)[1]
        data = data.split('</span>')
        if len(data): del data[-1]
        for item in data:
            title = self.cm.ph.getSearchGroups(item, '>([^<]+?)</a>')[0]
            icon = self._getFullUrl(
                self.cm.ph.getSearchGroups(item, 'src="([^"]+?)"')[0])
            url = self._getFullUrl(
                self.cm.ph.getSearchGroups(item, 'href="([^"]+?)"')[0])
            if '' != url and '' != title:
                list.append({
                    'waga_cat': 'explore',
                    'type': 'waga_cat',
                    'title': title,
                    'icon': icon,
                    'url': url
                })
        if nextPage:
            list.append({
                'type': 'waga_cat',
                'waga_cat': 'items',
                'title': _('Next page'),
                'url': cItem['url'],
                'page': page + 1
            })
        return list

    def getChannelsList(self, cItem):
        printDBG("WagasWorldApi.getChannelsList waga_cat[%s]" %
                 cItem.get('waga_cat', ''))
        list = []
        waga_cat = cItem.get('waga_cat', '')
        if '' == waga_cat:
            login = config.plugins.iptvplayer.wagasworld_login.value
            password = config.plugins.iptvplayer.wagasworld_password.value
            if login != '' and password != '':
                if self.doLogin(login, password):
                    self.loggedIn = True
                    self.http_params.update({
                        'save_cookie': True,
                        'load_cookie': True,
                        'cookiefile': self.COOKIE_FILE
                    })
                else:
                    self.sessionEx.open(
                        MessageBox,
                        _('"%s" login failed! Please check your login and password.'
                          ) % login,
                        type=MessageBox.TYPE_INFO,
                        timeout=10)

            list = self.getGroups({'url': self.MAIN_URL + 'channel'})
            #list = self.getMainCategories(cItem)
        elif 'groups' == waga_cat:
            list = self.getGroups(cItem)
        elif 'items' == waga_cat:
            list = self.getItems(cItem)
        elif 'explore' == waga_cat:
            list = self.exploreItem(cItem)
        elif 'more' == waga_cat:
            list = self.loadMore(cItem)
        return list

    def _getEpisode(self, baseUrl, episode=-1):
        tmp = baseUrl.split('/')
        url = '/'.join(tmp[:-2]) + '/x.php?%s=%s&' % (tmp[-2], tmp[-1])

        if episode > -1:
            url += 'episode=%s&' % episode

        url += 'v=%s' % (int(time() * 1000))

        HTTP_HEADER = dict(self.HTTP_HEADER)
        HTTP_HEADER['Referer'] = baseUrl
        HTTP_HEADER['X-Requested-With'] = 'XMLHttpRequest'
        sts, data = self.cm.getPage(url, {'header': HTTP_HEADER})
        if not sts: return []

        ret = None
        errorMsg = ''
        try:
            data = byteify(json.loads(data))
            errorMsg = self.cleanHtmlStr(data.get('err', ''))
            ret = {
                'url': data['url'],
                'episode': data['episode'],
                'title': data['name']
            }
        except Exception:
            printExc()
            if errorMsg != '':
                self.sessionEx.open(MessageBox,
                                    errorMsg,
                                    type=MessageBox.TYPE_ERROR,
                                    timeout=10)
        return ret

    def exploreItem(self, cItem):
        printDBG("WagasWorldApi.exploreItem url[%s]" % cItem['url'])
        sts, data = self.cm.getPage(cItem['url'], self.http_params)
        if not sts: return []
        data = self.cm.ph.getDataBeetwenMarkers(data,
                                                '<div class="videoWrapper">',
                                                ' </section>', False)[1]
        if 'pr3v4t.tk' not in data:
            params = dict(cItem)
            params['type'] = 'video'
            return [params]

        retTab = []
        url = self.cm.ph.getSearchGroups(
            data,
            '''<iframe[^>]+?src=["'](https?://[^"^']*?pr3v4t\.tk[^"^']+)["']''',
            1, True)[0]
        data = self._getEpisode(url)
        if data:
            params = dict(cItem)
            params.update({
                'type': 'video',
                'title': cItem['title'] + ' ' + data['title'],
                'waga_url': url,
                'waga_episode': int(data['episode'])
            })
            retTab.append(params)

            params = dict(cItem)
            params.update({
                'type': 'more',
                'waga_cat': 'more',
                'title': _('More'),
                'waga_title': cItem['title'],
                'waga_url': url,
                'waga_episode': int(data['episode']) + 1
            })
            retTab.append(params)

        return retTab

    def loadMore(self, cItem):
        printDBG("WagasWorldApi.loadMore cItem[%s]" % cItem)

        episode = cItem.get('waga_episode', 1)
        baseUrl = cItem.get('waga_url', '')
        title = cItem.get('waga_title', '')

        retTab = []
        data = self._getEpisode(baseUrl, episode)
        if data:
            params = dict(cItem)
            params.update({
                'type': 'video',
                'title': title + ' ' + data['title'],
                'waga_url': baseUrl,
                'waga_episode': int(data['episode'])
            })
            retTab.append(params)

            params = dict(cItem)
            params.update({'waga_episode': int(data['episode']) + 1})
            retTab.append(params)

        return retTab

    def getVideoLink(self, cItem):
        printDBG("WagasWorldApi.getVideoLink cItem[%s]" % cItem)
        baseUrl = cItem['url']
        url = cItem.get('waga_url', '')

        if url != '':
            data = self._getEpisode(url, cItem.get('waga_episode', 1))
            if data:
                return [{'name': data['title'], 'url': data['url']}]
        else:
            sts, data = self.cm.getPage(baseUrl, self.http_params)
            if not sts: return []
            data = self.cm.ph.getDataBeetwenMarkers(
                data, '<div class="videoWrapper">', ' </section>', False)[1]
            return self.up.getAutoDetectedStreamLink(baseUrl, data)
        return []

    def doLogin(self, login, password):
        logged = False
        loginUrl = self.MAIN_URL + '?q=user'

        params = dict(self.http_params)
        params['load_cookie'] = False
        sts, data = self.cm.getPage(loginUrl, params)
        if not sts: return False

        data = self.cm.ph.getDataBeetwenMarkers(data, '<form', '</form>',
                                                False, False)[1]
        action = self.cm.ph.getSearchGroups(data,
                                            '''action=['"]([^'^"]+?)['"]''')[0]
        if action.startswith('/'):
            action = self.MAIN_URL + action[1:]

        printDBG(data)
        post_data = dict(
            re.findall(
                r'<(?:input|button)[^>]*name="([^"]*)"[^>]*value="([^"]*)"[^>]*>',
                data))
        post_data.update({'name': login, 'pass': password})

        HTTP_HEADER = dict(self.HTTP_HEADER)
        HTTP_HEADER.update({'Referer': loginUrl})

        params = {
            'header': HTTP_HEADER,
            'cookiefile': self.COOKIE_FILE,
            'save_cookie': True,
            'load_cookie': True
        }
        sts, data = self.cm.getPage(loginUrl, params, post_data)
        if sts:
            if os_path.isfile(self.COOKIE_FILE):
                if 'user/logout' in data:
                    printDBG('WagasWorldApi.doLogin login as [%s]' % login)
                    logged = True
                else:
                    printDBG(
                        'WagasWorldApi.doLogin login failed - wrong user or password?'
                    )
            else:
                printDBG(
                    'WagasWorldApi.doLogin there is no cookie file after login'
                )
        return logged
class UnCaptchaReCaptcha:
    def __init__(self, lang='en'):
        self.cm = common()
        self.sessionEx = MainSessionWrapper()
        self.MAIN_URL = 'https://www.9kw.eu/'

    def getMainUrl(self):
        return self.MAIN_URL

    def getFullUrl(self, url, mainUrl=None):
        if mainUrl == None: mainUrl = self.getMainUrl()
        return self.cm.getFullUrl(url, mainUrl)

    def processCaptcha(self, sitekey, referer=''):
        sleepObj = None
        token = ''
        errorMsgTab = []
        apiKey = config.plugins.iptvplayer.api_key_9kweu.value
        apiUrl = self.getFullUrl(
            '/index.cgi?apikey='
        ) + apiKey + '&action=usercaptchaupload&interactive=1&json=1&file-upload-01=' + sitekey + '&oldsource=recaptchav2&pageurl=' + urllib.quote(
            referer)
        try:
            token = ''
            sts, data = self.cm.getPage(apiUrl)
            if sts:
                printDBG('API DATA:\n%s\n' % data)
                data = byteify(json.loads(data))
                if 'captchaid' in data:
                    captchaid = data['captchaid']
                    sleepObj = GetIPTVSleep()
                    sleepObj.Sleep(300, False)
                    tries = 0
                    while True:
                        tries += 1
                        timeout = sleepObj.getTimeout()
                        if tries == 1:
                            timeout = 10
                        elif timeout > 10:
                            timeout = 5
                        time.sleep(timeout)

                        apiUrl = self.getFullUrl(
                            '/index.cgi?apikey='
                        ) + apiKey + '&action=usercaptchacorrectdata&json=1&id=' + captchaid
                        sts, data = self.cm.getPage(apiUrl)
                        if not sts:
                            continue
                            # maybe simple continue here ?
                            errorMsgTab.append(_('Network failed %s.') % '2')
                            break
                        else:
                            printDBG('API DATA:\n%s\n' % data)
                            data = byteify(json.loads(data))
                            token = data['answer']
                            if token != '':
                                break
                        if sleepObj.getTimeout() == 0:
                            errorMsgTab.append(
                                _('%s timeout.') % self.getMainUrl())
                            break
                else:
                    errorMsgTab.append(data['error'])
            else:
                errorMsgTab.append(_('Network failed %s.') % '1')
        except Exception as e:
            errorMsgTab.append(str(e))
            printExc()

        if sleepObj != None:
            sleepObj.Reset()

        if token == '':
            self.sessionEx.waitForFinishOpen(
                MessageBox,
                (_('Resolving reCaptcha with %s failed!\n\n') %
                 self.getMainUrl()) + '\n'.join(errorMsgTab),
                type=MessageBox.TYPE_ERROR,
                timeout=10)
        return token
class UnCaptchaReCaptcha:
    def __init__(self, lang='en'):
        self.HTTP_HEADER = {'Accept-Language':lang, 'Referer': 'https://www.google.com/recaptcha/demo/', 'User-Agent': 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.18) Gecko/20110621 Mandriva Linux/1.9.2.18-0.1mdv2010.2 (2010.2) Firefox/3.6.18'}
        self.cm = common()
        self.sessionEx = MainSessionWrapper() 
        self.challenge = ''
        self.response  = ''
        
    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
Exemple #21
0
class EdemTvApi:
    def __init__(self):
        self.MAIN_URL = 'https://edem.tv/'
        self.HTTP_HEADER = {
            'User-Agent':
            'Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:12.0) Gecko/20100101 Firefox/12.0',
            'Referer': self.MAIN_URL
        }
        self.COOKIE_FILE = GetCookieDir('edemtv.cookie')
        self.cm = common()
        self.up = urlparser()
        self.http_params = {}
        self.http_params.update({
            'header': self.HTTP_HEADER,
            'save_cookie': True,
            'load_cookie': True,
            'cookiefile': self.COOKIE_FILE
        })
        self.cacheChannels = {}
        self.sessionEx = MainSessionWrapper()

    def getFullUrl(self, url):
        if url.startswith('http'):
            return url
        elif url.startswith('/'):
            return self.MAIN_URL + url[1:]
        return self.MAIN_URL + url

    def cleanHtmlStr(self, str):
        return CBaseHostClass.cleanHtmlStr(str)

    def doLogin(self, login, password):
        logged = False
        HTTP_HEADER = dict(self.HTTP_HEADER)
        HTTP_HEADER.update({
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'X-Requested-With': 'XMLHttpRequest'
        })

        post_data = {'email': login, 'password': password}
        params = {
            'header': HTTP_HEADER,
            'cookiefile': self.COOKIE_FILE,
            'save_cookie': True
        }
        loginUrl = self.getFullUrl('account/login')
        sts, data = self.cm.getPage(loginUrl, params, post_data)
        if sts and '/account/logout' in data:
            logged = True
        return logged

    def getChannelsList(self, cItem):
        printDBG("EdemTvApi.getChannelsList")
        channelsTab = []
        getList = cItem.get('get_list', True)
        if getList:
            login = config.plugins.iptvplayer.edemtv_login.value
            passwd = config.plugins.iptvplayer.edemtv_password.value
            if '' != login.strip() and '' != passwd.strip():
                if not self.doLogin(login, passwd):
                    self.sessionEx.open(MessageBox,
                                        _('Login failed.'),
                                        type=MessageBox.TYPE_INFO,
                                        timeout=10)
                    return []
            else:
                self.sessionEx.open(
                    MessageBox,
                    _('This host requires registration. \nPlease fill your login and password in the host configuration. Available under blue button.'
                      ),
                    type=MessageBox.TYPE_ERROR,
                    timeout=10)
                return []

            self.cacheChannels = {}
            categoryUrl = self.getFullUrl('category')
            sts, data = self.cm.getPage(categoryUrl, self.http_params)
            if not sts: return []

            marker = "animated_hidden uk-width-1-1"
            channelsData = self.cm.ph.getDataBeetwenMarkers(
                data, marker, 'uk-visible-small', False)[1]
            channelsData = channelsData.split(marker)
            for catItem in channelsData:
                catId = self.cm.ph.getSearchGroups(
                    catItem, ''' id=['"]([^'^"]+?)['"]''')[0]
                if catId == '': continue
                channelsPerCat = self.cm.ph.getAllItemsBeetwenMarkers(
                    catItem, '<a ', '</a>')
                for item in channelsPerCat:
                    url = self.cm.ph.getSearchGroups(
                        item, ''' href=['"]([^'^"]+?)['"]''')[0]
                    icon = self.cm.ph.getSearchGroups(
                        item, ''' src=['"]([^'^"]+?)['"]''')[0]
                    alt = self.cm.ph.getSearchGroups(
                        item, ''' alt=['"]([^'^"]+?)['"]''')[0]

                    params = {
                        'type': 'video',
                        'url': self.getFullUrl(url),
                        'title': self.cleanHtmlStr(alt),
                        'icon': self.getFullUrl(icon),
                        'desc': self.cleanHtmlStr(item)
                    }
                    if catId not in self.cacheChannels:
                        self.cacheChannels[catId] = [params]
                    else:
                        self.cacheChannels[catId].append(params)

            catsData = self.cm.ph.getDataBeetwenMarkers(
                data, 'uk-visible-small', '</ul>')[1]
            catsData = self.cm.ph.getAllItemsBeetwenMarkers(
                catsData, '<li ', '</li>')
            for item in catsData:
                catId = self.cm.ph.getSearchGroups(
                    item, '''data-target=['"]([^'^"]+?)['"]''')[0]
                catTitle = self.cleanHtmlStr(item) + ' (%s)' % catId.title()
                if 0 == len(self.cacheChannels.get(catId, [])): continue

                if 'adult' == catId:
                    adult = True
                else:
                    adult = False

                params = dict(cItem)
                params.update({
                    'title': catTitle,
                    'cat_id': catId,
                    'get_list': False,
                    'pin_locked': adult
                })
                channelsTab.append(params)
        else:
            catId = cItem.get('cat_id', '')
            channels = self.cacheChannels.get(catId, [])
            for item in channels:
                params = dict(cItem)
                params.update(item)
                channelsTab.append(params)
        return channelsTab

    def getCookieItem(self, name):
        value = ''
        try:
            value = self.cm.getCookieItem(self.COOKIE_FILE, name)
        except Exception:
            printExc()
        return value

    def getVideoLink(self, cItem):
        printDBG("EdemTvApi.getVideoLink")

        playlistUrl = self.getFullUrl('playlist')
        tries = 0
        while tries < 7:
            tries += 1
            sts, data = self.cm.getPage(playlistUrl, self.http_params)
            if not sts: return []

            subdomain = self.cm.ph.getSearchGroups(
                data,
                '''<input[^>]*?name=['"]subdomain['"][^>]*?value=['"]([^'^"]+?)['"]'''
            )[0]
            domainTab = self.cm.ph.getSearchGroups(
                data,
                '''<option[^>]*?value="([0-9]+?)"[^>]*?selected[^>]*?>([^<]+?)</option>''',
                2)
            if subdomain == '' or '' == domainTab[0] or '' == domainTab[1]:
                HTTP_HEADER = dict(self.HTTP_HEADER)
                HTTP_HEADER.update({
                    'Referer': playlistUrl,
                    'Content-Type':
                    'application/x-www-form-urlencoded; charset=UTF-8',
                    'X-Requested-With': 'XMLHttpRequest'
                })

                login = config.plugins.iptvplayer.edemtv_login.value
                passwd = config.plugins.iptvplayer.edemtv_password.value
                subdomain = md5(login + passwd).hexdigest()
                post_data = {'server_id': tries, 'name': subdomain}
                params = dict(self.http_params)
                params['header'] = HTTP_HEADER
                url = self.getFullUrl('ajax/user_server')
                sts, data = self.cm.getPage(url, params, post_data)
                printDBG(data)
                if 'success' in data:
                    post_data = {
                        'server': tries,
                        'subdomain': subdomain,
                        'type': 1
                    }
                    sts, data = self.cm.getPage(playlistUrl, params, post_data)
                    printDBG(data)
            else:
                break

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

        #printDBG(data)

        data = self.cm.ph.getDataBeetwenMarkers(data, 'playlist:', ']',
                                                False)[1]

        hlsUrl = self.cm.ph.getSearchGroups(data,
                                            '''['"](http[^'^"]+?)['"]''')[0]
        rmpUrl = self.cm.ph.getSearchGroups(data,
                                            '''['"](rtmp[^'^"]+?)['"]''')[0]

        urlsTab = []
        if hlsUrl.startswith('http://') and 'm3u8' in hlsUrl:
            hlsUrl = 'http://{0}.{1}/iptv/'.format(
                subdomain, domainTab[1]) + hlsUrl.split('/iptv/')[-1]
            hlsUrl = strwithmeta(
                hlsUrl, {
                    'Cookie': 'session=%s;' % self.getCookieItem('session'),
                    'Referer': cItem['url'],
                    'User-Agent': self.HTTP_HEADER['User-Agent']
                })
            urlsTab = getDirectM3U8Playlist(hlsUrl)
        #if rmpUrl.startswith('rtmp'):
        #    urlsTab.append({'name':'rtmp', 'url':rmpUrl + ' live=1'})
        return urlsTab
Exemple #22
0
class UnCaptchaReCaptcha:
    def __init__(self, lang='en'):
        self.HTTP_HEADER = {
            'Accept-Language':
            lang,
            'Referer':
            'https://www.google.com/recaptcha/api2/demo',
            'User-Agent':
            'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.18) Gecko/20110621 Mandriva Linux/1.9.2.18-0.1mdv2010.2 (2010.2) Firefox/3.6.18'
        }
        self.cm = common()
        self.sessionEx = MainSessionWrapper()
        self.COOKIE_FILE = GetCookieDir('google.cookie')

    def processCaptcha(self, key):
        post_data = None
        token = ''
        iteration = 0
        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 ''

            imgUrl = self.cm.ph.getSearchGroups(
                data, '"(/recaptcha/api2/payload[^"]+?)"')[0]
            iteration += 1
            message = self.cm.ph.getSearchGroups(
                data,
                '<label[^>]+class="fbc-imageselect-message-text"[^>]*>(.*?)</label>'
            )[0]
            if '' == message:
                message = self.cm.ph.getSearchGroups(
                    data,
                    '<div[^>]+class="fbc-imageselect-message-error">(.*?)</div>'
                )[0]
            if '' == message:
                token = self.cm.ph.getDataBeetwenNodes(
                    data, ('<div', '>', 'verification-token'), ('</div', '>'),
                    False)[1]
                token = self.cm.ph.getDataBeetwenNodes(data,
                                                       ('<textarea', '>'),
                                                       ('</textarea', '>'),
                                                       False)[1].strip()
                if token == '':
                    token = self.cm.ph.getSearchGroups(
                        data, '"this\.select\(\)">(.*?)</textarea>')[0]
                if token == '':
                    token = self.cm.ph.getDataBeetwenNodes(
                        data, ('<textarea', '>'), ('</textarea', '>'),
                        False)[1].strip()
                if '' != token:
                    printDBG('>>>>>>>> Captcha token[%s]' % (token))
                else:
                    printDBG('>>>>>>>> Captcha Failed\n\n%s\n\n' % data)
                break

            cval = self.cm.ph.getSearchGroups(data,
                                              'name="c"\s+value="([^"]+)')[0]
            imgUrl = 'https://www.google.com%s' % (imgUrl.replace(
                '&amp;', '&'))
            message = clean_html(message)
            accepLabel = clean_html(
                self.cm.ph.getSearchGroups(
                    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