示例#1
0
 def __init__(self, lang='en'):
     self.COOKIE_FILE = GetCookieDir('google.cookie')
     self.HTTP_HEADER = {
         'Accept':
         'text/html',
         'Accept-Charset':
         'UTF-8',
         'Accept-Encoding':
         'gzip',
         'Accept-Language':
         lang,
         'Referer':
         'https://www.google.com/recaptcha/api2/demo',
         'User-Agent':
         'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36'
     }
     self.HttpParams = {
         'header': self.HTTP_HEADER,
         'cookiefile': self.COOKIE_FILE,
         'use_cookie': True,
         'load_cookie': True,
         'save_cookie': True
     }
     self.cm = common()
     self.sessionEx = MainSessionWrapper()
示例#2
0
 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}
     self.DEFAULT_URL_ICON = self.getFullIconUrl('/sites/default/files/styles/slideshow_full/public/12_0.jpg?itok=LHobtpyX')
 def __init__(self):
     printDBG('Host __init__ begin')
     self.exSession = MainSessionWrapper()
     self.COOKIEFILE = GetCookieDir('scseriale.cookie')
     self.cm = common()
     self.currList = []
     self.up = urlparser()
     self.history = CSearchHistoryHelper('wspolne')
     printDBG('Host __init__ end')
示例#4
0
 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
示例#5
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()
示例#6
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}
示例#7
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')
示例#8
0
 def __init__(self):
     self.COOKIE_FILE = GetCookieDir('sport365live.cookie')
     self.sessionEx = MainSessionWrapper()
     self.cm = common()
     self.up = urlparser()
     self.http_params = {
         'header': dict(self.HTTP_HEADER),
         'use_cookie': True,
         'save_cookie': True,
         'load_cookie': True,
         'cookiefile': self.COOKIE_FILE
     }
     self.needRefreshAdvert = True
示例#9
0
 def __init__(self):
     self.up = urlparser.urlparser()
     self.cm = pCommon.common()
     self.sessionEx = MainSessionWrapper()
     self.ytp = YouTubeParser()
     self.ytformats = config.plugins.iptvplayer.ytformat.value
     # Temporary data
     self.currList = []
     self.currItem = {}
     # Login data
     self.COOKIEFILE = GetCookieDir('Diff-anime.cookie')
     self.usePremiumAccount = config.plugins.iptvplayer.diffanime_premium.value
     self.username = config.plugins.iptvplayer.diffanime_login.value
     self.password = config.plugins.iptvplayer.diffanime_password.value
示例#10
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 = {}
示例#11
0
    def __init__(self, params={}):
        self.USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0'
        self.HEADER = {
            'User-Agent': self.USER_AGENT,
            'Connection': 'keep-alive'
        }
        if '' != params.get('cookie', ''):
            self.COOKIE_FILE = GetCookieDir(params['cookie'])
            self.defaultParams = {
                'header': self.HEADER,
                'use_cookie': True,
                'load_cookie': True,
                'save_cookie': True,
                'cookiefile': self.COOKIE_FILE
            }
        else:
            self.defaultParams = {'header': self.HEADER}
        self.sessionEx = MainSessionWrapper()
        self.up = urlparser()
        self.ts_urlpars = ts_urlparser()
        proxyURL = params.get('proxyURL', '')
        useProxy = params.get('useProxy', False)
        self.cm = common(proxyURL, useProxy)

        self.currList = []
        self.currItem = {}
        if '' != params.get('history', ''):
            self.history = CSearchHistoryHelper(
                params['history'], params.get('history_store_type', False))
        self.moreMode = False
示例#12
0
 def __init__(self):
     CBaseHostClass.__init__(self)
     
     # temporary data
     self.currList = []
     self.currItem = {}
     
     #Login data
     self.sort = config.plugins.iptvplayer.SortowanieWebstream.value
     self.sessionEx = MainSessionWrapper()
     
     self.filmOnApi            = None
     self.videoStarApi         = None
     self.webCameraApi         = None
     self.wagasWorldApi        = None
     self.ustvnowApi           = None
     self.meteoPLApi           = None
     self.livemassNetApi       = None
     self.goldvodTvApi         = None
     self.sport365LiveApi      = None
     self.edemTvApi            = None
     self.wkylinewebcamsComApi = None
     self.wizjaTvApi           = None
     self.bilaSportPwApi       = None
     self.canlitvliveIoApi     = None
     self.weebTvApi            = None
     self.djingComApi          = None
     self.MLBStreamTVApi       = None
     self.BeinmatchApi         = None
     self.Wiz1NetApi           = None
     
     self.hasbahcaiptv = {}
     self.webcameraSubCats = {}
     self.webCameraParams = {}
示例#13
0
    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 ''
示例#14
0
    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
        }
示例#15
0
 def captcha(self):
     self.USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0'
     self.HTTP_HEADER = {'User-Agent': self.USER_AGENT, 'DNT':'1', 'Accept': 'application/json, text/javascript, */*; q=0.01', 'Accept-Encoding':'gzip, deflate', 'Referer':'https://zalukaj.com/', 'Origin':'https://zalukaj.com/'}
     self.defaultParams = {'header':self.HTTP_HEADER, 'with_metadata':True, 'use_cookie': True, 'load_cookie': True, 'save_cookie': True, 'cookiefile': self.COOKIE_FILE}
     httpParams = dict(self.defaultParams)
     imgUrl = 'https://zalukaj.com/captcha-image'
     from copy import deepcopy
     from Plugins.Extensions.IPTVPlayer.components.iptvmultipleinputbox import IPTVMultipleInputBox
     from Plugins.Extensions.IPTVPlayer.components.asynccall import MainSessionWrapper
     self.sessionEx = MainSessionWrapper()  
     captchaTitle = ''
     captchaLabel = _('Captcha')
     captchaTitle = captchaLabel  
     sendLabel = _('Send')
     header = dict(self.HTTP_HEADER)
     header['Accept'] = 'image/png,image/*;q=0.8,*/*;q=0.5'
     params = dict(self.defaultParams)
     params.update( {'maintype': 'image', 'subtypes':['jpeg', 'png'], 'check_first_bytes':['\xFF\xD8','\xFF\xD9','\x89\x50\x4E\x47'], 'header':header} )
     filePath = GetTmpDir('.iptvplayer_captcha.jpg')
     rm(filePath)
     ret = self.cm.saveWebFile(filePath, imgUrl.replace('&', '&'), params)
     if not ret.get('sts'):
         SetIPTVPlayerLastHostError(_('Fail to get "%s".') % imgUrl)
         return []
     params = deepcopy(IPTVMultipleInputBox.DEF_PARAMS)
     params['accep_label'] = sendLabel
     params['title'] = captchaLabel
     params['status_text'] = captchaTitle
     params['status_text_hight'] = 200
     params['with_accept_button'] = True
     params['list'] = []
     item = deepcopy(IPTVMultipleInputBox.DEF_INPUT_PARAMS)
     item['label_size'] = (660,110)
     item['input_size'] = (680,25)
     item['icon_path'] = filePath
     item['title'] = _('Answer')
     item['input']['text'] = ''
     params['list'].append(item)
     params['vk_params'] = {'invert_letters_case':True}
     ret = 0
     retArg = self.sessionEx.waitForFinishOpen(IPTVMultipleInputBox, params)
     printDBG(retArg)
     if retArg and len(retArg) and retArg[0]:
         return retArg[0][0].lower()
     else:
         return []
示例#16
0
 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):
     printDBG( 'Host __init__ begin' )
     self.exSession = MainSessionWrapper()
     self.COOKIEFILE = GetCookieDir('zalukajtv.cookie')
     self.cm = common()
     self.up = urlparser()
     self.history = CSearchHistoryHelper('wspolne')
     self.currList = []
     printDBG( 'Host __init__ end' )
示例#18
0
class UnCaptchaReCaptcha:
    def __init__(self, lang='en'):
        self.sessionEx = MainSessionWrapper()

    def processCaptcha(self, sitekey, referer=''):
        answer = ''
        retArg = self.sessionEx.waitForFinishOpen(UnCaptchaReCaptchaMyJDWidget, title=_("My JDownloader reCAPTCHA v2 solution"), sitekey=sitekey, referer=referer)
        if retArg is not None and len(retArg) and retArg[0]:
            answer = retArg[0]
        return answer
示例#19
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)
示例#20
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({'save_cookie': True, 'load_cookie': True, 'cookiefile': self.COOKIE_FILE})
     self.cacheChannels = {}
     self.sessionEx = MainSessionWrapper()
示例#21
0
 def __init__(self):
     self.cm = common()
     self.up = urlparser()
     self.sessionEx = MainSessionWrapper()
     self.cookiePath = GetCookieDir('ustvnow.cookie')
     self.token = ''
     
     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}
示例#22
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)
示例#23
0
 def __init__(self):
     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 = {}
 def __init__(self):
     self.up = urlparser.urlparser()
     self.cm = pCommon.common()
     self.sessionEx = MainSessionWrapper()
     self.ytp = YouTubeParser()
     self.ytformats = config.plugins.iptvplayer.ytformat.value
     # Temporary data
     self.currList = []
     self.currItem = {}
     # Login data
     self.COOKIEFILE = GetCookieDir('Diff-anime.cookie')
     self.usePremiumAccount = config.plugins.iptvplayer.diffanime_premium.value
     self.username = config.plugins.iptvplayer.diffanime_login.value
     self.password = config.plugins.iptvplayer.diffanime_password.value
示例#25
0
    def __init__(self, params={}):
        self.sessionEx = MainSessionWrapper() 
        self.up = urlparser()
        
        proxyURL = params.get('proxyURL', '')
        useProxy = params.get('useProxy', False)
        self.cm = common(proxyURL, useProxy)

        self.currList = []
        self.currItem = {}
        if '' != params.get('history', ''):
            self.history = CSearchHistoryHelper(params['history'])
        if '' != params.get('cookie', ''):
            self.COOKIE_FILE = GetCookieDir(params['cookie'])
        self.moreMode = False
    def __init__(self):
        self.up = urlparser()
        self.cm = common()
        # temporary data
        self.currList = []
        self.currItem = {}

        #Login data
        self.sort = config.plugins.iptvplayer.SortowanieWebstream.value
        self.sessionEx = MainSessionWrapper()
        self.filmOnApi = None
        self.videoStarApi = None
        self.satLiveApi = None
        self.vidTvApi = None
        self.looknijTvApi = None
        self.tvSportCdaApi = None
        self.nettvpwApi = None
        self.weebTvApi = None
        self.teamCastTab = {}
 def __init__(self, lang='en'):
     self.cm = common()
     self.sessionEx = MainSessionWrapper()
     self.MAIN_URL = 'https://2captcha.com/'
示例#28
0
 def __init__(self):
     self.cm = common()#proxyURL= '', useProxy = True)
     self.up = urlparser()
     self.sessionEx = MainSessionWrapper()
示例#29
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, referer=None):
        post_data = None
        token = ''
        iteration = 0
        if referer != None:
            self.HTTP_HEADER['Referer'] = referer
        reCaptchaUrl = 'http://www.google.com/recaptcha/api/fallback?k=%s' % (
            key)
        while iteration < 20:
            #,'cookiefile':self.COOKIE_FILE, 'use_cookie': True, 'load_cookie': True, 'save_cookie':True
            sts, data = self.cm.getPage(reCaptchaUrl, {
                'header': self.HTTP_HEADER,
                'raw_post_data': True
            },
                                        post_data=post_data)
            if not sts:
                SetIPTVPlayerLastHostError(
                    _('Fail to get "%s".') % reCaptchaUrl)
                return ''

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

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

            cval = ph.search(data, 'name="c"\s+value="([^"]+)')[0]
            imgUrl = 'https://www.google.com%s' % (imgUrl.replace(
                '&amp;', '&'))
            message = ph.clean_html(message)
            accepLabel = ph.clean_html(
                ph.search(data, 'type="submit"\s+value="([^"]+)')[0])

            filePath = GetTmpDir('.iptvplayer_captcha.jpg')
            printDBG(">>>>>>>> Captcha message[%s]" % (message))
            printDBG(">>>>>>>> Captcha accep label[%s]" % (accepLabel))
            printDBG(">>>>>>>> Captcha imgUrl[%s] filePath[%s]" %
                     (imgUrl, filePath))

            params = {
                'maintype': 'image',
                'subtypes': ['jpeg'],
                'check_first_bytes': ['\xFF\xD8', '\xFF\xD9']
            }
            ret = self.cm.saveWebFile(filePath, imgUrl, params)
            if not ret.get('sts'):
                SetIPTVPlayerLastHostError(_('Fail to get "%s".') % imgUrl)
                break

            retArg = self.sessionEx.waitForFinishOpen(
                UnCaptchaReCaptchaWidget,
                imgFilePath=filePath,
                message=message,
                title="reCAPTCHA v2",
                additionalParams={'accep_label': accepLabel})
            printDBG('>>>>>>>> Captcha response[%s]' % (retArg))
            if retArg is not None and len(retArg) and retArg[0]:
                answer = retArg[0]
                printDBG('>>>>>>>> Captcha answer[%s]' % (answer))
                post_data = urllib.urlencode({
                    'c': cval,
                    'response': answer
                },
                                             doseq=True)
            else:
                break

        return token
示例#30
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
示例#31
0
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
class SatLiveApi:
    MAINURL      = 'http://web-live.tv/'
    LIST_URL     = MAINURL + 'transmissions/transmission/index'
    SWF_URL      = MAINURL + 'themes/default/swf/jwplayer.flash.swf'
    LOGIN_URL    = MAINURL + 'site/site/login'
    HTTP_HEADER  = { 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:12.0) Gecko/20100101 Firefox/12.0', 'Referer': MAINURL }

    def __init__(self):
        self.COOKIE_FILE = GetCookieDir('satlivetv.cookie')
        self.cm = common()
        self.sessionEx = MainSessionWrapper()
        self.loggedIn  = True
        self.http_params = {}
        
        #self._reInit()
        #self.channelsList = []

    def getChannelsList(self):
        printDBG("SatLiveApi.getChannelsList")
        
        # login
        premium  = config.plugins.iptvplayer.satlivetv_premium.value
        login    = config.plugins.iptvplayer.satlivetv_login.value
        password = config.plugins.iptvplayer.satlivetv_password.value
        if premium:        
            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 )

        # get channels
        channelsList = []
        sts, data = self.cm.getPage(SatLiveApi.LIST_URL, self.http_params)
        if not sts:
            return []
        
        data = self.cm.ph.getDataBeetwenMarkers(data, '<div class="tab-pane active" id="live">', '<div class="tab-pane" id="all">', False)[1]
        data = data.split('</li>')
        for item in data:
            tmp = self.cm.ph.getSearchGroups(item, '<h4><a href="([^"]+?)">([^<]+?)</a></h4>', 2)
            if '' != tmp[0]:
                params = {}
                params['url']   = SatLiveApi.MAINURL + tmp[0]
                params['title'] = tmp[1]
                icon = self.cm.ph.getSearchGroups(item, '<img class="" src="([^"]+?)"')[0]
                if '' != icon:
                    params['icon']  = SatLiveApi.MAINURL + icon
                params['desc']      = self.cm.ph.removeDoubles(clean_html(item.replace('>', '> ')).replace('\t', ' '), ' ')
                channelsList.append(params)
        return channelsList

    def getVideoLink(self, url):
        printDBG("SatLiveApi.getVideoLink")
        id = self.cm.ph.getSearchGroups(url+"/", 'id/([0-9]+?)/')[0]
        sts, data = self.cm.getPage(SatLiveApi.MAINURL + 'ge/' + id, self.http_params)
        if not sts:
            return ''
        base = self.cm.ph.getSearchGroups(data, 'base="([^"]+?)"')[0]
        src = self.cm.ph.getSearchGroups(data, 'src="([^"]+?)"')[0]
        if base.startswith('rtmp'):
            return base + '/' + src + ' swfUrl=%s live=1' % SatLiveApi.SWF_URL
        return ''

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

        
        post_data = {'LoginForm[email]' : login, 'LoginForm[password]' : password, 'ajax' : 'fast-login-form', 'undefined' : '' }
        params    = {'header' : HTTP_HEADER, 'cookiefile' : self.COOKIE_FILE, 'save_cookie' : True}
        sts, data = self.cm.getPage( SatLiveApi.LOGIN_URL, params, post_data)
        if sts:
            if os_path.isfile(self.COOKIE_FILE):
                printDBG(data)
                if '[]' == data:
                    printDBG('SatLiveApi.doLogin login as [%s]' % login)
                    logged = True
                else:
                    printDBG('SatLiveApi.doLogin login failed - wrong user or password?')
            else:
                printDBG('SatLiveApi.doLogin there is no cookie file after login')
        return logged
示例#33
0
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 = []
        
        nameMap = {'3':'Eleven','2':'TVgP 1 HD','4':'Polsat HD','5':'Polsat 2 HD','6':'Canal+ Sport HD','7':'Eleven Sports',
        '8':'Canal+ Sport 2 HD','9':'Canal+ HD','10':'TVN Meteo Active','11':'Eurosport 2 HD','12':'nSport HD',
        '13':'Erosport HD','14':'Nickelodeon','15':'Comedy Central','16':'National Geographic Channel HD','17':'MTV',
        '18':'Polsat Sport News','19':'TTV','20':'TVN 7 HD','21':'MiniMini+','22':'Discavery Channel HD','23':'BBC Earth',
        '24':'Nat Geo Wild HD','25':'AXN HD','26':'TVP Seriale','27':'TVP Info','28':'Fokus TV','29':'TV Puls',
        '30':'TVP 2 HD','31':'TVN HD','32':'HBO HD','33':'TLC HD','34':'TVP HD','35':'TVP Sport HD','36':'Canal+ Film HD',
        '37':'Canal+ Family HD','38':'Canal+ Seriale','39':'Eska Rock','40':'Polo TV','41':'Eska go','42':'Eska TV',
        '43':'6','44':'Stopklatka TV','45':'Animal Planet HD','46':'TVN Style HD','47':'TVN Trurbo HD','48':'TVN 24',
        '49':'KinoPolska PL','50':'HBO 2 HD','51':'HBO Comedy HD','52':'Travel Channel','53':'Polsat Sport HD',
        '54':'Fox HD','55':'TVP Historia','56':'TVN 24 Biznes i Świat','57':'AXN White','58':'AXN Black','59':'Polsat News',
        '60':'Cinemax 2 HD','61':'Discovery ID HD','62':'History HD','63':'Explorer','64':'Filmbox','65':'TVP Kultura',
        '66':'Comedy Central Family','67':'NickJR.','68':'Music VOX TV','69':'Eska Best Music TV','70':'Planete+',
        '71':'Tuba TV','72':'Music VOX TV','73':'TVK','74':'Czwórka Polskie Radio','75':'Disney XD','76':'Filmbox Family',
        '77':'TVP Pololnia','78':'Da Vinci Learning','79':'Polsat Film','80':'Disney Channel','81':'Kuchnia+','82':'History',
        '83':'4 Fun.TV','84':'SportKlub','85':'Domo+','86':'AXN Spin HD','87':'Discovery Historia','88':'4 Fun.TV','89':'Disney Junior',
        '94':'Kino Polska Muzyka', '102':'Boomerang', '97':'Polo Party TV', '96':'Fight Klube', '100':'Canal+ HD', '101':'Canal+ Sport HD'}

        sts, data = self.cm.getPage(self.MAIN_URL + 'kanaly.html')
        if not sts: return []
        sts, data = self.cm.ph.getDataBeetwenMarkers(data, "<div id='content'>", "<div id='footer'>", False)
        
        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['title'] = nameMap.get(id, params['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
        
        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
class PurecastNetApi:
    MAIN_URL   = 'http://api.pure-cast.net/'
    MOVIE_URL  = MAIN_URL + 'filmy'
    LIVE_URL   = MAIN_URL + 'kanaly'
    VER_URL    = MAIN_URL + 'wersja'
    AUTH       = '?email={0}&pass={1}'
    HTTP_HEADER  = { 'User-Agent': 'XBMC', 'ContentType': 'application/x-www-form-urlencoded' }

    def __init__(self):
        self.cm = common()
        self.up = urlparser()
        self.sessionEx = MainSessionWrapper()
        self.defParams = {'header':self.HTTP_HEADER}
        self.warned = False
        
    def id_generator(self, size=18, chars=string.ascii_uppercase + string.digits):
        return ''.join(random.choice(chars) for _ in range(size))
        
    def cleanHtmlStr(self, str):
        return CBaseHostClass.cleanHtmlStr(str)
    
    def getChannelsList(self, cItem):
        printDBG("PurecastNetApi.getChannelsList")
        
        login  = config.plugins.iptvplayer.purecastnet_login.value
        passwd = config.plugins.iptvplayer.purecastnet_password.value
        
        if ('' == login or '' == passwd) and not self.warned:
            self.sessionEx.open(MessageBox, _("There are no active premium account.\nUsing a limited version that may not work properly with congested links."), type = MessageBox.TYPE_INFO, timeout = 10 )
            self.warned = True
        
        channelsTab = []
        privCategory = cItem.get('priv_category', None)
        if None == privCategory:
            for item in [('Telewizja Online', 'tv'), ('Filmy Online', 'filmy')]:
                params = dict(cItem)
                params.update({'title':item[0], 'priv_category':item[1]})
                channelsTab.append(params)
            return channelsTab
        elif 'tv' == privCategory:
            url = self.LIVE_URL
            prefix = 'station'
        elif 'filmy' == privCategory:
            url = self.MOVIE_URL
            prefix = 'movie'
        
        url += self.AUTH.format(login, passwd)
        
        sts, data = self.cm.getPage(url, self.defParams)
        if not sts: return []
        try:
            data = byteify(json.loads(data))
            for item in data:
                params = dict(cItem)
                params.update({'type':'video', 'title':item[prefix+'Name'], 'icon':item[prefix+'Logo'], 'vid_url':item[prefix+'URL'].replace('swfVfy=true', ' ')})
                channelsTab.append(params)
        except:
            printExc()
        return channelsTab
        
    def getPage(self, url, params={}, post_data=None):
        proxy = 'http://www.proxy-german.de/index.php?q={0}&hl=240'.format(urllib.quote_plus(url))
        params['header']['Referer'] = proxy
        url = proxy
        return self.cm.getPage(url, params, post_data)

    def getVideoLink(self, cItem):
        printDBG("PurecastNetApi.getVideoLink")
        
        urlsTab = [{'name':'kodi', 'url':cItem['vid_url']}]
        if 0:
            channelID = self.cm.ph.getSearchGroups(cItem['vid_url'], '[^\?]+?/([^/^\?]+?)\?')[0]
            url = 'http://pure-cast.net/kanalyPlayer?id=%s' %  channelID
            HTTP_HEADER = dict(self.HTTP_HEADER)
            HTTP_HEADER['User-Agent'] = self.id_generator()
            HTTP_HEADER['X-Forwarded-For'] = ".".join(map(str, (random.randint(0, 255) for _ in range(4))))
            
            sts, data = self.getPage(url, {'header':HTTP_HEADER})
            if not sts: return urlsTab
            
            rtmpUrl = self.cm.ph.getSearchGroups(data, '''["'](rtmp[^'^"]+?)['"]''')[0]
            url = rtmpUrl + ' swfUrl=http://pure-cast.net/jwplayer/jwplayer.flash.swf live=live'
            if url.startswith('rtmp://'):
                urlsTab.append({'name':'webpage', 'url':url})
        
        return urlsTab
示例#35
0
class PierwszaTVApi:
    MAIN_URL   = 'http://pierwsza.tv/'
    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': MAIN_URL }
    
    def __init__(self):
        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 = {}
        
    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.startswith('http'):
            return url
        elif url.startswith('/'):
            return self.MAIN_URL + url[1:]
        return 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 )
        
        channelsTab = []
        sts, data = self.cm.getPage(self.MAIN_URL + 'player/watch?show=active')
        if not sts: return []
        data = self.cm.ph.getAllItemsBeetwenMarkers(data, '<a class="source', '</a>')
        for item in data:
            url   = self.getFullUrl( self.cm.ph.getSearchGroups(item, '''href="([^"]+?)"''', 1, True)[0] )
            icon  = self.getFullUrl( self.cm.ph.getSearchGroups(item, '''src="([^"]+?)"''', 1, True)[0] )
            #icon = ''
            title = self.cleanHtmlStr( self.cm.ph.getDataBeetwenMarkers(item, '<div class="name">', '</div>', False)[1] )
            desc  = self.cleanHtmlStr( item.split('<div class="author">')[-1] )
            if not url.startswith('http'): continue
            params = dict(cItem)
            params.update({'title':title, 'url':url, 'icon':icon, 'desc':desc})
            channelsTab.append(params)
        return channelsTab
        
    def getVideoLink(self, cItem):
        printDBG("TelewizjadaNetApi.getVideoLink")
        params    = {'header' : self.HTTP_HEADER, 'cookiefile' : self.COOKIE_FILE, 'save_cookie' : True}
        sts, data = self.cm.getPage(cItem['url'], params)
        if not sts: return []
        
        tmp = self.cm.ph.getDataBeetwenMarkers(data, 'connectToLive(', ')', False)[1]
        tmp = self.cm.ph.getSearchGroups(tmp, '''['"]([^'^"]+?)['"][^'^"]+?['"]([^'^"]+?)['"]''', 2, True)
        mainCon = {'url':tmp[0], 'token':tmp[1]}
        
        varData = data #self.cm.ph.getDataBeetwenMarkers(data, 'window.', 'var items')[1]
        window = {'streamUrl':'', 'endpoints':'', 'sourceId':'', 'sourceType':'', 'sourcePlayer':'', 'streamId':'', 'streamToken':'', 'serverId':''} 
        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
        
        window['urls'] = {}
        for keyUrl in ['playRecord', 'player', 'sync', 'multiLogin', 'reportError', 'reportOk', 'bumpToken']:
            window['urls'][keyUrl] = self.cm.ph.getSearchGroups(varData, '''window\.urls\['[^']+?\@%s'\][\s]*?=[\s]*?['"]([^'^"]+?)['"]''' % keyUrl, 1, True)[0].strip()
        
        for keyUrl in ['requestStream']:
            window['urls'][keyUrl] = self.cm.ph.getSearchGroups(varData, '''window\.routes\['[^']+?\@%s'\][\s]*?=[\s]*?['"]([^'^"]+?)['"]''' % keyUrl, 1, True)[0].strip()
        
        urlsTab = []
        try:
            printDBG(window)
            if '' != window['streamUrl']:
                tmp = window['streamUrl'].replace('\\"', '"')
            else:
                tmp = window['endpoints'].replace('\\"', '"')
            streamUrl = byteify(json.loads(tmp))
            ciphertext = base64.b64decode(streamUrl['ct'])
            iv         = a2b_hex(streamUrl['iv'])
            salt       = a2b_hex(streamUrl['s'])
            
            tmp = self.cryptoJS_AES_decrypt(ciphertext, 'number-one', salt)
            tmp = byteify(json.loads(tmp))
            tmp = byteify(json.loads(tmp))
            
            if isinstance(tmp, list):
                tmp = tmp[0]
            
            if isinstance(tmp, dict):
                baseUrl1     = mainCon['url']
                streamToken1 = mainCon['token']
                baseUrl2     = tmp['server']
                streamToken2 = tmp['token']
                
                serverId = tmp['id']
                
                printDBG("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
                printDBG(tmp)
                printDBG("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
                
                t1 = self.getTimestamp(time()*1000)
                url = baseUrl1 + '/socket.io/?EIO=3&transport=polling&t=' + t1
                sts, data = self.cm.getPage(url, self.http_params2)
                baseParams1 = data[data.find('{'):]
                baseParams1 = byteify(json.loads(baseParams1))
                printDBG("=========================================================")
                printDBG([data])
                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)
                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, '102: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 + window['sourceId'] + stoken).hexdigest()
                url = window['urls']["requestStream"] + "?token=" + streamToken2 + "&server=" + serverId + "&source=" + window['sourceId'] + "&cs=" + n
                sts, data = self.cm.getPage(url, self.http_params)
                data = byteify( json.loads(data) ) 
                streamId = 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("fake://fake", {'iptv_proto':'em3u8', 'iptv_buffering': 'required', 'iptv_refresh_cmd':pyCmd, 'Referer':cItem['url'], 'User-Agent':self.http_params['header']['User-Agent']})
                
                printDBG("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
                printDBG(pyCmd)
                printDBG("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
                
                return [{'name':'pierwsza_hls', 'url':vidUrl}]
            
        except:
            printExc()
            return []
        
        return urlsTab
        
    def doLogin(self, login, password):
        logged = False
        loginUrl = self.MAIN_URL + 'account/login'
        
        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(PierwszaTVApi.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
class Host:
    currList = []
    MAIN_URL = ''
    PREMIUM = False
    konto = ''
    COOKIEFILE = ''
    HOST = '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'

    def __init__(self):
        printDBG( 'Host __init__ begin' )
        self.exSession = MainSessionWrapper()
        self.COOKIEFILE = GetCookieDir('scseriale.cookie')        
        self.cm = common()
        self.currList = []
        self.up = urlparser()
        self.history = CSearchHistoryHelper('wspolne')
        printDBG( 'Host __init__ end' )
        
    def setCurrList(self, list):
        printDBG( 'Host setCurrList begin' )
        self.currList = list
        printDBG( 'Host setCurrList end' )
        return 

    def getInitList(self):
        printDBG( 'Host getInitList begin' )
        ####################################
        # logowanie
        ####################################
        self.PREMIUM = self.listsItems(-1, 'zaloguj', 'zaloguj')
        ####################################
        self.currList = self.listsItems(-1, 'main-menu', 'main-menu')
        printDBG( 'Host getInitList end' )
        return self.currList

    def getListForItem(self, Index = 0, refresh = 0, selItem = None):
        printDBG( 'Host getListForItem begin' )
        valTab = []
        if len(self.currList[Index].urlItems) == 0:
           return valTab
        valTab = self.listsItems(Index, self.currList[Index].urlItems[0], self.currList[Index].urlSeparateRequest)
        self.currList = valTab
        printDBG( 'Host getListForItem end' )
        return self.currList

    def getSearchResults(self, pattern, searchType = None):
        printDBG( "Host getSearchResults begin" )
        printDBG( "Host getSearchResults pattern: " +pattern)
        valTab = []
        valTab = self.listsItems(-1, pattern, 'search')
        self.currList = valTab
        printDBG( "Host getSearchResults end" )
        return self.currList

    def listsItems(self, Index, url, name = ''):
        printDBG( 'Host listsItems begin' )
        printDBG( 'Host listsItems url: '+url )
        valTab = []
        # ########## #
        if name == 'main-menu':
           printDBG( 'Host listsItems begin name='+name )
           self.MAIN_URL = 'http://scs.pl'
           valTab.append(CDisplayListItem("Seriale wg. kategorii"+self.konto,'http://scs.pl/seriale.html', CDisplayListItem.TYPE_CATEGORY, ['http://scs.pl/seriale.html'],       'seriale-kategorie',  '', None)) 
           valTab.append(CDisplayListItem("Seriale alfabetycznie",           'http://scs.pl/seriale.html', CDisplayListItem.TYPE_CATEGORY, ['http://scs.pl/seriale.html'],       'seriale-abc',  '', None)) 
           valTab.append(CDisplayListItem("Ostatnio aktualizowane seriale",  'http://scs.pl/ostatnio_aktualizowane_seriale.html',   CDisplayListItem.TYPE_CATEGORY, ['http://scs.pl/ostatnio_aktualizowane_seriale.html'], 'seriale-last', '', None)) 
           valTab.append(CDisplayListItem('Szukaj',                          'Szukaj',                     CDisplayListItem.TYPE_SEARCH,   ['http://scs.pl/serial,szukaj.html'], 'search',       '', None)) 
           valTab.append(CDisplayListItem('Historia wyszukiwania', 'Historia wyszukiwania', CDisplayListItem.TYPE_CATEGORY, [''],   'history', '', None)) 
           printDBG( 'Host listsItems end' )
           return valTab

        # ########## #
        if 'zaloguj' == name:
           printDBG( 'Host listsItems begin name='+name )
           if config.plugins.iptvplayer.scserialePREMIUM.value:
              url = 'http://scs.pl/logowanie.html'
              try: data = self.cm.getURLRequestData({ 'url': url, 'use_host': True, 'host': self.HOST, 'use_cookie': True, 'save_cookie': True, 'load_cookie': False, 'cookiefile': self.COOKIEFILE, 'use_post': True, 'return_data': True },{'email': config.plugins.iptvplayer.scseriale_login.value, 'password': config.plugins.iptvplayer.scseriale_password.value})
              except:
                 printDBG( 'Host listsItems query error' )
                 printDBG( 'Host listsItems query error url:'+url )
                 printDBG( 'Host listsItems query error: Uzywam Player z limitami')
                 data = None
              if data:
                 self.PREMIUM = True
                 printDBG( 'Host listsItems: chyba zalogowano do premium...' )
                 url = 'http://scs.pl/premium.html'
                 try: 
                    data = self.cm.getURLRequestData({ 'url': url, 'use_host': True, 'host': self.HOST, 'use_cookie': True, 'save_cookie': False, 'load_cookie': True, 'cookiefile': self.COOKIEFILE, 'use_post': False, 'return_data': True })
                    printDBG( 'Host listsItems data: '+data )
                    parse = re.search('Konto premium ważne do(.*?)".*?;(.*?)<', data, re.S)
                    if parse:
                       self.konto = ' - Twoje konto: '+parse.group(2)+parse.group(1)
                    else: 
                       self.konto = ''
                 except:
                    printDBG( 'Host listsItems: blad pobrania danych o koncie premium' )
                 
              if '' == self.konto:
                 self.exSession.open(MessageBox, 'Problem z zalogowaniem użytkownika \n"%s" jako VIP.' % config.plugins.iptvplayer.scseriale_login.value, type = MessageBox.TYPE_INFO, timeout = 10)
                 
           printDBG( 'Host listsItems end' )
           return self.PREMIUM

        # ########## #
        if 'history' == name:
           printDBG( 'Host listsItems begin name='+name )
           for histItem in self.history.getHistoryList():
               valTab.append(CDisplayListItem(histItem['pattern'], 'Szukaj ', CDisplayListItem.TYPE_CATEGORY, [histItem['pattern'],histItem['type']], 'search', '', None))          
           printDBG( 'Host listsItems end' )
           return valTab

        # ########## #
        if 'search' == name:
           printDBG( 'Host listsItems begin name='+name )
           pattern = url            
           if Index==-1: 
              self.history.addHistoryItem( pattern, 'seriale')
           url = 'http://scs.pl/serial,szukaj.html'
           postdata = { 'search': pattern }
           try: data = self.cm.getURLRequestData({ 'url': url, 'use_host': False, 'use_cookie': False, 'use_post': True, 'return_data': True },postdata)
           except:
              printDBG( 'Host listsItems query error' )
              printDBG( 'Host listsItems query error url:'+url )
              return valTab
           #printDBG( 'Host listsItems data: '+data )
           match = re.findall('<div class="img_box"><a href="(.*?)">.*?<img src="(.*?)" alt="(.*?)"', data, re.S)
           if len(match) > 0:
              for i in range(len(match)):
                  phImage = match[i][1]
                  phUrl = self.MAIN_URL+'/'+ match[i][0]
                  phTitle = match[i][2]
                  printDBG( 'Host listsItems phImage: '  +phImage )
                  printDBG( 'Host listsItems phUrl: '    +phUrl )
                  printDBG( 'Host listsItems phTitle: '  +phTitle )
                  valTab.append(CDisplayListItem(phTitle, phTitle, CDisplayListItem.TYPE_CATEGORY, [phUrl], 'seriale-sezony', phImage, None))
           printDBG( 'Host listsItems end' )
           return valTab
           
        # ########## #
        if 'seriale-last' == name:
           printDBG( 'Host listsItems begin name='+name )
           try: data = self.cm.getURLRequestData({ 'url': url, 'use_host': False, 'use_cookie': False, 'use_post': False, 'return_data': True })
           except:
              printDBG( 'Host listsItems query error' )
              printDBG( 'Host listsItems query error url:'+url )
              return valTab
           #printDBG( 'Host listsItems data: '+data )
           match = re.compile('online">(.+?)</a></div></div><span class="newest_ep" id=".+?">Ostatnio dodany:<br/><a href="odcinek,(.+?),(.+?),(.+?),(.+?).html">').findall(data)
           if len(match) > 0:
              for i in range(len(match)):
                  phImage='http://static.scs.pl/static/serials/' + match[i][1].replace('.html', '.jpg')+'.jpg'
                  phTitleS = match[i][1]
                  phTitle = match[i][0] + ' - ' + match[i][4] + ' - ' + match[i][2].capitalize().replace('-', ' ')
                  phUrlS = self.MAIN_URL + '/serial,' + match[i][0]
                  phUrl = self.MAIN_URL + '/odcinek,' + match[i][1] + ',' + match[i][2] + ',' + match[i][3] + ',' + match[i][4] + '.html'
                  printDBG( 'Host listsItems phImage: '  +phImage )
                  printDBG( 'Host listsItems phUrl: '  +phUrl )
                  printDBG( 'Host listsItems phTitle: '+phTitle )
                  valTab.append(CDisplayListItem(phTitleS, phTitleS, CDisplayListItem.TYPE_CATEGORY, [phUrlS], 'seriale-sezony', phImage, None))
                  valTab.append(CDisplayListItem(phTitle,  phTitle,  CDisplayListItem.TYPE_VIDEO, [CUrlItem('', phUrl, 1)], 0, phImage, None))
           printDBG( 'Host listsItems end' )
           return valTab
        if 'seriale-kategorie' == name:
           printDBG( 'Host listsItems begin name='+name )
           try: data = self.cm.getURLRequestData({ 'url': url, 'use_host': False, 'use_cookie': False, 'use_post': False, 'return_data': True })
           except:
              printDBG( 'Host listsItems query error' )
              printDBG( 'Host listsItems query error url:'+url )
              return valTab
           #printDBG( 'Host listsItems data: '+data )
           phMovies = re.findall('<span class="title1">(.*?)</span>(.*?)<.*?href="(.*?)"', data, re.S)
           if phMovies:
              for (phTitle, phCount, phUrl) in phMovies:
                  printDBG( 'Host listsItems phTitle: '+phTitle )
                  printDBG( 'Host listsItems phCount: '+phCount )
                  printDBG( 'Host listsItems phUrl: '  +phUrl )
                  valTab.append(CDisplayListItem(phTitle+phCount, phTitle, CDisplayListItem.TYPE_CATEGORY, [self.MAIN_URL+'/'+phUrl], 'seriale-kategoria', '', None))          
           printDBG( 'Host listsItems end' )
           return valTab
        if 'seriale-kategoria' == name:
           printDBG( 'Host listsItems begin name='+name )
           try: data = self.cm.getURLRequestData({ 'url': url, 'use_host': False, 'use_cookie': False, 'use_post': False, 'return_data': True })
           except:
              printDBG( 'Host listsItems query error' )
              printDBG( 'Host listsItems query error url:'+url )
              return valTab
           #printDBG( 'Host listsItems data: '+data )
           match = re.compile('class="serial_green" href="serial,(.+?)">(.+?)</a><br/>').findall(data)
           if len(match) > 0:
              for i in range(len(match)):
                  phImage='http://static.scs.pl/static/serials/' + match[i][0].replace('.html', '.jpg')
                  phTitle = match[i][1]
                  phUrl = self.MAIN_URL + '/serial,' + match[i][0]
                  printDBG( 'Host listsItems phImage: '  +phImage )
                  printDBG( 'Host listsItems phUrl: '  +phUrl )
                  printDBG( 'Host listsItems phTitle: '+phTitle )
                  valTab.append(CDisplayListItem(phTitle, phTitle, CDisplayListItem.TYPE_CATEGORY, [phUrl], 'seriale-sezony', phImage, None))
           printDBG( 'Host listsItems end' )
           return valTab
        if 'seriale-abc' == name:
           printDBG( 'Host listsItems begin name='+name )
           abcTab = self.cm.makeABCList()
           for i in range(len(abcTab)):
               phTitle = abcTab[i]
               valTab.append(CDisplayListItem(phTitle, phTitle, CDisplayListItem.TYPE_CATEGORY, [url,phTitle], 'seriale-alfabet', '', None))          
           printDBG( 'Host listsItems end' )
           return valTab
        if 'seriale-alfabet' == name:
           printDBG( 'Host listsItems begin name='+name )
           try: data = self.cm.getURLRequestData({ 'url': url, 'use_host': False, 'use_cookie': False, 'use_post': False, 'return_data': True })
           except:
              printDBG( 'Host listsItems query error' )
              printDBG( 'Host listsItems query error url:'+url )
              return valTab
           #printDBG( 'Host listsItems data: '+data )
           letter = self.currList[Index].urlItems[1]
           match = re.compile(' <a class="serial_green" href="serial,(.+?)">(.+?)</a><br/>').findall(data)
           if len(match) > 0:
              for i in range(len(match)):
                addItem = False
                if letter == '0 - 9' and (ord(match[i][1][0]) < 65 or ord(match[i][1][0]) > 91): addItem = True
                if (letter == match[i][1][0].upper()): addItem = True
                if (addItem):
                    phImage='http://static.scs.pl/static/serials/' + match[i][0].replace('.html', '.jpg')
                    phTitle = match[i][1]
                    phUrl = self.MAIN_URL + '/serial,' + match[i][0]
                    printDBG( 'Host listsItems phImage: '  +phImage )
                    printDBG( 'Host listsItems phUrl: '  +phUrl )
                    printDBG( 'Host listsItems phTitle: '+phTitle )
                    valTab.append(CDisplayListItem(phTitle, phTitle, CDisplayListItem.TYPE_CATEGORY, [phUrl], 'seriale-sezony', phImage, None))          
           printDBG( 'Host listsItems end' )
           return valTab
        if 'seriale-sezony' == name:
           printDBG( 'Host listsItems begin name='+name )
           try: data = self.cm.getURLRequestData({ 'url': url, 'use_host': False, 'use_cookie': False, 'use_post': False, 'return_data': True })
           except:
              printDBG( 'Host listsItems query error' )
              printDBG( 'Host listsItems query error url:'+url )
              return valTab
           #printDBG( 'Host listsItems data: '+data )
           phMovies = re.compile('<meta itemprop="seasonNumber" content="(.+?)">').findall(data)
           if phMovies:
              phImage=url.replace(self.MAIN_URL + '/serial,', 'http://static.scs.pl/static/serials/').replace('.html', '.jpg')
              printDBG( 'Host listsItems phImage: '+phImage )
              for (phTitle) in phMovies:
                  printDBG( 'Host listsItems phTitle: '+phTitle )
                  valTab.append(CDisplayListItem('Sezon '+phTitle, 'Sezon '+phTitle, CDisplayListItem.TYPE_CATEGORY, [url,phTitle], 'seriale-odcinki', phImage, None))          
           printDBG( 'Host listsItems end' )
           return valTab
        if 'seriale-odcinki' == name:
           printDBG( 'Host listsItems begin name='+name )
           try: data = self.cm.getURLRequestData({ 'url': url, 'use_host': False, 'use_cookie': False, 'use_post': False, 'return_data': True })
           except:
              printDBG( 'Host listsItems query error' )
              printDBG( 'Host listsItems query error url:'+url )
              return valTab
           #printDBG( 'Host listsItems data: '+data )
           sezon = self.currList[Index].urlItems[1]
           r = re.compile('<meta itemprop="seasonNumber" content="' + sezon + '">(.+?)</ul></div>', re.DOTALL).findall(data)
           if not r: return []
           phMovies = re.compile('itemprop="episodeNumber">(.+?)<.+?class="aLink " href="(odcinek,.+?,.+?,.+?,.+?.html)"><span itemprop="name">(.+?)</span></a>').findall(r[0])
           if phMovies:
              phImage=url.replace(self.MAIN_URL + '/serial,', 'http://static.scs.pl/static/serials/').replace('.html', '.jpg')
              serial=url.replace(self.MAIN_URL + '/serial,','').replace('.html', '')
              printDBG( 'Host listsItems phImage: '+phImage )
              for (phEpizod, phUrl, phName) in phMovies:
                  printDBG( 'Host listsItems phEpizod: '+phEpizod )
                  printDBG( 'Host listsItems phUrl: '+phUrl )
                  phTitle = '%s S%sE%s - %s' % (serial, sezon, phEpizod, phName)
                  printDBG( 'Host listsItems phTitle: '+phTitle )
                  valTab.append(CDisplayListItem(phTitle, phTitle, CDisplayListItem.TYPE_CATEGORY, [self.MAIN_URL+'/'+phUrl,phTitle], 'seriale-odcinki-wersje', phImage, None))          
           printDBG( 'Host listsItems end' )
           return valTab
        if 'seriale-odcinki-wersje' == name:
           printDBG( 'Host listsItems begin name='+name )
           try: data = self.cm.getURLRequestData({ 'url': url, 'use_host': False, 'use_cookie': False, 'use_post': False, 'return_data': True })
           except:
              printDBG( 'Host listsItems query error' )
              printDBG( 'Host listsItems query error url:'+url )
              return valTab
           #printDBG( 'Host listsItems data: '+data )
           parse = re.search('Wersje:(.*?)Kopie:', data, re.S)
           if not parse: return []
           phMovies = re.findall('<a href="(.+?)">(.+?)<', parse.group(1), re.S)           
           if phMovies:
              phImage=url.replace(self.MAIN_URL + '/serial,', 'http://static.scs.pl/static/serials/').replace('.html', '.jpg')
              printDBG( 'Host listsItems phImage: '+phImage )
              for (phUrl, phWersja) in phMovies:
                  printDBG( 'Host listsItems phUrl: '+phUrl )
                  printDBG( 'Host listsItems phWersja: '+phWersja )
                  valTab.append(CDisplayListItem(phWersja, phWersja, CDisplayListItem.TYPE_CATEGORY, [self.MAIN_URL+'/'+phUrl], 'seriale-odcinki-kopie', phImage, None))          
           printDBG( 'Host listsItems end' )
           return valTab
        if 'seriale-odcinki-kopie' == name:
           printDBG( 'Host listsItems begin name='+name )
           try: data = self.cm.getURLRequestData({ 'url': url, 'use_host': False, 'use_cookie': False, 'use_post': False, 'return_data': True })
           except:
              printDBG( 'Host listsItems query error' )
              printDBG( 'Host listsItems query error url:'+url )
              return valTab
           #printDBG( 'Host listsItems data: '+data )
           parse = re.search('class="mirrors"(.*?)class="switch"', data, re.S)
           if not parse: return []
           phMovies = re.findall('= "(.+?)"; ccc.+?;.+?"(.+?)";.+?"(.+?)";.+?"(.+?)";', parse.group(1), re.S)           
           if phMovies:
              for (phUrl, phTime, phUser, phComment) in phMovies:
                  printDBG( 'Host listsItems phUrl: '+phUrl )
                  printDBG( 'Host listsItems phTime: '+phTime )
                  printDBG( 'Host listsItems phUser: '******' '+phUser, phTime+' '+phUser+' '+phComment, CDisplayListItem.TYPE_VIDEO, [CUrlItem('', phUrl, 1)], 0, '', None))          
           printDBG( 'Host listsItems end' )
           return valTab

        return valTab

    def getResolvedURL(self, url):
        printDBG( 'Host getResolvedURL begin' )
        printDBG( 'Host getResolvedURL url: '+url )
        postdata = {'f' : url }
        if self.PREMIUM:
           query_data = { 'url': 'http://scs.pl/getVideo.html', 'use_host': True, 'host': self.HOST, 'use_cookie': True, 'save_cookie': False, 'load_cookie': True, 'cookiefile': self.COOKIEFILE, 'use_post': True, 'return_data': True }
        else: 
           query_data = { 'url': 'http://scs.pl/getVideo.html', 'use_host': False, 'use_cookie': False, 'use_post': True, 'return_data': True }
        try: data = self.cm.getURLRequestData(query_data, postdata)
        except:
           printDBG( 'Host getResolvedURL query error premium' )
           printDBG( 'Host getResolvedURL query error premium url: '+url )
           return ''
        #printDBG( 'Host getResolvedURL premium data: ' +data)
        match = re.compile("url: '(.+?)',").findall(data)
        if len(match) > 0:
           linkVideo = match[0]
           printDBG( 'Host getResolvedURL linkVideo: ' + linkVideo)
           printDBG( 'Host getResolvedURL end premium' )
           return linkVideo
        printDBG( 'Host getResolvedURL end' )
        return ''
 def __init__(self):
     self.cm = common()
     self.up = urlparser()
     self.sessionEx = MainSessionWrapper()
     self.defParams = {'header':self.HTTP_HEADER}
     self.warned = False
class Host:
    currList = []
    MAIN_URL = ''
    PREMIUM = False
    konto = ''
    COOKIEFILE = ''
    HOST = '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'

    def __init__(self):
        printDBG('Host __init__ begin')
        self.exSession = MainSessionWrapper()
        self.COOKIEFILE = GetCookieDir('scseriale.cookie')
        self.cm = common()
        self.currList = []
        self.up = urlparser()
        self.history = CSearchHistoryHelper('wspolne')
        printDBG('Host __init__ end')

    def setCurrList(self, list):
        printDBG('Host setCurrList begin')
        self.currList = list
        printDBG('Host setCurrList end')
        return

    def getInitList(self):
        printDBG('Host getInitList begin')
        ####################################
        # logowanie
        ####################################
        self.PREMIUM = self.listsItems(-1, 'zaloguj', 'zaloguj')
        ####################################
        self.currList = self.listsItems(-1, 'main-menu', 'main-menu')
        printDBG('Host getInitList end')
        return self.currList

    def getListForItem(self, Index=0, refresh=0, selItem=None):
        printDBG('Host getListForItem begin')
        valTab = []
        if len(self.currList[Index].urlItems) == 0:
            return valTab
        valTab = self.listsItems(Index, self.currList[Index].urlItems[0],
                                 self.currList[Index].urlSeparateRequest)
        self.currList = valTab
        printDBG('Host getListForItem end')
        return self.currList

    def getSearchResults(self, pattern, searchType=None):
        printDBG("Host getSearchResults begin")
        printDBG("Host getSearchResults pattern: " + pattern)
        valTab = []
        valTab = self.listsItems(-1, pattern, 'search')
        self.currList = valTab
        printDBG("Host getSearchResults end")
        return self.currList

    def listsItems(self, Index, url, name=''):
        printDBG('Host listsItems begin')
        printDBG('Host listsItems url: ' + url)
        valTab = []
        # ########## #
        if name == 'main-menu':
            printDBG('Host listsItems begin name=' + name)
            self.MAIN_URL = 'http://scs.pl'
            valTab.append(
                CDisplayListItem("Seriale wg. kategorii" + self.konto,
                                 'http://scs.pl/seriale.html',
                                 CDisplayListItem.TYPE_CATEGORY,
                                 ['http://scs.pl/seriale.html'],
                                 'seriale-kategorie', '', None))
            valTab.append(
                CDisplayListItem("Seriale alfabetycznie",
                                 'http://scs.pl/seriale.html',
                                 CDisplayListItem.TYPE_CATEGORY,
                                 ['http://scs.pl/seriale.html'], 'seriale-abc',
                                 '', None))
            valTab.append(
                CDisplayListItem(
                    "Ostatnio aktualizowane seriale",
                    'http://scs.pl/ostatnio_aktualizowane_seriale.html',
                    CDisplayListItem.TYPE_CATEGORY,
                    ['http://scs.pl/ostatnio_aktualizowane_seriale.html'],
                    'seriale-last', '', None))
            valTab.append(
                CDisplayListItem('Szukaj', 'Szukaj',
                                 CDisplayListItem.TYPE_SEARCH,
                                 ['http://scs.pl/serial,szukaj.html'],
                                 'search', '', None))
            valTab.append(
                CDisplayListItem('Historia wyszukiwania',
                                 'Historia wyszukiwania',
                                 CDisplayListItem.TYPE_CATEGORY, [''],
                                 'history', '', None))
            printDBG('Host listsItems end')
            return valTab

        # ########## #
        if 'zaloguj' == name:
            printDBG('Host listsItems begin name=' + name)
            if config.plugins.iptvplayer.scserialePREMIUM.value:
                url = 'http://scs.pl/logowanie.html'
                try:
                    data = self.cm.getURLRequestData(
                        {
                            'url': url,
                            'use_host': True,
                            'host': self.HOST,
                            'use_cookie': True,
                            'save_cookie': True,
                            'load_cookie': False,
                            'cookiefile': self.COOKIEFILE,
                            'use_post': True,
                            'return_data': True
                        }, {
                            'email':
                            config.plugins.iptvplayer.scseriale_login.value,
                            'password':
                            config.plugins.iptvplayer.scseriale_password.value
                        })
                except:
                    printDBG('Host listsItems query error')
                    printDBG('Host listsItems query error url:' + url)
                    printDBG(
                        'Host listsItems query error: Uzywam Player z limitami'
                    )
                    data = None
                if data:
                    self.PREMIUM = True
                    printDBG('Host listsItems: chyba zalogowano do premium...')
                    url = 'http://scs.pl/premium.html'
                    try:
                        data = self.cm.getURLRequestData({
                            'url': url,
                            'use_host': True,
                            'host': self.HOST,
                            'use_cookie': True,
                            'save_cookie': False,
                            'load_cookie': True,
                            'cookiefile': self.COOKIEFILE,
                            'use_post': False,
                            'return_data': True
                        })
                        printDBG('Host listsItems data: ' + data)
                        parse = re.search(
                            'Konto premium ważne do(.*?)".*?;(.*?)<', data,
                            re.S)
                        if parse:
                            self.konto = ' - Twoje konto: ' + parse.group(
                                2) + parse.group(1)
                        else:
                            self.konto = ''
                    except:
                        printDBG(
                            'Host listsItems: blad pobrania danych o koncie premium'
                        )

                if '' == self.konto:
                    self.exSession.open(
                        MessageBox,
                        'Problem z zalogowaniem użytkownika \n"%s" jako VIP.' %
                        config.plugins.iptvplayer.scseriale_login.value,
                        type=MessageBox.TYPE_INFO,
                        timeout=10)

            printDBG('Host listsItems end')
            return self.PREMIUM

        # ########## #
        if 'history' == name:
            printDBG('Host listsItems begin name=' + name)
            for histItem in self.history.getHistoryList():
                valTab.append(
                    CDisplayListItem(histItem['pattern'], 'Szukaj ',
                                     CDisplayListItem.TYPE_CATEGORY,
                                     [histItem['pattern'], histItem['type']],
                                     'search', '', None))
            printDBG('Host listsItems end')
            return valTab

        # ########## #
        if 'search' == name:
            printDBG('Host listsItems begin name=' + name)
            pattern = url
            if Index == -1:
                self.history.addHistoryItem(pattern, 'seriale')
            url = 'http://scs.pl/serial,szukaj.html'
            postdata = {'search': pattern}
            try:
                data = self.cm.getURLRequestData(
                    {
                        'url': url,
                        'use_host': False,
                        'use_cookie': False,
                        'use_post': True,
                        'return_data': True
                    }, postdata)
            except:
                printDBG('Host listsItems query error')
                printDBG('Host listsItems query error url:' + url)
                return valTab
            #printDBG( 'Host listsItems data: '+data )
            match = re.findall(
                '<div class="img_box"><a href="(.*?)">.*?<img src="(.*?)" alt="(.*?)"',
                data, re.S)
            if len(match) > 0:
                for i in range(len(match)):
                    phImage = match[i][1]
                    phUrl = self.MAIN_URL + '/' + match[i][0]
                    phTitle = match[i][2]
                    printDBG('Host listsItems phImage: ' + phImage)
                    printDBG('Host listsItems phUrl: ' + phUrl)
                    printDBG('Host listsItems phTitle: ' + phTitle)
                    valTab.append(
                        CDisplayListItem(phTitle, phTitle,
                                         CDisplayListItem.TYPE_CATEGORY,
                                         [phUrl], 'seriale-sezony', phImage,
                                         None))
            printDBG('Host listsItems end')
            return valTab

        # ########## #
        if 'seriale-last' == name:
            printDBG('Host listsItems begin name=' + name)
            try:
                data = self.cm.getURLRequestData({
                    'url': url,
                    'use_host': False,
                    'use_cookie': False,
                    'use_post': False,
                    'return_data': True
                })
            except:
                printDBG('Host listsItems query error')
                printDBG('Host listsItems query error url:' + url)
                return valTab
            #printDBG( 'Host listsItems data: '+data )
            match = re.compile(
                'online">(.+?)</a></div></div><span class="newest_ep" id=".+?">Ostatnio dodany:<br/><a href="odcinek,(.+?),(.+?),(.+?),(.+?).html">'
            ).findall(data)
            if len(match) > 0:
                for i in range(len(match)):
                    phImage = 'http://static.scs.pl/static/serials/' + match[
                        i][1].replace('.html', '.jpg') + '.jpg'
                    phTitleS = match[i][1]
                    phTitle = match[i][0] + ' - ' + match[i][
                        4] + ' - ' + match[i][2].capitalize().replace(
                            '-', ' ')
                    phUrlS = self.MAIN_URL + '/serial,' + match[i][0]
                    phUrl = self.MAIN_URL + '/odcinek,' + match[i][
                        1] + ',' + match[i][2] + ',' + match[i][
                            3] + ',' + match[i][4] + '.html'
                    printDBG('Host listsItems phImage: ' + phImage)
                    printDBG('Host listsItems phUrl: ' + phUrl)
                    printDBG('Host listsItems phTitle: ' + phTitle)
                    valTab.append(
                        CDisplayListItem(phTitleS, phTitleS,
                                         CDisplayListItem.TYPE_CATEGORY,
                                         [phUrlS], 'seriale-sezony', phImage,
                                         None))
                    valTab.append(
                        CDisplayListItem(phTitle, phTitle,
                                         CDisplayListItem.TYPE_VIDEO,
                                         [CUrlItem('', phUrl, 1)], 0, phImage,
                                         None))
            printDBG('Host listsItems end')
            return valTab
        if 'seriale-kategorie' == name:
            printDBG('Host listsItems begin name=' + name)
            try:
                data = self.cm.getURLRequestData({
                    'url': url,
                    'use_host': False,
                    'use_cookie': False,
                    'use_post': False,
                    'return_data': True
                })
            except:
                printDBG('Host listsItems query error')
                printDBG('Host listsItems query error url:' + url)
                return valTab
            #printDBG( 'Host listsItems data: '+data )
            phMovies = re.findall(
                '<span class="title1">(.*?)</span>(.*?)<.*?href="(.*?)"', data,
                re.S)
            if phMovies:
                for (phTitle, phCount, phUrl) in phMovies:
                    printDBG('Host listsItems phTitle: ' + phTitle)
                    printDBG('Host listsItems phCount: ' + phCount)
                    printDBG('Host listsItems phUrl: ' + phUrl)
                    valTab.append(
                        CDisplayListItem(phTitle + phCount, phTitle,
                                         CDisplayListItem.TYPE_CATEGORY,
                                         [self.MAIN_URL + '/' + phUrl],
                                         'seriale-kategoria', '', None))
            printDBG('Host listsItems end')
            return valTab
        if 'seriale-kategoria' == name:
            printDBG('Host listsItems begin name=' + name)
            try:
                data = self.cm.getURLRequestData({
                    'url': url,
                    'use_host': False,
                    'use_cookie': False,
                    'use_post': False,
                    'return_data': True
                })
            except:
                printDBG('Host listsItems query error')
                printDBG('Host listsItems query error url:' + url)
                return valTab
            #printDBG( 'Host listsItems data: '+data )
            match = re.compile(
                'class="serial_green" href="serial,(.+?)">(.+?)</a><br/>'
            ).findall(data)
            if len(match) > 0:
                for i in range(len(match)):
                    phImage = 'http://static.scs.pl/static/serials/' + match[
                        i][0].replace('.html', '.jpg')
                    phTitle = match[i][1]
                    phUrl = self.MAIN_URL + '/serial,' + match[i][0]
                    printDBG('Host listsItems phImage: ' + phImage)
                    printDBG('Host listsItems phUrl: ' + phUrl)
                    printDBG('Host listsItems phTitle: ' + phTitle)
                    valTab.append(
                        CDisplayListItem(phTitle, phTitle,
                                         CDisplayListItem.TYPE_CATEGORY,
                                         [phUrl], 'seriale-sezony', phImage,
                                         None))
            printDBG('Host listsItems end')
            return valTab
        if 'seriale-abc' == name:
            printDBG('Host listsItems begin name=' + name)
            abcTab = self.cm.makeABCList()
            for i in range(len(abcTab)):
                phTitle = abcTab[i]
                valTab.append(
                    CDisplayListItem(phTitle, phTitle,
                                     CDisplayListItem.TYPE_CATEGORY,
                                     [url, phTitle], 'seriale-alfabet', '',
                                     None))
            printDBG('Host listsItems end')
            return valTab
        if 'seriale-alfabet' == name:
            printDBG('Host listsItems begin name=' + name)
            try:
                data = self.cm.getURLRequestData({
                    'url': url,
                    'use_host': False,
                    'use_cookie': False,
                    'use_post': False,
                    'return_data': True
                })
            except:
                printDBG('Host listsItems query error')
                printDBG('Host listsItems query error url:' + url)
                return valTab
            #printDBG( 'Host listsItems data: '+data )
            letter = self.currList[Index].urlItems[1]
            match = re.compile(
                ' <a class="serial_green" href="serial,(.+?)">(.+?)</a><br/>'
            ).findall(data)
            if len(match) > 0:
                for i in range(len(match)):
                    addItem = False
                    if letter == '0 - 9' and (ord(match[i][1][0]) < 65
                                              or ord(match[i][1][0]) > 91):
                        addItem = True
                    if (letter == match[i][1][0].upper()): addItem = True
                    if (addItem):
                        phImage = 'http://static.scs.pl/static/serials/' + match[
                            i][0].replace('.html', '.jpg')
                        phTitle = match[i][1]
                        phUrl = self.MAIN_URL + '/serial,' + match[i][0]
                        printDBG('Host listsItems phImage: ' + phImage)
                        printDBG('Host listsItems phUrl: ' + phUrl)
                        printDBG('Host listsItems phTitle: ' + phTitle)
                        valTab.append(
                            CDisplayListItem(phTitle, phTitle,
                                             CDisplayListItem.TYPE_CATEGORY,
                                             [phUrl], 'seriale-sezony',
                                             phImage, None))
            printDBG('Host listsItems end')
            return valTab
        if 'seriale-sezony' == name:
            printDBG('Host listsItems begin name=' + name)
            try:
                data = self.cm.getURLRequestData({
                    'url': url,
                    'use_host': False,
                    'use_cookie': False,
                    'use_post': False,
                    'return_data': True
                })
            except:
                printDBG('Host listsItems query error')
                printDBG('Host listsItems query error url:' + url)
                return valTab
            #printDBG( 'Host listsItems data: '+data )
            phMovies = re.compile(
                '<meta itemprop="seasonNumber" content="(.+?)">').findall(data)
            if phMovies:
                phImage = url.replace(
                    self.MAIN_URL + '/serial,',
                    'http://static.scs.pl/static/serials/').replace(
                        '.html', '.jpg')
                printDBG('Host listsItems phImage: ' + phImage)
                for (phTitle) in phMovies:
                    printDBG('Host listsItems phTitle: ' + phTitle)
                    valTab.append(
                        CDisplayListItem('Sezon ' + phTitle,
                                         'Sezon ' + phTitle,
                                         CDisplayListItem.TYPE_CATEGORY,
                                         [url, phTitle], 'seriale-odcinki',
                                         phImage, None))
            printDBG('Host listsItems end')
            return valTab
        if 'seriale-odcinki' == name:
            printDBG('Host listsItems begin name=' + name)
            try:
                data = self.cm.getURLRequestData({
                    'url': url,
                    'use_host': False,
                    'use_cookie': False,
                    'use_post': False,
                    'return_data': True
                })
            except:
                printDBG('Host listsItems query error')
                printDBG('Host listsItems query error url:' + url)
                return valTab
            #printDBG( 'Host listsItems data: '+data )
            sezon = self.currList[Index].urlItems[1]
            r = re.compile(
                '<meta itemprop="seasonNumber" content="' + sezon +
                '">(.+?)</ul></div>', re.DOTALL).findall(data)
            if not r: return []
            phMovies = re.compile(
                'itemprop="episodeNumber">(.+?)<.+?class="aLink " href="(odcinek,.+?,.+?,.+?,.+?.html)"><span itemprop="name">(.+?)</span></a>'
            ).findall(r[0])
            if phMovies:
                phImage = url.replace(
                    self.MAIN_URL + '/serial,',
                    'http://static.scs.pl/static/serials/').replace(
                        '.html', '.jpg')
                serial = url.replace(self.MAIN_URL + '/serial,',
                                     '').replace('.html', '')
                printDBG('Host listsItems phImage: ' + phImage)
                for (phEpizod, phUrl, phName) in phMovies:
                    printDBG('Host listsItems phEpizod: ' + phEpizod)
                    printDBG('Host listsItems phUrl: ' + phUrl)
                    phTitle = '%s S%sE%s - %s' % (serial, sezon, phEpizod,
                                                  phName)
                    printDBG('Host listsItems phTitle: ' + phTitle)
                    valTab.append(
                        CDisplayListItem(
                            phTitle, phTitle, CDisplayListItem.TYPE_CATEGORY,
                            [self.MAIN_URL + '/' + phUrl, phTitle],
                            'seriale-odcinki-wersje', phImage, None))
            printDBG('Host listsItems end')
            return valTab
        if 'seriale-odcinki-wersje' == name:
            printDBG('Host listsItems begin name=' + name)
            try:
                data = self.cm.getURLRequestData({
                    'url': url,
                    'use_host': False,
                    'use_cookie': False,
                    'use_post': False,
                    'return_data': True
                })
            except:
                printDBG('Host listsItems query error')
                printDBG('Host listsItems query error url:' + url)
                return valTab
            #printDBG( 'Host listsItems data: '+data )
            parse = re.search('Wersje:(.*?)Kopie:', data, re.S)
            if not parse: return []
            phMovies = re.findall('<a href="(.+?)">(.+?)<', parse.group(1),
                                  re.S)
            if phMovies:
                phImage = url.replace(
                    self.MAIN_URL + '/serial,',
                    'http://static.scs.pl/static/serials/').replace(
                        '.html', '.jpg')
                printDBG('Host listsItems phImage: ' + phImage)
                for (phUrl, phWersja) in phMovies:
                    printDBG('Host listsItems phUrl: ' + phUrl)
                    printDBG('Host listsItems phWersja: ' + phWersja)
                    valTab.append(
                        CDisplayListItem(phWersja, phWersja,
                                         CDisplayListItem.TYPE_CATEGORY,
                                         [self.MAIN_URL + '/' + phUrl],
                                         'seriale-odcinki-kopie', phImage,
                                         None))
            printDBG('Host listsItems end')
            return valTab
        if 'seriale-odcinki-kopie' == name:
            printDBG('Host listsItems begin name=' + name)
            try:
                data = self.cm.getURLRequestData({
                    'url': url,
                    'use_host': False,
                    'use_cookie': False,
                    'use_post': False,
                    'return_data': True
                })
            except:
                printDBG('Host listsItems query error')
                printDBG('Host listsItems query error url:' + url)
                return valTab
            #printDBG( 'Host listsItems data: '+data )
            parse = re.search('class="mirrors"(.*?)class="switch"', data, re.S)
            if not parse: return []
            phMovies = re.findall(
                '= "(.+?)"; ccc.+?;.+?"(.+?)";.+?"(.+?)";.+?"(.+?)";',
                parse.group(1), re.S)
            if phMovies:
                for (phUrl, phTime, phUser, phComment) in phMovies:
                    printDBG('Host listsItems phUrl: ' + phUrl)
                    printDBG('Host listsItems phTime: ' + phTime)
                    printDBG('Host listsItems phUser: '******' ' + phUser,
                            phTime + ' ' + phUser + ' ' + phComment,
                            CDisplayListItem.TYPE_VIDEO,
                            [CUrlItem('', phUrl, 1)], 0, '', None))
            printDBG('Host listsItems end')
            return valTab

        return valTab

    def getResolvedURL(self, url):
        printDBG('Host getResolvedURL begin')
        printDBG('Host getResolvedURL url: ' + url)
        postdata = {'f': url}
        if self.PREMIUM:
            query_data = {
                'url': 'http://scs.pl/getVideo.html',
                'use_host': True,
                'host': self.HOST,
                'use_cookie': True,
                'save_cookie': False,
                'load_cookie': True,
                'cookiefile': self.COOKIEFILE,
                'use_post': True,
                'return_data': True
            }
        else:
            query_data = {
                'url': 'http://scs.pl/getVideo.html',
                'use_host': False,
                'use_cookie': False,
                'use_post': True,
                'return_data': True
            }
        try:
            data = self.cm.getURLRequestData(query_data, postdata)
        except:
            printDBG('Host getResolvedURL query error premium')
            printDBG('Host getResolvedURL query error premium url: ' + url)
            return ''
        #printDBG( 'Host getResolvedURL premium data: ' +data)
        match = re.compile("url: '(.+?)',").findall(data)
        if len(match) > 0:
            linkVideo = match[0]
            printDBG('Host getResolvedURL linkVideo: ' + linkVideo)
            printDBG('Host getResolvedURL end premium')
            return linkVideo
        printDBG('Host getResolvedURL end')
        return ''
示例#39
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({'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 getVideoLink(self, cItem):
        printDBG("EdemTvApi.getVideoLink")
        
        sts, data = self.cm.getPage(cItem['url'], self.http_params)
        if not sts: return []
        
        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:
            urlsTab = getDirectM3U8Playlist(hlsUrl)
        if rmpUrl.startswith('rtmp'):
            urlsTab.append({'name':'rtmp', 'url':rmpUrl + ' live=1'})
        return urlsTab
示例#40
0
class SatLiveApi:
    MAINURL      = 'http://web-live.tv/'
    LIST_URL     = MAINURL + 'transmissions/transmission/index'
    SWF_URL      = MAINURL + 'themes/default/swf/jwplayer.flash.swf'
    LOGIN_URL    = MAINURL + 'site/site/login'
    HTTP_HEADER  = { 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:12.0) Gecko/20100101 Firefox/12.0', 'Referer': MAINURL }

    def __init__(self):
        self.COOKIE_FILE = GetCookieDir('satlivetv.cookie')
        self.cm = common()
        self.sessionEx = MainSessionWrapper()
        self.loggedIn  = True
        self.http_params = {}
        
        #self._reInit()
        #self.channelsList = []

    def getChannelsList(self):
        printDBG("SatLiveApi.getChannelsList")
        
        # login
        premium  = config.plugins.iptvplayer.satlivetv_premium.value
        login    = config.plugins.iptvplayer.satlivetv_login.value
        password = config.plugins.iptvplayer.satlivetv_password.value
        if premium:        
            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 )

        # get channels
        channelsList = []
        sts, data = self.cm.getPage(SatLiveApi.LIST_URL, self.http_params)
        if not sts:
            return []
        
        data = self.cm.ph.getDataBeetwenMarkers(data, '<div class="tab-pane active" id="live">', '<div class="tab-pane" id="all">', False)[1]
        data = data.split('</li>')
        for item in data:
            tmp = self.cm.ph.getSearchGroups(item, '<h4><a href="([^"]+?)">([^<]+?)</a></h4>', 2)
            if '' != tmp[0]:
                params = {}
                params['url']   = SatLiveApi.MAINURL + tmp[0]
                params['title'] = tmp[1]
                icon = self.cm.ph.getSearchGroups(item, '<img class="" src="([^"]+?)"')[0]
                if '' != icon:
                    params['icon']  = SatLiveApi.MAINURL + icon
                params['desc']      = self.cm.ph.removeDoubles(clean_html(item.replace('>', '> ')).replace('\t', ' '), ' ')
                channelsList.append(params)
        if True:
                                                                                                                                                                                                                                                                                        num = 1
                                                                                                                                                                                                                                                                                        m = 'eyI1NzkiOiAiVFZQIDEiLCAiNjA0IjogIlBvbHNhdCBTcG9ydCIsICI2MTgiOiAiUG9sc2F0IFNwb3J0IiwgIjU3MiI6ICJUQ00iLCAiNjA2IjogIlBvbHNhdCBTcG9ydCBFeHRyYSIsICI2MDAiOiAiQ2FuYWwrIFNwb3J0IiwgIjYwMiI6ICJQb2xzYXQiLCAiNDY5IjogIkhCTyBbSERdIiwgIjEyMCI6ICJBWE4gV2hpdGUiLCAiOTgiOiAiTmF0R2VvIiwgIjEyMiI6ICJOYXRHZW8gV2lsZCIsICI5MyI6ICJIQk8iLCAiOTQiOiAiSEJPIDIiLCAiOTciOiAiQ2luZW1heCAyIiwgIjU5MSI6ICJDYW5hbCsgW0hEXSIsICI1OTAiOiAiTWluaU1pbmkiLCAiNTkzIjogIkNhbmFsKyBGaWxtIiwgIjU5MiI6ICJDYW5hbCsiLCAiNjAxIjogIlBvbHNhdCBbSERdIiwgIjU5NCI6ICJBbGVLaW5vKyIsICI1OTciOiAiQ2FuYWwrIFNlcmlhbGUiLCAiNTk2IjogIlRlbGVUb29uIiwgIjU5OSI6ICJDYW5hbCsgRmFtaWx5IiwgIjU5OCI6ICJDYW5hbCsiLCAiMTE0IjogIkRpc2NvdmVyeSBTY2llbmNlIiwgIjExNyI6ICJEaXNuZXkgSnVuaW9yIiwgIjExMCI6ICJEaXNuZXkgWEQiLCAiMTEyIjogIkZpbG1ib3giLCAiMTE5IjogIkZPWCIsICIxMTgiOiAiVHJhdmVsIENoYW5uZWwiLCAiNTI4IjogIlR1cmJvIFh0cmEiLCAiNTg3IjogIm5TcG9ydCIsICI1ODQiOiAiVFZQIFNlcmlhbGUiLCAiNTg1IjogIlRWUCBTcG9ydCIsICI1ODIiOiAiVFZQIDIgW0hEXSIsICI1ODMiOiAiVFZQIEluZm8iLCAiNTgwIjogIlRWUCAxIFtIRF0iLCAiNTgxIjogIlRWUCAyIiwgIjYxMiI6ICJVbmtub3duIiwgIjYxMyI6ICJVbmtub3duIiwgIjYxMCI6ICJVbmtub3duIiwgIjYxMSI6ICJUVk4gMjQiLCAiNTg4IjogIm5TcG9ydCBbSERdIiwgIjU4OSI6ICJDYW5hbCsgU3BvcnQgW0hEXSIsICIxMDgiOiAiRGlzY292ZXJ5IGxpZmUiLCAiMTA5IjogIkFYTiIsICIxMDIiOiAiRXVyb3Nwb3J0IDIiLCAiMTAxIjogIkV1cm9zcG9ydCIsICIxMDYiOiAiSEJPIENvbWVkeSIsICIxMDciOiAiS2lubyBQb2xza2EiLCAiMTA0IjogIlRMQyIsICI0NzAiOiAiRGlzY292ZXJ5IFtIRF0iLCAiNDcxIjogIk5hdEdlbyBbSERdIiwgIjQ3NiI6ICJCQkMgZWFydGgiLCAiNDc0IjogIkRpc2NvdmVyeSIsICI0NzgiOiAiVmlhc2F0IE5hdHVyZSIsICI0NzkiOiAiVmlhc2F0IEhpc3RvcnkiLCAiNjE2IjogIlBvbHNhdCBIRCIsICI2MTciOiAiUG9sc2F0IiwgIjYxOSI6ICJQb2xzYXQgU3BvcnQgRXh0cmEifQ=='
                                                                                                                                                                                                                                                                                        try: m = byteify(json.loads(base64.b64decode(m)))
                                                                                                                                                                                                                                                                                        except: m = {}
                                                                                                                                                                                                                                                                                        for a in base64.b64decode('OTMsOTQsOTcsOTgsMTAxLDEwMiwxMDQsMTA2LDEwOSwxMTAsMTEyLDExNCwxMTcsMTE4LDExOSwxMjAsMTIyLDQ2OSw0NzAsNDcxLDQ3NCw0NzYsNDc4LDQ3OSw1MjgsNTcxLDU3Miw1NzksNTgwLDU4MSw1ODIsNTgzLDU4NCw1ODUsNTg3LDU4OCw1ODksNTkwLDU5MSw1OTIsNTkzLDU5NCw1OTUsNTk2LDU5Nyw1OTgsNTk5LDYwMCw2MTAsNjExLDYxMiw2MTMsNjE2LDYxNyw2MTgsNjE5').split(','):
                                                                                                                                                                                                                                                                                            channelsList.append({'title':'Test %s' % m.get(a, ''), 'url':SatLiveApi.MAINURL+'/id/%s/' % a, 'icon':'http://web-live.tv/uploads/transmissions/Transmission/live/%s.jpg?%s' % (a, time.time()), 'desc':''})
                                                                                                                                                                                                                                                                                            num += 1
        return channelsList
    
    def getVideoLink(self, url):
        printDBG("SatLiveApi.getVideoLink")
        id = self.cm.ph.getSearchGroups(url+"/", 'id/([0-9]+?)/')[0]
        sts, data = self.cm.getPage(SatLiveApi.MAINURL + 'ge/' + id, self.http_params)
        if not sts:
            return ''
        base = self.cm.ph.getSearchGroups(data, 'base="([^"]+?)"')[0]
        src = self.cm.ph.getSearchGroups(data, 'src="([^"]+?)"')[0]
        if base.startswith('rtmp'):
            return base + '/' + src + ' swfUrl=%s live=1' % SatLiveApi.SWF_URL
        return ''

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

        
        post_data = {'LoginForm[email]' : login, 'LoginForm[password]' : password, 'ajax' : 'fast-login-form', 'undefined' : '' }
        params    = {'header' : HTTP_HEADER, 'cookiefile' : self.COOKIE_FILE, 'save_cookie' : True}
        sts, data = self.cm.getPage( SatLiveApi.LOGIN_URL, params, post_data)
        if sts:
            if os_path.isfile(self.COOKIE_FILE):
                printDBG(data)
                if '[]' == data:
                    printDBG('SatLiveApi.doLogin login as [%s]' % login)
                    logged = True
                else:
                    printDBG('SatLiveApi.doLogin login failed - wrong user or password?')
            else:
                printDBG('SatLiveApi.doLogin there is no cookie file after login')
        return logged
 def __init__(self):
     self.COOKIE_FILE = GetCookieDir('satlivetv.cookie')
     self.cm = common()
     self.sessionEx = MainSessionWrapper()
     self.loggedIn  = True
     self.http_params = {}
示例#42
0
class UstvnowApi:
    MAIN_URL = 'http://m.ustvnow.com/'
    LOG_URL  = MAIN_URL + 'iphone/1/live/login'
    LIVE_URL = MAIN_URL + 'iphone/1/live/playingnow'
    HTTP_HEADER  = { 'User-Agent': 'Mozilla/5.0', 'Referer': MAIN_URL }

    def __init__(self):
        self.cm = common()
        self.up = urlparser()
        self.sessionEx = MainSessionWrapper()
        self.cookiePath = GetCookieDir('ustvnow.cookie')
        self.token = ''
        
        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)
                
        except:
            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)
            if self.token == '':
                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']
                    prgsvcidMap[params['prgsvcid']] = len(channelsTab)
                    channelsTab.append(params)
                    break
                    
        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']]
                            channelsTab[idx]['desc'] += '[/br][/br] [%s %s][/br]%s[/br]%s[/br]%s[/br]%s' % (item.get('event_date', ''), item.get('event_time', ''), item.get('title', ''), item.get('synopsis', ''), item.get('description', ''), item.get('episode_title', ''))
                except:
                    printExc()
            
        return channelsTab
        
    def doLogin(self, login, password):
        printDBG("UstvnowApi.doLogin")
        token = ''
        post_data = {'username':login, 'password':password, 'device':'iphone'}
        sts, data = self.cm.getPage(self.LOG_URL, self.defParams, post_data)
        if sts:
            token = self.cm.getCookieItem(self.cookiePath, 'token')
        return token
        
    def getVideoLink(self, cItem):
        printDBG("UstvnowApi.getVideoLink")
        
        sts, data = self.cm.getPage(cItem['priv_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]
        urlsTab = []
        tmp = getDirectM3U8Playlist(strwithmeta(url, {'User-Agent':self.HTTP_HEADER['User-Agent']}), cookieParams = {'cookiefile': self.cookiePath, 'use_cookie': True, 'load_cookie':True, 'save_cookie':True})
        hdntl = self.cm.getCookieItem(self.cookiePath, 'hdntl')
        
        for item in tmp:
            item['url'] = urlparser.decorateUrl(item['url'], {'User-Agent':self.HTTP_HEADER['User-Agent'], 'Cookie':"hdntl=%s" % urllib.unquote(hdntl)})
            urlsTab.append(item)
        
        return urlsTab
示例#43
0
class Sport365LiveApi:
    MAIN_URL = 'http://www.sport365.live/'
    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',
        'Accept-Encoding': 'gzip, deflate',
        'Referer': MAIN_URL
    }
    CACHE_AES_PASSWORD = ''

    def __init__(self):
        self.COOKIE_FILE = GetCookieDir('sport365live.cookie')
        self.sessionEx = MainSessionWrapper()
        self.cm = common()
        self.up = urlparser()
        self.http_params = {
            'header': dict(self.HTTP_HEADER),
            'use_cookie': True,
            'save_cookie': True,
            'load_cookie': True,
            'cookiefile': self.COOKIE_FILE
        }
        self.needRefreshAdvert = True

    def getPage(self, url, params={}, post_data=None):
        sts, data = self.cm.getPage(url, params, post_data)
        if sts:
            #printDBG("---")
            #printDBG("url: %s" % url)
            #printDBG(data)
            #printDBG("---")
            return sts, data

    def getFullUrl(self, url):
        if url.startswith('http'):
            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 cryptoJS_AES_decrypt(self, encrypted, password, salt):
        printDBG("cryptoJS_AES_decrypt")

        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 decryptUrl(self, linkData, aes):
        playerUrl = ''
        if linkData:
            try:
                linkData = json_loads(base64.b64decode(linkData))
                ciphertext = base64.b64decode(linkData['ct'])
                iv = a2b_hex(linkData['iv'])
                salt = a2b_hex(linkData['s'])

                playerUrl = json_loads(
                    self.cryptoJS_AES_decrypt(ciphertext, aes, salt))
                printDBG("player Url -->  %s " % str(playerUrl))
            except Exception:
                printExc()

        return playerUrl

    def getMarketCookie(self, url, referer, num=1):
        try:
            id = url.split('.')[-2]
        except Exception:
            printExc()
            id = '403'

        printDBG(">> id[%s]\n" % id)
        xz = str(int(time() * 1000)) + id + str(int(
            random.random() * 1000)) + str(
                2 * int(random.random() * 4)) + str(num)
        xz = base64.b64encode(xz)
        return 'MarketGidStorage=%s; ' % urllib.quote(
            '{"0":{"svspr":"%s","svsds":%s,"TejndEEDj":"%s"},"C%s":{"page":1,"time":%s}}'
            % (referer, num, xz, id, int(time() * 100)))

    def refreshAdvert(self):
        if not self.needRefreshAdvert: return

        self.sessionEx.open(
            MessageBox,
            _('Please remember to visit http://www.sport365.live/ and watch a few advertisements.\nThis will fix problem, if your playback is constantly interrupted.'
              ),
            type=MessageBox.TYPE_INFO,
            timeout=10)
        self.needRefreshAdvert = False

        COOKIE_FILE = GetCookieDir('sport365live2.cookie')
        params = dict(self.http_params)
        params['cookiefile'] = COOKIE_FILE
        params['header'] = dict(params['header'])

        sts, data = self.getPage(self.MAIN_URL, params)
        if not sts: return

        baseUrl = self.cm.meta['url']

        sessionCookie = self.cm.getCookieHeader(COOKIE_FILE)
        params['header']['Referer'] = baseUrl

        awrapperUrls = re.compile(
            '''['"]([^"^']*?/awrapper/[^'^"]*?)["']''').findall(data)

        D = datetime.now()
        timeMarker = '{0}{1}{2}{3}'.format(D.year - 1900, D.month - 1, D.day,
                                           D.hour)
        jscUrl = self.cm.ph.getSearchGroups(
            data, '''['"]([^'^"]*?jsc\.mgid[^'^"]*?)['"]''')[0]
        printDBG(">> [%s]" % jscUrl)
        if jscUrl.endswith('t='): jscUrl += timeMarker
        adUrl = self.cm.ph.getSearchGroups(
            data, '''['"]([^'^"]*?\.adshell\.[^'^"]*?)['"]''')[0]

        sts, data = self.getPage(self.getFullUrl(adUrl), params)
        if sts:
            adUrl = self.cm.ph.getSearchGroups(
                data, '''['"]([^'^"]*?\.adshell\.[^'^"]*?)['"]''')[0]

        sts, data = self.getPage(self.getFullUrl(jscUrl), params)
        marketCookie = self.getMarketCookie(jscUrl, baseUrl)
        params['use_cookie'] = False
        params['header']['Cookie'] = marketCookie
        sts, data = self.getPage(self.getFullUrl(adUrl), params)

        return

        for awrapperUrl in awrapperUrls:
            awrapperUrl = self.getFullUrl(awrapperUrl)
            params['header']['Referer'] = baseUrl
            params['header']['Cookie'] = sessionCookie + marketCookie
            sts, data = self.getPage(awrapperUrl, params)
            if not sts: continue

            adUrl = self.cm.ph.getSearchGroups(
                data, '''['"]([^'^"]*?\.adshell\.[^'^"]*?)['"]''')[0]
            params['header']['Referer'] = awrapperUrl
            params['header']['Cookie'] = marketCookie

            sts, data = self.getPage(self.getFullUrl(adUrl), params)
            if not sts: continue

            jscUrl = self.cm.ph.getSearchGroups(
                data, '''['"]([^'^"]*?jsc\.mgid[^'^"]*?)['"]''')[0]
            if jscUrl.endswith('t='): jscUrl += timeMarker
            if jscUrl != '':
                sts, tmp = self.getPage(self.getFullUrl(jscUrl), params)
                if sts:
                    params['header']['Cookie'] = self.getMarketCookie(
                        jscUrl, awrapperUrl)
            adUrls = re.compile(
                '''['"]([^'^"]*?bannerid[^'^"]*?)['"]''').findall(data)
            for adUrl in adUrls:
                adUrl = adUrl.replace('&amp;', '&')
                sts, tmp = self.getPage(self.getFullUrl(adUrl), params)

        return

    def getMainCategories(self, cItem):
        printDBG("Sport365LiveApi.getMainCategories")
        channelsTab = []
        dt = datetime.now() - datetime.utcnow()
        OFFSET = (dt.microseconds +
                  (dt.seconds + dt.days * 24 * 3600) * 10**6) / 10**6
        OFFSET /= 60
        if OFFSET % 10 == 9:
            OFFSET += 1
        url = self.getFullUrl('en/events/-/1/-/-/%s' % (OFFSET))
        sts, data = self.getPage(self.MAIN_URL, self.http_params)
        sts, data = self.getPage(url, self.http_params)
        if not sts: return []

        date = ''
        data = self.cm.ph.getDataBeetwenMarkers(data, '<table', '</table>')[1]
        data = self.cm.ph.getAllItemsBeetwenMarkers(data, '<tr', '</tr>')
        for item in data:
            if '/types/' not in item:
                tmp = self.cm.ph.getSearchGroups(
                    item, '''>([0-9]{2}\.[0-9]{2}\.[0-9]{4})<''')[0]
                if tmp != '': date = tmp
            else:
                if '/types/dot-green-big.png' in item:
                    title = '[live] '
                else:
                    title = ''
                title += self.cleanHtmlStr(item)
                desc = self.cm.ph.getSearchGroups(
                    item, '''alt=['"]([^'^"]+?)['"]''')[0]
                desc = date + ' ' + self.cleanHtmlStr(desc)
                linksData = []
                tmp = self.cm.ph.getSearchGroups(
                    item, '''onClick=[^(]*?\(([^)]+?)\)''')[0].split(',')
                for t in tmp:
                    linksData.append(t.replace('"', '').strip())
                params = dict(cItem)
                params.update({
                    'type': 'category',
                    'priv_cat': 'streams_links',
                    'links_data': linksData,
                    'title': title,
                    'desc': desc
                })
                printDBG(str(params))
                channelsTab.append(params)

        return channelsTab

    def getStreamsLinks(self, cItem):
        printDBG("Sport365LiveApi.getStreamsLinks")
        channelsTab = []

        linksData = cItem.get('links_data', [])
        if len(linksData) < 4 or not linksData[0].startswith('event_'):
            return []

        eventId = linksData[0].replace('event_', '')
        url = self.getFullUrl('en/links/{0}/{1}'.format(
            eventId, linksData[-1]))
        sts, data = self.getPage(url, self.http_params)
        if not sts: return []

        desc = self.cleanHtmlStr(
            self.cm.ph.getDataBeetwenMarkers(
                data, '<table', '</table>')[1]) + '[/br]' + cItem.get(
                    'desc', '')
        data = self.cm.ph.getAllItemsBeetwenMarkers(data, '<tr', '</tr>')
        for item in data:
            sourceTitle = self.cleanHtmlStr(item.split('<span')[0])
            links = self.cm.ph.getAllItemsBeetwenMarkers(
                item, '<span ', '</span>')
            for link in links:
                linkTitle = self.cleanHtmlStr(link)
                if '{' in linkTitle: continue
                linkData = self.cm.ph.getSearchGroups(
                    link,
                    '''onClick=[^(]*?\(([^)]+?)\)''')[0].split(',')[0].replace(
                        '"', '').replace("'", '').strip()
                if linkData != '':
                    params = dict(cItem)
                    params.update({
                        'type': 'video',
                        'link_data': linkData,
                        'event_id': eventId,
                        'desc': desc,
                        'title': sourceTitle + ' ' + linkTitle
                    })
                    printDBG(str(params))
                    channelsTab.append(params)

        return channelsTab

    def getChannelsList(self, cItem):
        printDBG("Sport365LiveApi.getChannelsList")
        self.refreshAdvert()

        category = cItem.get('priv_cat', None)
        if None == category:
            return self.getMainCategories(cItem)
        elif 'streams_links' == category:
            return self.getStreamsLinks(cItem)

        return []

    def _getAesPassword(self, cItem, forceRefresh=False):
        if Sport365LiveApi.CACHE_AES_PASSWORD != '' and not forceRefresh:
            return Sport365LiveApi.CACHE_AES_PASSWORD

        sts, data = self.getPage(
            self.getFullUrl('en/home/' + cItem['event_id']), self.http_params)
        if not sts: return []

        jsData = ''
        tmp = self.cm.ph.getAllItemsBeetwenMarkers(data, '<script',
                                                   '</script>')
        for item in tmp:
            if 'Contact' in item:
                item = self.cm.ph.getDataBeetwenReMarkers(
                    item, re.compile('<script[^>]+?>'),
                    re.compile('</script>'), False)[1]
                if 'Contact' in item:
                    jsData = 'try{ %s; } catch(e){ ; }\n' % (item)
                    break

        jsData2 = ''
        aes = ''
        data = re.compile(
            '''src=['"](http[^"^']*?/js/[0-9a-fA-F]{32}\.js[^'^"]*?)["']'''
        ).findall(data)[::-1]
        for commonUrl in data:
            sts, tmpData = self.getPage(commonUrl, self.http_params)
            if not sts: continue
            if tmpData.startswith(';eval('):
                try:
                    jscode = base64.b64decode(
                        '''dmFyIGRvY3VtZW50ID0ge307DQp2YXIgd2luZG93ID0gdGhpczsNCmRvY3VtZW50LndyaXRlID0gZnVuY3Rpb24oKXt9Ow0Kd2luZG93LmF0b2IgPSBmdW5jdGlvbigpe3JldHVybiAiIjt9Ow0KDQpmdW5jdGlvbiBkZWNyeXB0KCl7DQogICAgdmFyIHRleHQgPSBKU09OLnN0cmluZ2lmeSh7YWVzOmFyZ3VtZW50c1sxXX0pOw0KICAgIHByaW50KHRleHQpOw0KICAgIHJldHVybiAiIjsNCn0NCg0KdmFyIENyeXB0b0pTID0ge307DQpDcnlwdG9KUy5BRVMgPSB7fTsNCkNyeXB0b0pTLkFFUy5kZWNyeXB0ID0gZGVjcnlwdDsNCkNyeXB0b0pTLmVuYyA9IHt9Ow0KQ3J5cHRvSlMuZW5jLlV0ZjggPSAidXRmLTgiOw0K'''
                    )
                    jscode = '%s %s %s' % (jscode, tmpData, jsData)
                    ret = js_execute(jscode)
                    if ret['sts'] and 0 == ret['code']:
                        decoded = ret['data'].strip()
                        aes = json_loads(decoded)['aes']
                except Exception:
                    printExc()
                if aes != '':
                    break

        if aes != '':
            Sport365LiveApi.CACHE_AES_PASSWORD = aes
        return aes

    def getAesPassword(self, cItem, forceRefresh=False):
        if Sport365LiveApi.CACHE_AES_PASSWORD != '' and not forceRefresh:
            return Sport365LiveApi.CACHE_AES_PASSWORD

        sts, data = self.getPage(
            self.getFullUrl('en/home/' + cItem['event_id']), self.http_params)
        if not sts: return []

        aes = ''
        data = re.compile(
            '''src=['"](http[^"^']*?/js/[0-9a-fA-F]{32}\.js[^'^"]*?)["']'''
        ).findall(data)[::-1]
        num = 0
        deObfuscatedData = ''
        aes_password = []

        for commonUrl in data:
            num += 1
            printDBG("common url n. %s : %s " % (str(num), commonUrl))

            sts, tmpData = self.getPage(commonUrl, self.http_params)
            if not sts:
                continue
            aes = ''
            try:
                while ('eval' in tmpData) and (not aes):
                    tmp = tmpData.split('eval(')
                    if len(tmp): del tmp[0]
                    tmpData = ''
                    for item in tmp:
                        for decFun in [
                                VIDEOWEED_decryptPlayerParams,
                                VIDEOWEED_decryptPlayerParams2,
                                SAWLIVETV_decryptPlayerParams
                        ]:
                            if not (item.startswith('function(w,i,s,e){for')
                                    and decFun
                                    == VIDEOWEED_decryptPlayerParams):
                                tmpData = unpackJSPlayerParams(
                                    'eval(' + item, decFun, 0)
                                if '' != tmpData:
                                    printDBG(
                                        '**********************************')
                                    printDBG(tmpData)
                                    printDBG(
                                        '**********************************')
                                    break

                        aes = self.cm.ph.getSearchGroups(
                            tmpData, 'aes_key="([^"]+?)"')[0]
                        if '' == aes:
                            aes = self.cm.ph.getSearchGroups(
                                tmpData, 'aes\(\)\{return "([^"]+?)"')[0]

                        if aes == '':
                            funname = self.cm.ph.getSearchGroups(
                                tmpData,
                                'CryptoJS\.AES\.decrypt\([^\,]+?\,([^\,]+?)\,'
                            )[0].strip()
                            if funname != '':
                                printDBG("ZZZZZZZZZZZZZ")
                                printDBG("FUN NAME: [%s]" % funname)
                                printDBG("ZZZZZZZZZZZZZ")
                                tmp = self.cm.ph.getDataBeetwenMarkers(
                                    tmpData, 'function %s' % funname, '}')[1]
                                try:
                                    aes = self.cm.ph.getSearchGroups(
                                        tmp, '"([^"]+?)"')[0].encode('utf-8')
                                except Exception:
                                    printExc()

                aes = aes.encode('utf-8')
            except Exception:
                printExc()
                aes = ''

            if aes:
                printDBG("Added password %s" % aes)
                aes_password.append(aes)

        if aes_password:
            Sport365LiveApi.CACHE_AES_PASSWORD = aes_password
        return aes_password

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

        if Sport365LiveApi.CACHE_AES_PASSWORD != '':
            tries = 2
        else:
            tries = 1

        urlsTab = []
        for checkIdx in range(tries):
            if checkIdx > 0:
                aes_password = self.getAesPassword(cItem, True)
            else:
                aes_password = self.getAesPassword(cItem)

            if not aes_password:
                return []

            printDBG("aes -----> %s" % str(aes_password))
            for aes in aes_password:
                try:
                    printDBG("link_data -----> " + str(cItem['link_data']))

                    playerUrl = self.decryptUrl(cItem['link_data'], aes)

                    if not playerUrl.startswith('http'):
                        continue

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

                    links = re.compile(
                        '(http://www.[^\.]+.pw/(?!&#)[^"]+)', re.IGNORECASE +
                        re.DOTALL + re.MULTILINE + re.UNICODE).findall(data)
                    link = [x for x in links if '&#' in x]
                    if link:
                        link = re.sub(r'&#(\d+);',
                                      lambda x: chr(int(x.group(1))), link[0])
                        printDBG("Found *.pw link ------> %s " % link)

                        h = self.http_params
                        h['header']['Referer'] = playerUrl
                        sts, data = self.getPage(link, h)

                        if sts:
                            #printDBG("*****************")
                            #printDBG(data)
                            #printDBG("*****************")

                            # search form data in page
                            action = re.compile(
                                '[\'"]action[\'"][,\s]*[\'"](http.*?)[\'"]'
                            ).findall(data)

                            r = re.compile(
                                '.*?name="r"\s*value=["\']([^"\']+)["\']'
                            ).findall(data)
                            d = re.compile(
                                '.*?name="d"\s*value=["\']([^"\']+)["\']'
                            ).findall(data)
                            f = re.compile(
                                '.*?name="f"\s*value=["\']([^"\']+)["\']'
                            ).findall(data)

                            srcs = re.compile('src=[\'"](.*?)[\'"]').findall(
                                data)

                            if f and r and d and action:
                                postData = {'r': r[0], 'd': d[0], 'f': f[0]}
                                h['header']['Referer'] = link
                                sts, data = self.getPage(
                                    action[0], h, postData)
                                if sts:
                                    #printDBG("*****************")
                                    #printDBG(data)
                                    #printDBG("*****************")

                                    try:
                                        #######ads banners#########
                                        # simulate ads viewing
                                        bheaders = h
                                        bheaders['header']['Referer'] = action[
                                            0]
                                        banner = re.findall(
                                            r'<script\s*src=[\'"](.+?)[\'"]',
                                            data)[-1]
                                        sts, bsrc = self.getPage(
                                            banner, bheaders)
                                        banner = re.findall(
                                            r"url:'([^']+)", bsrc)[0]
                                        sts, bsrc = self.getPage(
                                            banner, bheaders)
                                        bheaders['header']['Referer'] = banner
                                        banner = re.findall(
                                            r'window.location.replace\("([^"]+)"\);\s*}\)<\/script><div',
                                            bsrc)[0]
                                        banner = urllib.quote(
                                            banner, ':/()!@#$%^&;><?')
                                        sts, bsrc = self.getPage(
                                            banner, bheaders)
                                        ###########################
                                    except BaseException:
                                        pass

                                    link2 = re.compile(
                                        '\([\'"][^"\']+[\'"], [\'"][^"\']+[\'"], [\'"]([^"\']+)[\'"], 1\)'
                                    ).findall(data)
                                    if link2:
                                        printDBG(link2[0])
                                        playerUrl = self.decryptUrl(
                                            link2[0],
                                            aes).replace("/i", "/master.m3u8")
                                        printDBG(
                                            "Final player Url ----------->  %s "
                                            % str(playerUrl))

                                        playerUrl = strwithmeta(
                                            playerUrl, {
                                                'User-Agent':
                                                h['header']['User-Agent'],
                                                'Referer':
                                                action[0]
                                            })

                                        COOKIE_FILE_M3U8 = GetCookieDir(
                                            'sport365live.cookie')
                                        params = {
                                            'cookiefile': COOKIE_FILE_M3U8,
                                            'use_cookie': True,
                                            'load_cookie': False,
                                            'save_cookie': True
                                        }

                                        urlsTab.extend(
                                            getDirectM3U8Playlist(
                                                playerUrl,
                                                checkExt=False,
                                                variantCheck=True,
                                                cookieParams=params,
                                                checkContent=True,
                                                sortWithMaxBitrate=99999999))

                    else:
                        # old system
                        playerUrl = self.cm.ph.getSearchGroups(
                            data,
                            '''location\.replace\(\s*?['"]([^'^"]+?)['"]''', 1,
                            True)[0]
                        if playerUrl:
                            printDBG("player Url 2 ------> %s " % playerUrl)

                        else:
                            data = self.cm.ph.getDataBeetwenMarkers(
                                data, 'document.write(', '(')[1]
                            playerUrl = self.cleanHtmlStr(
                                self.cm.ph.getSearchGroups(
                                    data,
                                    '''<iframe[^>]+?src=['"](http[^"^']+?)['"]''',
                                    1, True)[0])

                        urlsTab = self.up.getVideoLinkExt(
                            strwithmeta(playerUrl, {'aes_key': aes}))
                        if len(urlsTab):
                            break

                except Exception:
                    printExc()

        return urlsTab
示例#44
0
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
示例#45
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 = 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 = 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 = json_loads(data)
            return data['globalparams']['passkey']
        except Exception:
            return ''

    def getVideoLink(self, cItem):
        printDBG("UstvnowApi.getVideoLink %s" % cItem)
        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 = 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']

                    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(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']

            item['url'] = urlparser.decorateUrl(
                vidUrl, {
                    'User-Agent': self.HTTP_HEADER['User-Agent'],
                    'Cookie': cookieValue
                })
            urlsTab.append(item)

        return urlsTab
class Host:
    currList = []
    MAIN_URL = ''
    PREMIUM = False
    konto = ''
    HOST = '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'

    def __init__(self):
        printDBG( 'Host __init__ begin' )
        self.exSession = MainSessionWrapper()
        self.COOKIEFILE = GetCookieDir('zalukajtv.cookie')
        self.cm = common()
        self.up = urlparser()
        self.history = CSearchHistoryHelper('wspolne')
        self.currList = []
        printDBG( 'Host __init__ end' )
        
    def setCurrList(self, list):
        printDBG( 'Host setCurrList begin' )
        self.currList = list
        printDBG( 'Host setCurrList end' )
        return 
        
    def fullUrl(self, phUrl):
        if not phUrl.startswith('http'):
            if '/' == phUrl[0]:
                phUrl = '/' + phUrl
            phUrl = self.MAIN_URL + phUrl
        return phUrl

    def getInitList(self):
        printDBG( 'Host getInitList begin' )
        ####################################
        # logowanie
        ####################################
        if config.plugins.iptvplayer.zalukajtvPREMIUM.value:
           url = 'http://zalukaj.tv/account.php'
           try: data = self.cm.getURLRequestData({ 'url': url, 'use_host': True, 'host': self.HOST, 'use_cookie': True, 'save_cookie': True, 'load_cookie': False, 'cookiefile': self.COOKIEFILE, 'use_post': True, 'return_data': True },{'login': config.plugins.iptvplayer.zalukajtv_login.value, 'password': config.plugins.iptvplayer.zalukajtv_password.value})
           except:
              printDBG( 'Host getInitList query error' )
              printDBG( 'Host getInitList query error url:'+url )
              printDBG( 'Host getInitList query error: Uzywam Player z limitami')
              data = None
           if data:
              self.PREMIUM = True
              printDBG( 'Host getInitList: chyba zalogowano do premium...' )
              url = 'http://zalukaj.tv/libs/ajax/login.php?login=1'
              try: 
                 data = self.cm.getURLRequestData({ 'url': url, 'use_host': True, 'host': self.HOST, 'use_cookie': True, 'save_cookie': False, 'load_cookie': True, 'cookiefile': self.COOKIEFILE, 'use_post': False, 'return_data': True })
                 printDBG( 'Host listsItems data: '+data )
                 parse = re.search('Typ Konta:.*?>(.*?)<.*?>(.*?)<', data, re.S)
                 if parse:
                    self.konto = '- Typ Konta: '+parse.group(1)+parse.group(2)
                 else: 
                    self.konto = ''
              except:
                 printDBG( 'Host getInitList: blad pobrania danych o koncie premium' )
                 
           if '' == self.konto:
              self.exSession.open(MessageBox, 'Problem z zalogowaniem użytkownika \n"%s" jako VIP.' % config.plugins.iptvplayer.zalukajtv_login.value, type = MessageBox.TYPE_INFO, timeout = 10)

              #if 'Wyloguj' in data:
              #   self.PREMIUM = True 
              #   printDBG('Host getInitList:' + config.plugins.iptvplayer.zalukajtv_login.value + ', Zostales poprawnie zalogowany')
              #else:
              #   printDBG('Host getInitList: Blad logowania, uzywam Player z limitami')
        ####################################
        self.currList = self.listsItems(-1, '', 'main-menu')
        printDBG( 'Host getInitList end' )
        return self.currList

    def getListForItem(self, Index = 0, refresh = 0, selItem = None):
        printDBG( 'Host getListForItem begin' )
        valTab = []
        if len(self.currList[Index].urlItems) == 0:
           return valTab
        valTab = self.listsItems(Index, self.currList[Index].urlItems[0], self.currList[Index].urlSeparateRequest)
        self.currList = valTab
        printDBG( 'Host getListForItem end' )
        return self.currList

    def getSearchResults(self, pattern, searchType = None):
        printDBG( "Host getSearchResults begin" )
        printDBG( "Host getSearchResults pattern: " +pattern)
        valTab = []
        valTab = self.listsItems(-1, pattern, 'search')
        #valTab = [] #test       
        self.currList = valTab
        printDBG( "Host getSearchResults end" )
        return self.currList

    def listsItems(self, Index, url, name = ''):
        printDBG( 'Host listsItems begin' )
        printDBG( 'Host listsItems url: '+url )
        valTab = []
        if name == 'main-menu':
           printDBG( 'Host listsItems begin name='+name )
           self.MAIN_URL = 'http://zalukaj.tv'
           valTab.append(CDisplayListItem('Filmy '+self.konto,   'http://zalukaj.tv',         CDisplayListItem.TYPE_CATEGORY, ['http://zalukaj.tv/'],          'filmy', '', None)) 
           valTab.append(CDisplayListItem('Seriale', 'http://zalukaj.tv/seriale', CDisplayListItem.TYPE_CATEGORY, ['http://zalukaj.tv/seriale'],   'seriale', '', None)) 
           valTab.append(CDisplayListItem('Szukaj',  'Szukaj filmów',             CDisplayListItem.TYPE_SEARCH,   ['http://szukaj.zalukaj.tv/szukaj'],   'seriale', '', None)) 
           valTab.append(CDisplayListItem('Historia wyszukiwania', 'Historia wyszukiwania', CDisplayListItem.TYPE_CATEGORY, ['http://zalukaj.tv/seriale'],   'history', '', None)) 
           printDBG( 'Host listsItems end' )
           return valTab

        # ########## #
        if 'history' == name:
           printDBG( 'Host listsItems begin name='+name )
           for histItem in self.history.getHistoryList():
               valTab.append(CDisplayListItem(histItem['pattern'], 'Szukaj ', CDisplayListItem.TYPE_CATEGORY, [histItem['pattern'],histItem['type']], 'search', '', None))          
           printDBG( 'Host listsItems end' )
           return valTab
           
        # ########## #
        if 'search' == name:
           printDBG( 'Host listsItems begin name='+name )
           pattern = url 
           if Index==-1: 
              self.history.addHistoryItem( pattern, 'video')
           url = 'http://k.zalukaj.tv/szukaj'
           try: data = self.cm.getURLRequestData({ 'url': url, 'use_host': False, 'use_cookie': False, 'use_post': True, 'return_data': True },{'searchinput': pattern})
           except:
              printDBG( 'Host listsItems query error' )
              printDBG( 'Host listsItems query error url:'+url )
              return valTab
           #printDBG( 'Host listsItems data: '+data )
           phMovies = re.findall('class="tivief4".*?src="(.*?)".*?<a href="(.*?)".*?title="(.*?)".*?div style.*?">(.*?)<.*?class="few_more">(.*?)<', data, re.S)
           if phMovies:
              for (phImage, phUrl, phTitle, phDescr, phMore) in phMovies:
                  printDBG( 'Host listsItems phImage: '  +phImage )
                  printDBG( 'Host listsItems phUrl: '    +phUrl )
                  printDBG( 'Host listsItems phTitle: '  +phTitle )
                  printDBG( 'Host listsItems phDescr: '  +phDescr )
                  printDBG( 'Host listsItems phMore: '   +phMore )
                  valTab.append(CDisplayListItem(phTitle, phMore+' | '+decodeHtml(phDescr), CDisplayListItem.TYPE_VIDEO, [CUrlItem('', phUrl, 1)], 0, phImage, None)) 
           printDBG( 'Host listsItems end' )
           return valTab
           
        # ########## #
        if 'seriale' == name:
           printDBG( 'Host listsItems begin name='+name )
           self.MAIN_URL = 'http://zalukaj.tv' 
           try: data = self.cm.getURLRequestData({ 'url': url, 'use_host': False, 'use_cookie': False, 'use_post': False, 'return_data': True })
           except:
              printDBG( 'Host listsItems query error' )
              printDBG( 'Host listsItems query error url:'+url )
              return valTab
           #printDBG( 'Host listsItems data: '+data )
           parse = re.search('<div id="two"(.*?)</table>', data, re.S)
           if not parse: return ''
           phMovies = re.findall('<td class="wef32f"><a href="(.*?)" title="(.*?)"', parse.group(1), re.S)
           if phMovies:
              for (phUrl, phTitle) in phMovies:
                  printDBG( 'Host listsItems phUrl: '  +phUrl )
                  printDBG( 'Host listsItems phTitle: '+phTitle )
                  valTab.append(CDisplayListItem(phTitle, phTitle, CDisplayListItem.TYPE_CATEGORY, [self.fullUrl(phUrl)], 'seriale-sezony', '', None))          
           valTab.insert(0,CDisplayListItem('--Ostatnio zaktualizowane seriale--',   'Ostatnio zaktualizowane seriale', CDisplayListItem.TYPE_CATEGORY, ['http://zalukaj.tv/seriale'], 'seriale-last', '', None))
           printDBG( 'Host listsItems end' )
           return valTab
        if 'seriale-last' == name:
           printDBG( 'Host listsItems begin name='+name )
           self.MAIN_URL = 'http://zalukaj.tv' 
           try: data = self.cm.getURLRequestData({ 'url': url, 'use_host': False, 'use_cookie': False, 'use_post': False, 'return_data': True })
           except:
              printDBG( 'Host listsItems query error' )
              printDBG( 'Host listsItems query error url:'+url )
              return valTab
           #printDBG( 'Host listsItems data: '+data )
           phMovies = re.findall('<div class="latest tooltip".*?href="(.*?)" title="(.*?)".*?src="(.*?)"', data, re.S)
           if phMovies:
              for (phUrl, phTitle, phImage) in phMovies:
                  printDBG( 'Host listsItems phUrl: '  +phUrl )
                  printDBG( 'Host listsItems phTitle: '+phTitle )
                  printDBG( 'Host listsItems phImage: '+phImage )
                  valTab.append(CDisplayListItem(phTitle, phTitle, CDisplayListItem.TYPE_CATEGORY, [self.fullUrl(phUrl)], 'seriale-sezon', phImage, None))          
           printDBG( 'Host listsItems end' )
           return valTab
        if 'seriale-sezony' == name:
           printDBG( 'Host listsItems begin name='+name )
           self.MAIN_URL = 'http://zalukaj.tv' 
           try: data = self.cm.getURLRequestData({ 'url': url, 'use_host': False, 'use_cookie': False, 'use_post': False, 'return_data': True })
           except:
              printDBG( 'Host listsItems query error' )
              printDBG( 'Host listsItems query error url:'+url )
              return valTab
           #printDBG( 'Host listsItems data: '+data )
           phImage = ''
           parse = re.search('<div id="sezony".*?img src="(.*?)"', data, re.S)
           if parse: phImage = parse.group(1)
           printDBG( 'Host listsItems phImage: '  +phImage )
           phMovies = re.findall('<a class="sezon" href="(.*?)".*?>(.*?)<', data, re.S)
           if phMovies:
              for (phUrl, phTitle) in phMovies:
                  printDBG( 'Host listsItems phUrl: '  +phUrl )
                  printDBG( 'Host listsItems phTitle: '+phTitle )
                  valTab.append(CDisplayListItem(phTitle, phTitle, CDisplayListItem.TYPE_CATEGORY, [self.fullUrl(phUrl)], 'seriale-sezon', phImage, None))          
           printDBG( 'Host listsItems end' )
           return valTab
        if 'seriale-sezon' == name:
           printDBG( 'Host listsItems begin name='+name )
           self.MAIN_URL = 'http://zalukaj.tv' 
           try: data = self.cm.getURLRequestData({ 'url': url, 'use_host': False, 'use_cookie': False, 'use_post': False, 'return_data': True })
           except:
              printDBG( 'Host listsItems query error' )
              printDBG( 'Host listsItems query error url:'+url )
              return valTab
           #printDBG( 'Host listsItems data: '+data )
           phImage = ''
           parse = re.search('<img src="(.*?)"', data, re.S)
           if parse: phImage = parse.group(1)
           printDBG( 'Host listsItems phImage: '  +phImage )
           phMovies = re.findall('id="sezony".*?>(.*?)<.*?href="(.*?)" title="(.*?)"', data, re.S)
           if phMovies:
              for (phEpisode, phUrl, phTitle) in phMovies:
                  printDBG( 'Host listsItems phEpizod: '  +phEpisode )
                  printDBG( 'Host listsItems phUrl: '  +phUrl )
                  printDBG( 'Host listsItems phTitle: '+phTitle )
                  valTab.append(CDisplayListItem(phEpisode+' - '+phTitle, phTitle, CDisplayListItem.TYPE_VIDEO, [CUrlItem('', self.fullUrl(phUrl), 1)], 0, phImage, None))          
                  printDBG( 'Host listsItems end' )
           return valTab
        if 'filmy' == name:
           printDBG( 'Host listsItems begin name='+name )
           self.MAIN_URL = 'http://zalukaj.tv' 
           try: data = self.cm.getURLRequestData({ 'url': url, 'use_host': False, 'use_cookie': False, 'use_post': False, 'return_data': True })
           except:
              printDBG( 'Host listsItems query error' )
              printDBG( 'Host listsItems query error url:'+url )
              return valTab
           #printDBG( 'Host listsItems data: '+data )
           sts,parse = CParsingHelper.getDataBeetwenMarkers(data, '<table id="one"', '</table>', False)
           phMovies = re.findall('<td class="wef32f"><a href="([^"]+?)">([^<]+?)</a>', parse, re.S)
           if phMovies:
              for (phUrl, phTitle) in phMovies:
                  printDBG( 'Host listsItems phUrl: '   + phUrl )
                  printDBG( 'Host listsItems phTitle: ' + phTitle )
                  valTab.append(CDisplayListItem(phTitle, phTitle, CDisplayListItem.TYPE_CATEGORY, [ self.fullUrl(phUrl) ], 'filmy-clip', '', None))          
           #valTab.insert(0,CDisplayListItem('--Najpopularniejsze--', 'Najpopularniejsze wyswietlenia-miesiac', CDisplayListItem.TYPE_CATEGORY, ['http://zalukaj.tv/#wyswietlenia-miesiac'], 'filmy-last', '', None))          
           #valTab.insert(0,CDisplayListItem('--Ostatnio oglądane--', 'Ostatnio oglądane',                      CDisplayListItem.TYPE_CATEGORY, ['http://zalukaj.tv/#lastseen'],             'filmy-last', '', None))          
           valTab.insert(0,CDisplayListItem('--Ostatnio dodane--',   'Ostatnio dodane',                        CDisplayListItem.TYPE_CATEGORY, ['http://zalukaj.tv'],            'filmy-last', '', None))          
           printDBG( 'Host listsItems end' )
           return valTab
        if 'filmy-clip' == name:
           printDBG( 'Host listsItems begin name='+name )
           self.MAIN_URL = 'http://zalukaj.tv' 
           try: data = self.cm.getURLRequestData({ 'url': url, 'use_host': False, 'use_cookie': False, 'use_post': False, 'return_data': True })
           except:
              printDBG( 'Host listsItems query error' )
              printDBG( 'Host listsItems query error url:'+url )
              return valTab
           #printDBG( 'Host listsItems data: '+data )
           phMovies = re.findall('background-image:url(.*?);"><p><span>(.*?)</span>.*?<h3><a href="(.*?)".*?">(.*?)<.*?">(.*?)<.*?class="few_more">(.*?)<', data, re.S)
           if phMovies:
              for (phImage, phRok, phUrl, phTitle, phDescr, phMore) in phMovies:
                  printDBG( 'Host listsItems phImage: '  +phImage )
                  printDBG( 'Host listsItems phRok: '    +phRok )
                  printDBG( 'Host listsItems phUrl: '    +phUrl )
                  printDBG( 'Host listsItems phTitle: '  +phTitle )
                  printDBG( 'Host listsItems phDescr: '  +phDescr )
                  printDBG( 'Host listsItems phMore: '   +phMore )
                  valTab.append(CDisplayListItem(phTitle, phRok+' | '+phMore+' | '+decodeHtml(phDescr), CDisplayListItem.TYPE_VIDEO, [CUrlItem('', phUrl, 1)], 0, phImage[1:-1], None)) 
           match = re.findall('class="pc_current">.*?href="(.*?)">(.*?)<', data, re.S)
           if match:               
                  phUrl = match[-1][0]
                  phTitle = match[-1][1]
                  valTab.append(CDisplayListItem('Strona '+phTitle, 'Strona: '+phUrl, CDisplayListItem.TYPE_CATEGORY, [self.fullUrl(phUrl)], name, '', None)) 
           printDBG( 'Host listsItems end' )
           return valTab
        if 'filmy-last' == name:
           printDBG( 'Host listsItems begin name='+name )
           self.MAIN_URL = 'http://zalukaj.tv' 
           try: data = self.cm.getURLRequestData({ 'url': url, 'use_host': False, 'use_cookie': False, 'use_post': False, 'return_data': True })
           except:
              printDBG( 'Host listsItems query error' )
              printDBG( 'Host listsItems query error url:'+url )
              return valTab
           #printDBG( 'Host listsItems data: '+data )
           phMovies = re.findall('class="tivief4".*?src="(.*?)".*?<h3><a href="(.*?)".*?">(.*?)<.*?">(.*?)<.*?class="few_more">(.*?)<', data, re.S)
           if phMovies:
              for (phImage, phUrl, phTitle, phDescr, phMore) in phMovies:
                  printDBG( 'Host listsItems phImage: '  +phImage )
                  printDBG( 'Host listsItems phUrl: '    +phUrl )
                  printDBG( 'Host listsItems phTitle: '  +phTitle )
                  printDBG( 'Host listsItems phDescr: '  +phDescr )
                  printDBG( 'Host listsItems phMore: '   +phMore )
                  valTab.append(CDisplayListItem(phTitle, phMore+' | '+decodeHtml(phDescr), CDisplayListItem.TYPE_VIDEO, [CUrlItem('', self.fullUrl(phUrl), 1)], 0, phImage, None)) 
           printDBG( 'Host listsItems end' )
           return valTab

        return valTab

    def getResolvedURL(self, url):
        printDBG( 'Host getResolvedURL begin' )
        printDBG( 'Host getResolvedURL url: '+url )
        videoUrl = ''
        valTab = []
        
        if self.PREMIUM:
            sts, data = self.cm.getPage(url, {'use_host': True, 'host': self.HOST, 'use_cookie': True, 'save_cookie': False, 'load_cookie': True, 'cookiefile': self.COOKIEFILE})
            if sts:
                parse = re.search('/player.php.*?"', data, re.S)
                if parse: 
                    printDBG( 'parse1p: '+parse.group(0) )
                    url2 = self.fullUrl(parse.group(0))
                    sts, data = self.cm.getPage(url2, {'use_host': True, 'host': self.HOST, 'use_cookie': True, 'save_cookie': False, 'load_cookie': True, 'cookiefile': self.COOKIEFILE, 'use_post': False, 'return_data': True })
                    if sts:
                        parse = re.search('<a href="(.*?)"', data, re.S)
                        if parse:
                            printDBG( 'parse2p: '+parse.group(1) )
                            url2 = parse.group(1)
                            sts,data = self.cm.getPage(url2, { 'use_host': True, 'host': self.HOST, 'use_cookie': True, 'save_cookie': False, 'load_cookie': True, 'cookiefile': self.COOKIEFILE, 'use_post': False, 'return_data': True })
                            if sts: 
                                printDBG( 'parse3pdata ')
                                match = re.compile("url:'(.+?)'").findall(data)
                                if len(match) > 0:                       
                                    printDBG( 'parse3p: PREMIUM: '+match[0] )
                                    linkvideo = match[0]
                                    return linkvideo
                    else:
                        printDBG( 'Host getResolvedURL query error premium' )
                        printDBG( 'Host getResolvedURL query error premium url: '+url2 )
                else:
                    printDBG( 'Host getResolvedURL query error premium' )
                    printDBG( 'Host getResolvedURL query error premium url: '+url2 )
            else:
                printDBG( 'Host getResolvedURL query error premium' )
                printDBG( 'Host getResolvedURL query error premium url: '+url )
              
        if url[0:30] == 'http://zalukaj.tv/zalukaj-film' or url[0:31] == 'http://zalukaj.tv/serial-online':      
            sts, data = self.cm.getPage(url)
            if not sts:
               printDBG( 'Host getResolvedURL query error' )
               printDBG( 'Host getResolvedURL query error url: '+url )
               return ''
               
            parse = re.search('/player.php.*?"', data, re.S)
            if not parse: return '' 
            printDBG( 'parse1: '+parse.group(0) )
            url2 = self.fullUrl(parse.group(0))
            sts, data = self.cm.getPage(url2)
            if not sts:
               printDBG( 'Host getResolvedURL query error' )
               printDBG( 'Host getResolvedURL query error url: '+ url2 )
               return ''
            parse = re.search('<a href="([^"]+?)"', data, re.S)
            if not parse: 
               return ''
            printDBG( 'parse2: '+parse.group(1) )
            url2 = parse.group(1)
            sts, data = self.cm.getPage(url2)
            if not sts:
               return ''
            parse = re.search('iframe src="([^"]+?)" width=', data)
            if not parse:
               return ''
            ret = self.up.getVideoLink( parse.group(1) )
            if ret:
               return ret
        return ''
示例#47
0
 def __init__(self, lang='en'):
     self.sessionEx = MainSessionWrapper()
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='', action='verify'):
        sleepObj = None
        token = ''
        errorMsgTab = []
        apiKey = config.plugins.iptvplayer.api_key_2captcha.value
        apiUrl = self.getFullUrl('/in.php?key=') + apiKey + '&method=userrecaptcha&version=v3&action=' + action + '&min_score=0.3&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 = 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 = 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
class diffanime:
    HOST = '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'
    HEADER = {'User-Agent': HOST, 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'}

    MAINURL = 'http://diff-anime.pl'
    SERVICE_MENU_TABLE = {
        1: "Lista anime (alfabetycznie)",
#        2: "Lista anime (wg. gatunku)",
        2: "Ranking",
        3: "Ulubione",
        4: "Aktualności"
    }

    def __init__(self):
        self.up = urlparser.urlparser()
        self.cm = pCommon.common()
        self.sessionEx = MainSessionWrapper()
        self.ytp = YouTubeParser()
        self.ytformats = config.plugins.iptvplayer.ytformat.value
        # Temporary data
        self.currList = []
        self.currItem = {}
        # Login data
        self.COOKIEFILE = GetCookieDir('Diff-anime.cookie')
        self.usePremiumAccount = config.plugins.iptvplayer.diffanime_premium.value
        self.username = config.plugins.iptvplayer.diffanime_login.value
        self.password = config.plugins.iptvplayer.diffanime_password.value

    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

# Login in to the site
    def requestLoginData(self):
        if False == self.usePremiumAccount:
            printDBG("diffanime niezalogowany")
        else:
            self.usePremiumAccount = False
            url = self.MAINURL
            query_data = {'url': url, 'header': self.HEADER, 'use_cookie': True, 'save_cookie': True, 'cookiefile': self.COOKIEFILE, 'return_data': True}
            postdata = {'user_name': self.username, 'user_pass': self.password, 'remember_me': 'y', "login": "******"}
            try:
                data = self.cm.getURLRequestData(query_data, postdata)
            except:
                printDBG("diffanime requestLoginData exception")
                return
            if 'Wyloguj' in data:
                printDBG("diffanime Notification(" + self.username + ", Zostales poprawnie zalogowany)")
                self.usePremiumAccount = True
            else:
                self.sessionEx.waitForFinishOpen(MessageBox, 'Błąd logowania. Sprawdź dane.\nlogin - ' + self.username + ' \nhasło - ' + self.password, type=MessageBox.TYPE_INFO, timeout=10)
                printDBG("diffanime Notification(Blad logowania)")
# end login

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

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

    def setTable(self):
        return self.SERVICE_MENU_TABLE

# Get YT link
    def getYTVideoUrl(self, url):
        printDBG("getYTVideoUrl url[%s]" % url)
        tmpTab = self.ytp.getDirectLinks(url, self.ytformats)

        movieUrls = []
        for item in tmpTab:
            movieUrls.append({'name': item['format'] + '\t' + item['ext'], 'url': item['url']})

        return movieUrls

    def getVideoUrlforYTube(self, url):
        printDBG("getVideoUrl url[%s]" % url)
        query_data = {'url': url, 'use_host': True, 'host': self.HOST, 'use_cookie': True, 'save_cookie': False, 'load_cookie': True, 'cookiefile': self.COOKIEFILE, 'use_post': False, 'return_data': True}
        try:
            data = self.cm.getURLRequestData(query_data)
        except:
            printDBG('getVideoUrl exception')
            return ''
        match = re.search('src="//www.youtube.com/(.+?)"', data)
        if match:
            printDBG('www.youtube.com/' + match.group(1))
            return self.getYTVideoUrl('www.youtube.com/' + match.group(1))
        else:
            printDBG('nie znaleziono YT link')
        return ''
# end Get YT link

# Get mp4 link
    def getVideoUrl(self, url):
        printDBG("getVideoUrl url[%s]" % url)
        query_data = {'url': url, 'use_host': True, 'host': self.HOST, 'use_cookie': True, 'save_cookie': False, 'load_cookie': True, 'cookiefile': self.COOKIEFILE, 'use_post': False, 'return_data': True}
        try:
            data = self.cm.getURLRequestData(query_data)
        except:
            printDBG('getVideoUrl exception')
            return ''
        match = re.search("'file': '(.+?)',", data)
        if match:
            return match.group(1)
        else:
            printDBG('nie znaleziono mp4 link')
        return ''
# end Get mp4 link

    def listsMainMenu(self, table):
        query_data = {'url': self.MAINURL + '/newsy', 'return_data': True}
        try:
            data = self.cm.getURLRequestData(query_data)
        except:
            printDBG('listAbcItem exception')
            return
        match = re.compile("div class='sRight'><div class='panel news'>(.+?)<div class='left'><div>Czytań:", re.DOTALL).findall(data)
        if len(match) > 0:
            match2 = re.search(".png' alt=([^<]+?)class='news-category'", match[0])
            if match2:
                plot = match2.group(1)
            else:
                plot = ''
            match3 = re.search("class='news-category' />([^<]+?)</div>", match[0])
            if match3:
                plot2 = match3.group(1)
            else:
                plot2 = ''
            icon = re.compile("<div class='content'><img src='(.+?)' alt='").findall(match[0])

        for num, val in table.items():
                params = {'name': 'main-menu', 'category': val, 'title': val, 'icon': self.MAINURL + icon[0], 'plot': self.cm.html_entity_decode(plot + plot2)}
                self.addDir(params)

    def listsABCMenu(self, table):
        for i in range(len(table)):
            params = {'name': 'abc-menu', 'category': table[i], 'title': table[i], 'icon': ''}
            self.addDir(params)

# "AKTUALNOŚCI"
    def getlistsNews(self, url):
        query_data = {'url': url, 'use_host': False, 'use_cookie': False, 'use_post': False, 'return_data': True}
        try:
            data = self.cm.getURLRequestData(query_data)
        except:
            printDBG('listsGenre EXCEPTION')
        r2 = re.compile("<div class='head'><h2><a href='/news/(.+?)'>(.+?)</a>").findall(data)
        if len(r2) > 0:
                for i in range(len(r2)):
                    value = r2[i]
                    title = self.cm.html_entity_decode(value[1])
                    data = self.MAINURL + '/news/' + value[0]
                    data2 = self.cm.getURLRequestData({'url': data, 'use_host': False, 'use_cookie': False, 'use_post': False, 'return_data': True})
                    value = re.search("<div class='content'><img src='(.+?)' alt='(.+?)' class='news-category' />(.+?).<br />", data2)
                    if value:
                        icon = self.MAINURL + value.group(1)
                        plot = self.cm.html_entity_decode(value.group(2) + value.group(3))
                    else:
                        icon = ''
                        plot = ''
                    params = {'name': 'news', 'title': title, 'icon': icon, 'plot': plot, 'page': data}
                    self.addVideo(params)

# "ULUBIONE"
    def getlistsUlubione(self, url):
        query_data = {'url': url + '/odcinki', 'use_host': True, 'host': self.HOST, 'use_cookie': True, 'save_cookie': False, 'load_cookie': True, 'cookiefile': self.COOKIEFILE, 'use_post': False, 'return_data': True}
        try:
            data = self.cm.getURLRequestData(query_data)
        except:
            printDBG('listsGenre EXCEPTION')
        r = re.compile("<div id='pUAL' class='panel pDef'>(.+?)<div id='footer'>", re.DOTALL).findall(data)
        if len(r) > 0:
            x1 = re.compile("W trakcie<(.+?)>Ukończone<", re.DOTALL).findall(data)
            if len(x1) > 0:
                rx1 = re.compile("'sTitle'><a href='(.+?)'>(.+?)</a>").findall(x1[0])
                if len(rx1) > 0:
                    for i in range(len(rx1)):
                        value = rx1[i]
                        title = self.cm.html_entity_decode("W trakcie - " + value[1])
                        page = self.MAINURL + value[0]
                        params = {'name': 'ulubione', 'title': title, 'page': page, 'icon': ''}
                        self.addDir(params)
            x2 = re.compile("Ukończone<(.+?)>Wstrzymane<", re.DOTALL).findall(data)
            if len(x2) > 0:
                rx2 = re.compile("'sTitle'><a href='(.+?)'>(.+?)</a>").findall(x2[0])
                if len(rx2) > 0:
                    for i in range(len(rx2)):
                        value = rx2[i]
                        title = self.cm.html_entity_decode("Ukończone - " + value[1])
                        page = self.MAINURL + value[0]
                        params = {'name': 'ulubione', 'title': title, 'page': page, 'icon': ''}
                        self.addDir(params)
            x3 = re.compile("Wstrzymane<(.+?)>Porzucone<", re.DOTALL).findall(data)
            if len(x3) > 0:
                rx3 = re.compile("'sTitle'><a href='(.+?)'>(.+?)</a>").findall(x3[0])
                if len(rx3) > 0:
                    for i in range(len(rx3)):
                        value = rx3[i]
                        title = self.cm.html_entity_decode("Wstrzymane - " + value[1])
                        page = self.MAINURL + value[0]
                        params = {'name': 'ulubione', 'title': title, 'page': page, 'icon': ''}
                        self.addDir(params)
            x4 = re.compile("Porzucone<(.+?)>W planach<", re.DOTALL).findall(data)
            if len(x4) > 0:
                rx4 = re.compile("'sTitle'><a href='(.+?)'>(.+?)</a>").findall(x4[0])
                if len(rx4) > 0:
                    for i in range(len(rx4)):
                        value = rx4[i]
                        title = self.cm.html_entity_decode("Porzucone - " + value[1])
                        page = self.MAINURL + value[0]
                        params = {'name': 'ulubione', 'title': title, 'page': page, 'icon': ''}
                        self.addDir(params)
            x5 = re.compile("W planach<(.+?)='footer'>", re.DOTALL).findall(data)
            if len(x5) > 0:
                rx5 = re.compile("'sTitle'><a href='(.+?)'>(.+?)</a>").findall(x5[0])
                if len(rx5) > 0:
                    for i in range(len(rx5)):
                        value = rx5[i]
                        title = self.cm.html_entity_decode("W planach - " + value[1])
                        page = self.MAINURL + value[0]
                        params = {'name': 'ulubione', 'title': title, 'page': page, 'icon': ''}
                        self.addDir(params)
# "RANKING"
    def getlistsRanks(self, url):
        query_data = {'url': url, 'use_host': False, 'use_cookie': False, 'use_post': False, 'return_data': True}
        try:
            data = self.cm.getURLRequestData(query_data)
        except:
            printDBG('listsGenre EXCEPTION')
        r = re.compile("<h2>Ranking anime</h2>(.+?)</table>", re.DOTALL).findall(data)
        if len(r) > 0:
            r2 = re.compile("<td class='td2'><a href='/(.+?)'><img src='(.+?)' class='img' /></a><div class='con'><a href='(.+?)'>(.+?)</a><p>").findall(r[0])
            if len(r2) > 0:
                for i in range(len(r2)):
                    value = r2[i]
                    title = self.cm.html_entity_decode(value[3])
                    page = self.MAINURL + value[2]
                    icon = self.MAINURL + value[1]
                    params = {'name': 'ranks', 'title': title, 'page': page, 'icon': icon}
                    self.addDir(params)

# "KATEGORIE"
    def getlistsGenre(self, url):
        query_data = {'url': url, 'use_host': False, 'use_cookie': False, 'use_post': False, 'return_data': True}
        try:
            data = self.cm.getURLRequestData(query_data)
        except:
            printDBG('listsGenre EXCEPTION')
        r = re.compile("</div><div id='pSettings' class='panel'>(.+?)</div></div>", re.DOTALL).findall(data)
        if len(r) > 0:
            r2 = re.compile("<a href='(.+?)'>(.+?)</a>").findall(r[0])
            if len(r2) > 0:
                for i in range(len(r2)):
                    value = r2[i]
                    title = self.cm.html_entity_decode(value[1])
                    page = value[0] + '&rowstart=00'
                    params = {'name': 'genset', 'title': title, 'page': page, 'plot': title, 'icon': ''}
                    self.addDir(params)

# ANIME TITLES
    def getAnimeList(self, url):
        query_data = {'url': self.MAINURL + url, 'use_host': False, 'use_cookie': False, 'use_post': False, 'return_data': True}
        try:
            data = self.cm.getURLRequestData(query_data)
        except:
            printDBG('getAnimeList EXCEPTION')
            nextPage = False
        if -1 != data.find("div class='pagenav") and -1 != data.find("class='img"):
            nextPage = True
        else:
            nextPage = False
        r = re.compile("</div><div id='pSeries' class='panel'>(.+?)<div id='footer'>", re.DOTALL).findall(data)
        if len(r) > 0:
            r2 = re.compile("</a><div class='con'><a href='/(.+?)'>(.+?)</a><p>").findall(r[0])

            if len(r2) > 0:
                for i in range(len(r2)):
                    value = r2[i]
                    title = self.cm.html_entity_decode(value[1])
                    page = value[0]
                    data = self.MAINURL + "/" + value[0]
                    data2 = self.cm.getURLRequestData({'url': data, 'use_host': False, 'use_cookie': False, 'use_post': False, 'return_data': True})
    #Cover
                    grafika = re.search("</div><div class='content'><div class='con'><a href='(.+?)' class='fbox'>", data2)
                    if grafika:
                        icon = self.MAINURL + grafika.group(1)
                    else: icon =''
    #Description
                    match = re.search("<h2>Opis anime</h2></div><div class='content'><div class='con'>(.+?)</div>", data2)
                    if match:
                        plot = match.group(1)
                    else:
                        match = re.search("<h2>Opis anime</h2></div><div class='content'><div class='con'>(.+?)<", data2)
                        if match:
                            plot = match.group(1)
                        else:
                            match = re.search("<h2>Opis anime</h2></div><.+?>(.+?)<", data2)
                            if match:
                                plot = match.group(1)
                            else:
                                plot = ''
                    params = {'name': 'episodelist', 'title': title, 'page': page, 'icon': icon, 'plot': self.cm.html_entity_decode(plot)}
                    self.addDir(params)
        if nextPage is True:
                        nextpage = url[:-2] + str(int(url[-2:]) + 10)

                        params = {'name': 'nextpage', 'title': 'Next page', 'page': nextpage}
                        self.addDir(params)

# EPISODES LIST
    def getEpisodeList(self, url):
        query_data = {'url': url + '/odcinki', 'use_host': True, 'host': self.HOST, 'use_cookie': True, 'save_cookie': False, 'load_cookie': True, 'cookiefile': self.COOKIEFILE, 'use_post': False, 'return_data': True}
        query_data1 = {'url': url, 'use_host': False, 'use_cookie': False, 'use_post': False, 'return_data': True}
        try:
            data = self.cm.getURLRequestData(query_data)  # episodes data
            data2 = self.cm.getURLRequestData(query_data1)  # cover, desc. data
        except:
            printExc()
    # Description
        match = re.search("<h2>Opis anime</h2></div><div class='content'><div class='con'>(.+?)</div>", data2)
        if match:
            plot = match.group(1)
        else:
            match = re.search("<h2>Opis anime</h2></div><div class='content'><div class='con'>(.+?)<", data2)
            if match:
                plot = match.group(1)
            else:
                match = re.search("<h2>Opis anime</h2></div><.+?>(.+?)<", data2)
                if match:
                    plot = match.group(1)
                else:
                    plot = ''
    # Cover
        grafika = re.search("</div><div class='content'><div class='con'><a href='(.+?)' class='fbox'>", data2)
        if grafika:
            icon = self.MAINURL + grafika.group(1)
        else: icon =''
    # Episodes
        match = re.compile("<span class='head2'>Statystyki:</span>(.+?)<div class='mainCon'>", re.DOTALL).findall(data)
        if len(match) > 0:
            match2 = re.compile("#(.+?)</div><div class=.+?</div><div class='con3'><a href='(.+?)' class='i'>").findall(match[0])
            if len(match2) > 0:
                for i in range(len(match2)):
                    value = match2[i]
                    page = self.MAINURL + value[1]
                    title = 'Odcinek ' + value[0]
                    params = {'title': title, 'page': page, 'plot': self.cm.html_entity_decode(plot), 'icon': icon}
                    self.addVideo(params)

    def handleService(self, index, refresh=0, searchPattern='', searchType=''):
        printDBG('handleService start')
        if 0 == refresh:
            if len(self.currList) <= index:
                printDBG("handleService wrong index: %s, len(self.currList): %d" % (index, len(self.currList)))
                return
            if -1 == index:
                # use default value
                self.currItem = {"name": None}
                printDBG("handleService for first self.category")
            else:
                self.currItem = self.currList[index]

        name = self.currItem.get("name", '')
        title = self.currItem.get("title", '')
        category = self.currItem.get("category", '')
        page = self.currItem.get("page", '')
        icon = self.currItem.get("icon", '')

        printDBG("handleService: |||||||||||||||||||||||||||||||| [%s] " % name)
        self.currList = []

        if str(page) == 'None' or page == '':
            page = '0'

# Fill the Menu

    #MAIN MENU
        if name is None:
            #logowanie
            if self.usePremiumAccount:
                self.requestLoginData()
            self.listsMainMenu(self.SERVICE_MENU_TABLE)

    #LISTA ANIME (Alfabetycznie)
        elif category == self.setTable()[1]:
            self.listsABCMenu(self.cm.makeABCList())
        elif name == 'abc-menu':
            url = '/lista-anime?letter=' + category + '&rowstart=00'
            self.getAnimeList(url)
        elif name == 'nextpage':
            self.getAnimeList(page)

    #LISTA ANIME (wg. Gatunku)
#        elif category == self.setTable()[2]:
#            url = self.MAINURL + '/lista-anime'
#            self.getlistsGenre(url)
#        elif name == 'genset':
#            self.getAnimeList(page)

    #LISTA ANIME (wg. Rankingu)
        elif category == self.setTable()[2]:
            url = self.MAINURL + '/ranking-anime'
            self.getlistsRanks(url)
        elif name == 'ranks':
            self.getEpisodeList(page)

    #ULUBIONE
        elif category == self.setTable()[3]:
            url = self.MAINURL + '/moja-lista/' + self.username
            self.getlistsUlubione(url)
        elif name == 'ulubione':
            self.getEpisodeList(page)

    #AKTUALNOŚCI
        elif category == self.setTable()[4]:
            url = self.MAINURL + '/newsy'
            self.getlistsNews(url)
        elif name == 'news':
            self.getlistsNews(page)

    #Episodes will not display without this:
    #Episodes list
        elif name == 'episodelist':
            url = self.MAINURL + '/' + page
            self.getEpisodeList(url)
示例#50
0
class VideoStarApi:
    MAINURL_PC      = 'https://videostar.pl/'
    MAINURL_IOS     = 'https://m.videostar.pl/'
    HTTP_HEADER_PC   = { 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:12.0) Gecko/20100101 Firefox/12.0', 'Referer': MAINURL_PC }
    HTTP_HEADER_IOS  = { 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B179 Safari/7534.48.3', 'Referer': MAINURL_IOS }
    HTTP_HEADER2     = { 'User-Agent':'Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16', 'Referer': MAINURL_IOS}

    API_URLS = { 'login_url'          : 'login',
                 'get_ad_show'        : 'api/ad/show',
                 'get_ad_urls'        : 'api/ad/urls',
                 'get_channels_list'  : 'api/channels/list/web',
                 'get_channel_url'    : 'api/channels/get/%s?format_id=%s',
                 'close_channel'      : 'api/channels/close',
               }
    VIDEO_STAR_T   = ''
    VIDEO_GUEST_M  = False

    def __init__(self):
        self.cm = common()#proxyURL= '', useProxy = True)
        self.up = urlparser()
        self.sessionEx = MainSessionWrapper()

    def doInit(self):
        if config.plugins.iptvplayer.videostar_use_proxy_gateway.value:
            self.proxy_gateway_url = "http://www.bramka-proxy.pl/browse.php?u={0}&b=192&f=norefer" #config.plugins.iptvplayer.videostar_proxy_gateway_url.value
            self.proxy_gateway_ssl = "http://www.bramka-proxy.pl/includes/process.php?action=sslagree"
            self.my_ip             = self.getProxyGatewayIP()
        else:
            self.my_ip = ''
            self.proxy_gateway_url = ''
        self._reInit()
        self.channelsList = []
        
    def getProxyGatewayIP(self):
        url = 'http://showip.net/'
        sts, data = self.cm.getPage(url, {'header':{'User-Agent':'Mozilla/5.0', 'Referer':self.proxy_gateway_url}, 'proxy_gateway':self.proxy_gateway_url})
        my_ip = ''
        if sts:
            try:
                my_ip = self.cm.ph.getSearchGroups(data, 'name="check_ip"[^>]+?value="([^"]+?)"')[0]
                printDBG('getProxyGatewayIP my_ip[%s]' % my_ip)
            except:
                printExc()
        if '' == my_ip:
            self.sessionEx.open(MessageBox, _('Problem z uzyskaniem IP bramki proxy!'), type = MessageBox.TYPE_INFO, timeout = 10 )
        return my_ip
        

    def _getUrl(self, key):
        if '2' == self.streamprotocol:
            MAINURL = VideoStarApi.MAINURL_IOS
        else:
            MAINURL = VideoStarApi.MAINURL_PC
        if key in VideoStarApi.API_URLS:
            return MAINURL + VideoStarApi.API_URLS[key]
        if not key.startswith('http'):
            return MAINURL + key
        return key
        
    def _reInit(self): 
        self.streamprotocol  = config.plugins.iptvplayer.videostar_streamprotocol.value
        if '2' == self.streamprotocol:
            self.MAINURL = VideoStarApi.MAINURL_IOS
            self.cm.HEADER = dict(VideoStarApi.HTTP_HEADER_IOS)
        else:
            self.MAINURL = VideoStarApi.MAINURL_PC
            self.cm.HEADER = dict(VideoStarApi.HTTP_HEADER_PC)
        if '' != self.my_ip:
            self.cm.HEADER['X-Forwarded-For'] = self.my_ip
        self.PREMIUM         = config.plugins.iptvplayer.videostar_premium.value
        self.LOGIN           = config.plugins.iptvplayer.videostar_login.value
        self.PASSWORD        = config.plugins.iptvplayer.videostar_password.value
        
    def getDefaultQuality(self):
        return config.plugins.iptvplayer.videostar_defquality.value

    def getChannelsList(self, refresh=False):
        printDBG("VideoStarApi.getChannelsList")
        self.doInit()
        if not refresh and 0 < len(self.channelsList):
            return self.channelsList

        self.channelsList = []
        if '' != self.LOGIN.strip() and '' != self.PASSWORD.strip():
            if not self.doLogin(self.LOGIN, self.PASSWORD):
                self.sessionEx.open(MessageBox, _('Problem z zalogowanie użytkownika "%s. Sprawdź dane do logowania w konfiguracji hosta."') % self.LOGIN, type = MessageBox.TYPE_INFO, timeout = 10 )
                return self.channelsList
        else:
            self.sessionEx.open(MessageBox, _('Strona wymaga zalogowania. Proszę uzupełnić dane w konfiguracji hosta.'), type = MessageBox.TYPE_INFO, timeout = 10 )
            return self.channelsList
         
        self._fillChannelsList()
        return self.channelsList 
        
    def _fillChannelsList(self):
        printDBG("VideoStarApi._fillChannelsList")
        # get channels list
        sts, data = self.cm.getPage( self._getUrl('get_channels_list') )
        if sts:
            try:
                data = json.loads(data)
                if "ok" == data['status']:
                    self.channelsList = data['channels']
            except:
                printExc()
        
        #self.getVideoLink(12)
        #self.getVideoLink(12)

    def getVideoLink(self, channelID):
        printDBG("VideoStarApi.getVideoLink")
        urlsTab = []
        
        #get referer page
        referer = ''
        guestMode   = False 
        for item in self.channelsList:
            if channelID == item['id']:
                referer = self.MAINURL  + '#' + item['slug'] # "slug" attrib can be also taken from stream_channel data
                if "unsubscribed" == item['access_status']:
                    guestMode = True
                break
        
        for tryNum in range(2):
        
            # there is need to close previuse played channel 
            self._closePrevChannel()
            
            # retrie if there was unknown problem with getting link
            self._reInit()
            if not guestMode:
                self.doLogin(self.LOGIN, self.PASSWORD)
                sts, data = self.cm.getPage( referer )
                if not sts:
                    printExc('Error when downloading referer')
            else:
                self.cm.HEADER = dict(VideoStarApi.HTTP_HEADER2)
                if '' != self.my_ip:
                    self.cm.HEADER['X-Forwarded-For'] = self.my_ip
            
            url     = self._getUrl('get_channel_url') % (channelID, self.streamprotocol)
            HTTP_HEADER = dict(self.cm.HEADER)
            HTTP_HEADER.update( {'X-Reguested-With':'XMLHttpReguest'} )
            
            if guestMode: 
                url = url.replace('https://videostar.pl/api', 'https://api.videostar.pl/guest')
            sts, data = self.cm.getPage( url, {'header': HTTP_HEADER} )
            try:
                #printDBG("--------------------------------------------------")
                #printDBG(data)
                #printDBG("--------------------------------------------------")
                data = json.loads(data)
                if "ok" == data['status']:
                    VideoStarApi.VIDEO_STAR_T = data['stream_channel']['url_params'][-1].decode('utf-8')
                    url_param1 = data['stream_channel']['url_params'][1].decode('utf-8')
                    VideoStarApi.VIDEO_GUEST_M  = guestMode
                    if '1' == self.streamprotocol:
                        url = data['stream_channel']['url_base'].decode('utf-8')
                        sts, data = self.cm.getPage( url, {'header': HTTP_HEADER})
                        r = re.search('<baseURL>([^<]+?)</baseURL>', data).group(1)
                        
                        streams = re.findall('url="([^"]+?)" bitrate="([0-9]+?)"', data)
                        for item in streams:
                            # swfVfy=https://videostar.pl/javascripts/libs/flowplayer/flowplayer.netvi-x.swf protocol=1 
                            url = r + '/' + item[0] + ' live=1 swfUrl=https://videostar.pl/javascripts/libs/flowplayer/flowplayer.commercial-3.2.11.swf' + ' pageUrl=' + referer + (' conn=S:%s conn=S:%s token=%s' % (url_param1, VideoStarApi.VIDEO_STAR_T, VideoStarApi.VIDEO_STAR_T)) + ' flashVer=WIN 12,0,0,44 '
                            urlsTab.append({'url': strwithmeta(url, {'iptv_proto':'rtmp'}), 'name': item[1], 'bitrate':item[1]+'000', 'type':'rtmpt'})
                    else:
                        # hls
                        url = data['stream_channel']['url_base'].decode('utf-8')
                        meta = {'iptv_proto':'m3u8'}
                        if '' != self.proxy_gateway_url:
                            channelID = data['stream_channel']['channel_id']
                            #if url.startswith('https://'): url = 'http://' + url[8:]
                            server = self.cm.ph.getSearchGroups(url, r'://([^/]+?)/')[0]
                            meta['iptv_m3u8_custom_base_link'] = 'http://%s:1935/%s/smil:%s.ism/list.m3u8' % (server, channelID, 'basic')
                            meta['iptv_proxy_gateway'] = self.proxy_gateway_url
                            meta['Referer'] =  self.proxy_gateway_url
                            meta['User-Agent'] = 'Mozilla/5.0'
                            meta['X-Forwarded-For'] = self.my_ip
                            
                            meta['Cookie'] = self.getCookieItem('s', self.proxy_gateway_ssl, {'header':{'User-Agent':'Mozilla/5.0'}})
                        urlsTab.append({'url': self.up.decorateUrl(url, meta), 'name': 'videostar hls', 'type':'hls'})
            except:
                printExc()
                
            if 0 < len(urlsTab):
                break
        
        printDBG(urlsTab)
        return urlsTab

    def _closePrevChannel(self):
        printDBG("VideoStarApi._closePrevChannel start VIDEO_STAR_T[%s]" % VideoStarApi.VIDEO_STAR_T)
        if '' != VideoStarApi.VIDEO_STAR_T:
            url         = self._getUrl('close_channel')
            HTTP_HEADER = dict(self.cm.HEADER)
            HTTP_HEADER.update( {'X-Reguested-With':'XMLHttpReguest', 'Content-Type':'application/x-www-form-urlencoded', 'charset':'UTF-8'} )
            post_data = {'t': VideoStarApi.VIDEO_STAR_T}
            
            if VideoStarApi.VIDEO_GUEST_M: url = url.replace('https://videostar.pl/api', 'https://api.videostar.pl/guest')
            sts, data = self.cm.getPage( url, {'header': HTTP_HEADER}, post_data)
            try:
                data = json.loads(data)
                if "ok" == data['status']:
                    VideoStarApi.VIDEO_STAR_T = ''
            except:
                printExc()
        printDBG("_closePrevChannel end VIDEO_STAR_T[%s]" % VideoStarApi.VIDEO_STAR_T)

    def doLogin(self, login, password):
        HTTP_HEADER= dict(self.cm.HEADER)
        HTTP_HEADER.update( {'Content-Type':'application/x-www-form-urlencoded'} )
        
        cookiePath = GetCookieDir('videostar.cookie')
        params = {'header':HTTP_HEADER, 'cookiefile': cookiePath, 'use_cookie': True, 'save_cookie':True}
        post_data = {'login': login, 'password': password, 'permanent': '1'}
        sts, data = self.cm.getPage( self._getUrl('login_url'), params, post_data)
        if sts:
            # the LWP has problem to read prepared Cookie, so we will manually read them and add to header
            try:
                with open(cookiePath, 'r') as infile:
                    data = infile.read()
                    PHPSESSID = re.search('(PHPSESSID=[^;]+?;)', data).group(1)
                    netviapisessid = re.findall('(netviapisessid[^;]+?;)', data)[-1] #HttpOnly
                    self.cm.HEADER['Cookie'] = PHPSESSID + netviapisessid

                sts, data = self.cm.getPage(self.MAINURL)
                if sts and 'Wyloguj' in data:
                    return True
            except:
                printExc()
        return False
        
        
    def getCookieItem(self, key, url, params={}, post_data=None):
        
        cookiePath = GetCookieDir('tmp.cookie')
        params.update({'cookiefile': cookiePath, 'use_cookie': True, 'save_cookie':True})
        sts, data = self.cm.getPage(url, params, post_data)
        itemValue = ''
        if sts:
            # the LWP has problem to read prepared Cookie, so we will manually read them and add to header
            try:
                with open(cookiePath, 'r') as infile:
                    data = infile.read()
                    itemValue = re.search(' (%s=[^;]+?;)' % key, data).group(1)
            except:
                printExc()
        return itemValue