def __init__(self):
     self.up = urlparser.urlparser()
     self.cm = common()
     self.history = CSearchHistoryHelper('Wgrane')
     # temporary data
     self.currList = []
     self.currItem = {}
Exemple #2
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
Exemple #3
0
    def __init__(self):
        self.menuHTML = ''
        self.refresh = False
        self.cm = common()
        self.history = CSearchHistoryHelper('ninateka')

        # temporary data
        self.currList = []
        self.currItem = {}
 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')
Exemple #5
0
    def __init__(self):

        printDBG('Loading ' + serialeo.SERVICE)

        self.cm = common()
        self.up = urlparser.urlparser()
        self.history = CSearchHistoryHelper('serialeo')

        self.tabMenu = []
        self.currList = []
Exemple #6
0
 def __init__(self):
     self.up = urlparser.urlparser()
     self.cm = pCommon.common()
     self.history = CSearchHistoryHelper('iptak')
     # temporary data
     self.currList = []
     self.currItem = {}
     
     # for cache to speedUp
     self.menuData = None
Exemple #7
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
Exemple #8
0
    def __init__(self):
        CBaseHostClass.__init__(self, {
            'history': 'ninateka',
            'cookie': 'ninateka.cookie'
        })
        self.DEFAULT_ICON_URL = 'http://ninateka.pl/Content/images/ninateka_logo.png'

        self.menuHTML = ''
        self.refresh = False
        self.cm = common()
        self.history = CSearchHistoryHelper('ninateka')

        self.MAIN_URL = 'http://ninateka.pl/'
        self.VIDEOS_URL = self.getFullUrl(
            'filmy?MediaType=video&Paid=False&CategoryCodenames=')
        self.SEARCH_URL = self.VIDEOS_URL + '&SearchQuery='

        #DEFAULT_GET_PARAM = 'MediaType=video&Paid=False'

        self.MAIN_CAT_TAB = [{
            'category': 'list_all',
            'title': 'Wszystkie',
            'url': self.VIDEOS_URL
        }, {
            'category': 'list_cats',
            'title': 'Kategorie',
            'url': self.MAIN_URL
        }, {
            'category': 'search',
            'title': _('Search'),
            'search_item': True,
        }, {
            'category': 'search_history',
            'title': _('Search history'),
        }]
 def __init__(self):
     self.up = urlparser.urlparser()
     self.cm = common()
     self.history = CSearchHistoryHelper('Wgrane')
     # temporary data
     self.currList = []
     self.currItem = {}
 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' )
Exemple #11
0
    def __init__(self):
        self.cm = common()
        self.history = CSearchHistoryHelper('fighttube')
        self.ytp = YouTubeParser()
        self.ytformats = config.plugins.iptvplayer.ytformat.value

        # temporary data
        self.currList = []
        self.currItem = {}
Exemple #12
0
 def getListForItem(self, Index = 0, refresh = 0, selItem = None):
     self.listOfprevList.append(self.host.getCurrList())
     self.listOfprevItems.append(self.host.getCurrItem())
     
     self.currIndex = Index
     if self.withSearchHistrory:
         self.setSearchPattern()
         try:
             if len(self.searchPattern):
                 sts, prevPattern = CSearchHistoryHelper.loadLastPattern()
                 if sts and prevPattern != self.searchPattern:
                     CSearchHistoryHelper.saveLastPattern(self.searchPattern)
         except:
             printExc()
     
     self.host.handleService(Index, refresh, self.searchPattern, self.searchType)
     convList = self.convertList(self.host.getCurrList())
     
     return RetHost(RetHost.OK, value = convList)
Exemple #13
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)
    def __init__(self):

        
        printDBG('Loading ' + serialeo.SERVICE)
        

        self.cm = common()
        self.up = urlparser.urlparser()
        self.history = CSearchHistoryHelper('serialeo')
        

        self.tabMenu = []
        self.currList = []
Exemple #15
0
class Ninateka:
    MAIN_URL = 'http://ninateka.pl/'
    VIDEOS_URL = MAIN_URL + 'filmy?MediaType=video&Paid=False&CategoryCodenames='
    SEARCH_URL = VIDEOS_URL + '&SearchQuery='
    
    DEFAULT_GET_PARAM = 'MediaType=video&Paid=False'
  
    MENU_TAB = {
        1: "Wszystkie",
        2: "Kategorie",
        3: "Wyszukaj",
        4: "Historia Wyszukiwania"
    }
    def __init__(self):
        self.menuHTML = ''
        self.refresh = False
        self.cm = common()
        self.history = CSearchHistoryHelper('ninateka')

        # temporary data
        self.currList = []
        self.currItem = {}

    def getCurrList(self):
        return self.currList

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

    def setCurrItem(self, item):
        self.currItem = item
        
    def getMenuHTML(self):
        printDBG("getMenuHTML start")
        
        if True == self.refresh or '' == self.menuHTML:
            self.menuHTML = ''
            sts, data = self.cm.getPage( self.MAIN_URL )
            if sts: self.menuHTML = CParsingHelper.getDataBeetwenMarkers(data, '<div class="nav-collapse collapse">', '<!--/.nav-collapse -->', False)[1]
        return self.menuHTML
        
    def setTable(self):
        return self.MENU_TAB
        
    def listsMainMenu(self, table):
        for num, val in table.items():
            params = {'type': 'category', 'name': 'main-menu', 'category': val, 'title': val}
            self.currList.append( params )
        
    def getMainCategory(self):
        menuHTML = self.getMenuHTML()
        
        match = re.compile('<li data-codename="([^"]+?)"><a href="/filmy/([^"^,^/]+?)">([^<]+?)</a>').findall( menuHTML )
        if len(match) > 0:
            for i in range(len(match)):
                params = {'type': 'category', 'name': 'main-category', 'page': match[i][0], 'title': match[i][2]}
                self.currList.append( params )
                
    def getSubCategory(self, cat):
        menuHTML = self.getMenuHTML()
        
        pattern = '<li data-codename="([^"]+?)"><a href="/filmy/(%s,[^"^,^/]+?)">([^<]+?)</a></li>' % cat
        match = re.compile( pattern ).findall( menuHTML )
        if len(match) > 0:
            for i in range(len(match)):
                params = {'type': 'category', 'name': 'sub-category', 'page': self.VIDEOS_URL + (match[i][1]).replace(',', '%2C'), 'title': match[i][2]}
                self.currList.append( params )

    def getVideoUrl(self, url):
        printDBG("getVideoUrl url[%s]" % url)
        linksTab = []
        sts, data = self.cm.getPage(url)
        if not sts:
            printDBG("getVideoUrl except")
            return linksTab
        
        match = re.search( '{"file":"([^"]+?.mp4)"}', data )
        if match: 
            linksTab.append( {'name': 'mp4', 'url': match.group(1)} )
        match = re.search( '{"file":"([^"]+?.m3u8)"}', data )
        if match: 
            m3u8Tab = getDirectM3U8Playlist( match.group(1))
            linksTab.extend(m3u8Tab)
        return linksTab

    def getVideosList(self, url):
        printDBG("getVideosList url[%s]" % url)
        sts, data = self.cm.getPage(url)
        if not sts:
            printDBG("getVideosList except")
            return
        
        # get pagination HTML part
        nextPageData = CParsingHelper.getDataBeetwenMarkers(data, 'class="pager"', '</div>', False)[1]
        # get Video HTML part
        data = CParsingHelper.getDataBeetwenMarkers(data, '<!-- ************ end user menu ************ -->', '</ul>', False)[1].split('<li>')
        del data[0]
        
        for videoItemData in data:
            printDBG('                              videoItemData')
            icon     = ''
            duration = ''
            gatunek  = ''
            plot     = ''
            title    = ''
            url      = ''
            
            if 'class="playIcon"' in videoItemData:
                # get icon src
                match = re.search('src="(http://[^"]+?)"', videoItemData)
                if match: icon = match.group(1).replace('&amp;', '&')
                # get duration
                match = re.search('class="duration"[^>]*?>([^<]+?)<', videoItemData)
                if match: duration = match.group(1).replace('&#39;', "'")
                # get gatunek
                match = re.search('"gatunek"[^>]*?>([^<]+?)<', videoItemData)
                if match: gatunek = match.group(1)
                # get plot
                match = re.search('class="text"[^>]*?>([^<]+?)<', videoItemData)
                if match: plot = match.group(1)
                # get title and url
                match = re.search('<a href="([^"]+?)" class="title"[^>]*?>([^<]+?)</a>', videoItemData)
                if match:
                    url   = self.MAIN_URL + match.group(1)
                    title = match.group(2)
                    params = {'type': 'video', 'page': url, 'title': title, 'icon': icon, 'duration': duration, 'gatunek': gatunek, 'plot': plot}
                    self.currList.append( params )

        # check next page
        nextPageUrl = ''
        match = re.search('href="([^"]+?)" class="nextPage"', nextPageData)
        if match: 
            nextPageUrl = match.group(1)
        else:
            match = re.search('href="([^"]+?)" class="lastPage"', nextPageData)
            if match:
                nextPageUrl = match.group(1)

        if '' != nextPageUrl:
            params = {'type': 'category', 'name': 'sub-category', 'page': self.MAIN_URL + nextPageUrl.replace('&amp;', '&'), 'title': 'Następna strona'}
            self.currList.append( params )
    # end getVideosList
    
    def listsHistory(self):
            list = self.history.getHistoryList()
            for item in list:
                params = { 'type': 'category', 'name': 'history', 'category': 'Wyszukaj', 'title': item, 'plot': 'Szukaj: "%s"' % item, 'icon': ''}
                self.currList.append( 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 = []

    #MAIN MENU
        if name == None:
            self.listsMainMenu(self.MENU_TAB)
    #WSZYSTKIE
        elif category == self.setTable()[1]:
            self.getVideosList(self.VIDEOS_URL)
    #KATEGORIE
        elif category == self.setTable()[2]:
            self.getMainCategory()
    #SUB-KATEGORIE
        elif name == 'main-category':
            self.getSubCategory(page)
        elif name == 'sub-category':
            self.getVideosList(page)
    #WYSZUKAJ
        elif category == self.setTable()[3]:
            text = searchPattern
            self.getVideosList(self.SEARCH_URL + urllib.quote_plus(text))
    #HISTORIA WYSZUKIWANIA
        elif category == self.setTable()[4]:
            self.listsHistory()
    #WRONG WAY
        else:
            printDBG('handleService WRONG WAY')
class Wgrane:
    MAINURL = 'http://www.wgrane.pl'
    CAT_URL = MAINURL + '/categories.html'
    VID_URL = MAINURL + '/watch.html?category=%s&sort=%s&page=%s'
    SEARCH_URL = MAINURL + '/szukaj/'

    SERVICE_MENU_TABLE = {
        1: "Kategorie",
        2: "Wyszukaj",
        3: "Historia wyszukiwania"
    }

    SORT_FILTERS_TABLE = [{
        'title': 'Ostatnio dodane',
        'sort': ''
    }, {
        'title': 'Najczęściej oglądane',
        'sort': 'views'
    }, {
        'title': 'Najwyżej oceniane',
        'sort': 'points'
    }, {
        'title': 'Najczęściej komentowane',
        'sort': 'comments'
    }, {
        'title': 'Ostatnio oglądane',
        'sort': 'recent'
    }]

    def __init__(self):
        self.up = urlparser.urlparser()
        self.cm = common()
        self.history = CSearchHistoryHelper('Wgrane')
        # temporary data
        self.currList = []
        self.currItem = {}

    def getCurrList(self):
        return self.currList

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

    def getCurrItem(self):
        return self.currItem

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

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

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

    def setTable(self):
        return self.SERVICE_MENU_TABLE

    def listsMainMenu(self, table):
        for num, val in table.items():
            params = {'name': 'main-menu', 'title': val, 'category': val}
            self.addDir(params)

    def listCategories(self, url, cat):
        printDBG("listCategories for url[%s] cat[%s]" % (url, cat))
        # add all item
        params = {'category': cat, 'title': '--Wszystkie--', 'cat_id': ''}
        self.addDir(params)

        sts, data = self.cm.getPage(url)
        if not sts: return
        sts, data = CParsingHelper.getDataBeetwenMarkers(
            data, "<div class='window_title'>", "<div class='footer'>")
        if not sts: return False
        data = data.split("<div class='list_title'>")
        if len(data) > 1:
            del data[0]
            for item in data:
                # cat_id: match.group(2) & title: match.group(1) & img: self.MAINURL + match.group(3)
                match = re.search(
                    "<b>([^<]+?)</b></a></div><a href='[^']*?category=([0-9]+?)'><img[^>]*?src='([^']+?)'",
                    item)
                if not match: continue
                # plot
                printDBG('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA: [%s]' %
                         match.group(2))
                plot = CParsingHelper.removeDoubles(
                    remove_html_markup(item, ' ').replace(match.group(1), ''),
                    ' ')
                params = {
                    'category': cat,
                    'title': match.group(1),
                    'cat_id': match.group(2),
                    'icon': self.MAINURL + "/" + match.group(3),
                    'plot': plot
                }
                self.addDir(params)

    def listFilters(self, table, cat, cat_id, icon):
        printDBG("listFilters for cat[%s] cat_id[%s]" % (cat, cat_id))
        for item in table:
            item['category'] = cat
            item['cat_id'] = cat_id
            item['icon'] = icon
            self.addDir(item)

    def listVideos(self, baseUrl, cat, cat_id, sort, page, search_pattern=''):
        url = baseUrl % (cat_id, sort, page)
        printDBG("listVideos for url[%s]" % url)

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

        nextPage = False
        if -1 < data.find("class='black'>&raquo;</a>"):
            nextPage = True

        sts, data = CParsingHelper.getDataBeetwenMarkers(
            data, "<div class='window_title'>", "<div class='footer'>")
        if not sts: return False
        data = data.split("<div class='list' style='width: 173px;'>")
        if len(data) > 1:
            del data[0]
            for item in data:
                # vid_hash & img
                match = re.search(
                    "href='([0-9a-fA-F]{32})'[^>]*?><img[^>]*?src='([^']+?)'",
                    item)
                if not match: continue
                vid_hash = match.group(1)
                img = self.MAINURL + "/" + match.group(2)
                if not match: continue
                # title
                match = re.search(
                    "<div class='list_title'><a href='%s'>([^<]+?)</a></div>" %
                    vid_hash, item)
                if not match: continue
                title = match.group(1)
                # plot
                plot = CParsingHelper.removeDoubles(
                    remove_html_markup(item, ' ').replace(title, ''), ' ')

                params = {
                    'title': title,
                    'url': self.MAINURL + "/" + vid_hash,
                    'icon': img,
                    'plot': plot
                }
                self.playVideo(params)

        if nextPage:
            params = {
                'title': "Następna strona",
                'category': cat,
                'cat_id': cat_id,
                'sort': sort,
                'page': str(int(page) + 1),
                'search_pattern': search_pattern
            }
            self.addDir(params)

    def getSearchResult(self, baseUrl, cat, page):
        printDBG("getSearchResult for url[%s] page[%s]" % (baseUrl, page))

        if 1 < int(page) != '1': url = baseUrl + page
        else: url = baseUrl
        sts, data = self.cm.getPage(url)
        if not sts: return

        nextPage = False
        if -1 < data.find("class='pagination_next'"):
            nextPage = True

        sts, data = self.getDataBeetwenMarkers(data,
                                               '<td valign="top">',
                                               '<div class="menu_dol">',
                                               withMarkers=False)
        if not sts: return

        data = data.split('<td valign="top">')
        for item in data:
            # url & title
            match = re.search(
                '<div class="video_title">[^<]*?<a href="([^"]+?)">([^<]+?)</a>',
                item)
            if match:
                url = match.group(1)
                title = match.group(2)
            else:
                continue
            # img
            match = re.search('src="([^"]+?)"', item)
            if match: img = match.group(1)
            else: img = ''
            # plot
            match = re.search('<div class="video_details">(.+?)</td>', item,
                              re.DOTALL)
            if match:
                plot = remove_html_markup(
                    match.group(1))  #.replace("</div>", " ")
            else:
                plot = ''

            params = {'title': title, 'url': url, 'icon': img, 'plot': plot}
            self.playVideo(params)

        if nextPage:
            params = {
                'title': "Następna strona",
                'url': baseUrl,
                'category': cat,
                'page': str(int(page) + 1)
            }
            self.addDir(params)

    def listsHistory(self):
        list = self.history.getHistoryList()
        for item in list:
            params = {
                'name': 'history',
                'category': 'Wyszukaj',
                'title': item,
                'plot': 'Szukaj: "%s"' % item
            }
            self.addDir(params)

    def getHostingTable(self, url):
        printDBG("getHostingTable for url[%s]" % url)

        directUrl = self.up.getVideoLink(url)
        if directUrl:
            return [{'name': self.up.getHostName(url), 'url': directUrl}]
        else:
            return []

    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", '1')
        icon = self.currItem.get("icon", '')
        url = self.currItem.get("url", '')
        cat_id = self.currItem.get("cat_id", '')
        sort = self.currItem.get("sort", '')
        search_pattern = self.currItem.get("search_pattern", '')
        printDBG(
            "handleService: |||||||||||||||||||||||||||||||||||| name[%s], category[%s] "
            % (name, category))
        self.currList = []

        #MAIN MENU
        if name == None:
            self.listsMainMenu(self.SERVICE_MENU_TABLE)
    #KATEGORIE
        elif category == "Kategorie":
            self.listCategories(self.CAT_URL, 'add_filter')
        elif category == "add_filter":
            self.listFilters(self.SORT_FILTERS_TABLE, "video_category", cat_id,
                             icon)
        elif category == "video_category":
            self.listVideos(self.VID_URL, category, cat_id, sort, page)
    #WYSZUKAJ
        elif category == "Wyszukaj":
            pattern = searchPattern.replace(" ", "+")
            self.listVideos(self.VID_URL + "&search=" + pattern, "search_next",
                            '', '', page, pattern)
        elif category == "search_next":
            pattern = search_pattern
            self.listVideos(self.VID_URL + "&search=" + pattern, "search_next",
                            '', '', page, pattern)

    #HISTORIA WYSZUKIWANIA
        elif category == "Historia wyszukiwania":
            self.listsHistory()
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 ''
Exemple #18
0
class TSCBaseHostClass:
    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

    def getPage(self, baseUrl, addParams={}, post_data=None):
        baseUrl = self.std_url(baseUrl)
        if addParams == {}: addParams = dict(self.defaultParams)
        return self.cm.getPage(baseUrl, addParams, post_data)

    def get_url_page(self, url, page, type_=1):
        if page > 1:
            if type_ == 1:
                url = url + '/page/' + str(page)
                url = url.replace('//page', '/page')
        return url

    def start(self, cItem):
        mode = cItem.get('mode', None)
        if mode == '00':
            self.showmenu(cItem)
        elif mode == '10':
            self.showmenu1(cItem)
        elif mode == '20':
            self.showitms(cItem)
        elif mode == '21':
            self.showelms(cItem)
        return True

    def add_menu(self,
                 cItem,
                 pat1,
                 pat2,
                 data,
                 mode,
                 del_=[],
                 TAB=[],
                 search=False,
                 Titre='',
                 ord=[0, 1],
                 Desc=[],
                 Next=[0, 0],
                 u_titre=False,
                 ind_0=0,
                 local=[],
                 resolve='0',
                 EPG=False,
                 corr_=True):
        page = cItem.get('page', 1)
        data_out = ''
        found = False
        TAB0 = []
        if TAB != []:
            for (titre, url, mode, sub_mode) in TAB:
                if url.startswith('/'): url = self.MAIN_URL + url
                self.addDir({
                    'category': 'host2',
                    'title': titre,
                    'mode': mode,
                    'sub_mode': sub_mode,
                    'url': url,
                    'import': cItem['import'],
                    'icon': cItem['icon']
                })
        else:
            if data == '':
                sts, data = self.getPage(cItem.get('url', self.MAIN_URL))
                if not sts: data = ''
            if pat1 != '':
                data0 = re.findall(pat1, data, re.S)
            else:
                data0 = [
                    data,
                ]
            if data0:
                if len(data0) > ind_0:
                    if pat2 != '':
                        data1 = re.findall(pat2, data0[ind_0], re.S)
                    else:
                        data1 = [
                            data0[ind_0],
                        ]
                    if data1 and (Titre != ''):
                        self.addMarker({
                            'title': tscolor('\c00????30') + Titre,
                            'icon': cItem['icon']
                        })
                    if mode == 'desc':
                        desc = ''
                        for (tag, pat, frst, Del_) in Desc:
                            printDBG('pat=' + str(pat))
                            if desc == '': frst = ''
                            elif frst == '': frst = ' | '
                            if data1:
                                desc_ = re.findall(pat, data1[0], re.S)
                                if desc_:
                                    printDBG('1')
                                    if ((Del_ == '')
                                            or ((Del_ != '') and
                                                (Del_.lower()
                                                 not in desc_[0].lower()))):
                                        printDBG('2')
                                        if self.cleanHtmlStr(
                                                desc_[0]).strip() != '':
                                            desc = desc + frst + tscolor(
                                                '\c00????00'
                                            ) + tag + ': ' + tscolor(
                                                '\c00??????'
                                            ) + self.cleanHtmlStr(desc_[0])
                        return desc
                    for elm in data1:
                        if len(ord) == 2:
                            if mode.startswith('data_out'):
                                url = elm[ord[0]]
                                titre = elm[ord[1]]
                                image = cItem.get('icon', '')
                                desc = cItem.get('desc', '')
                                data_out = elm[2]
                                printDBG('data_out1=' + data_out)
                            else:
                                url = elm[ord[0]]
                                titre = elm[ord[1]]
                                image = cItem.get('icon', '')
                                desc = cItem.get('desc', '')
                        elif len(ord) == 3:
                            url = elm[ord[0]]
                            titre = elm[ord[1]]
                            image = self.std_url(elm[ord[2]])
                            desc = cItem.get('desc', '')
                        elif len(ord) > 3:
                            url = elm[ord[0]]
                            titre = elm[ord[1]]
                            image = self.std_url(elm[ord[2]])
                            x = range(3, len(ord))
                            printDBG('x=' + str(x))
                            desc0 = ''
                            for i in x:
                                desc0 = desc0 + elm[ord[i]]
                            desc = ''
                            printDBG('desc0=' + str(desc0))
                            for (tag, pat, frst, Del_) in Desc:
                                printDBG('pat=' + str(pat))
                                if desc == '': frst = ''
                                elif frst == '': frst = ' | '
                                desc_ = re.findall(pat, desc0, re.S)
                                if desc_:
                                    printDBG('1')
                                    if ((Del_ == '')
                                            or ((Del_ != '') and
                                                (Del_.lower()
                                                 not in desc_[0].lower()))):
                                        printDBG('2')
                                        desc = desc + frst + tscolor(
                                            '\c00????00'
                                        ) + tag + ': ' + tscolor(
                                            '\c00??????') + self.cleanHtmlStr(
                                                desc_[0])
                        if corr_:
                            if url.startswith('http'): url = url
                            elif url.startswith('/'): url = self.MAIN_URL + url
                            else: url = self.MAIN_URL + '/' + url
                        if mode == 'serv':
                            Local = ''
                            for elm in local:
                                URL = url
                                if resolve == '1': URL = 'hst#tshost#' + url
                                if elm[0] in url:
                                    Local = 'local'
                                    titre = '|Local| ' + elm[1]
                                    if elm[2] == '1': URL = 'hst#tshost#' + url
                                    else: URL = url
                            TAB0.append({
                                'name': self.cleanHtmlStr(titre),
                                'url': URL,
                                'need_resolve': 1,
                                'type': Local
                            })
                        elif mode.startswith('link'):
                            if mode == 'link4':
                                TAB0.append((titre + '|' + url, '4'))
                        else:
                            titre = self.cleanHtmlStr(titre)
                            if not any(word in titre for word in del_):
                                if u_titre:
                                    desc1, titre = self.uniform_titre(titre)
                                    desc = desc1 + desc
                                if titre != '':
                                    if mode == 'video':
                                        found = True
                                        self.addVideo({
                                            'category': 'host2',
                                            'title': titre,
                                            'url': url,
                                            'desc': desc,
                                            'import': cItem['import'],
                                            'icon': image,
                                            'hst': 'tshost',
                                            'EPG': EPG
                                        })
                                    else:
                                        self.addDir({
                                            'category':
                                            'host2',
                                            'title':
                                            titre,
                                            'mode':
                                            mode.replace('data_out:', ''),
                                            'url':
                                            url,
                                            'desc':
                                            desc,
                                            'import':
                                            cItem['import'],
                                            'icon':
                                            image,
                                            'hst':
                                            'tshost',
                                            'EPG':
                                            EPG,
                                            'data_out':
                                            data_out
                                        })
                    if Next[0] == 1:
                        self.addDir({
                            'import': cItem['import'],
                            'name': 'categories',
                            'category': 'host2',
                            'url': cItem['url'],
                            'title': 'Page Suivante',
                            'page': page + 1,
                            'desc': 'Page Suivante',
                            'icon': cItem['icon'],
                            'mode': Next[1]
                        })
                    elif Next[0] != 0:
                        next_ = re.findall(Next[0], data, re.S)
                        if next_:
                            URL_ = next_[0]
                            if corr_:
                                if URL_.startswith('http'): URL_ = URL_
                                elif URL_.startswith('/'):
                                    URL_ = self.MAIN_URL + URL_
                                else:
                                    URL_ = self.MAIN_URL + '/' + URL_
                            self.addDir({
                                'import': cItem['import'],
                                'name': 'categories',
                                'category': 'host2',
                                'url': URL_,
                                'title': 'Page Suivante',
                                'page': 1,
                                'desc': 'Page Suivante',
                                'icon': cItem['icon'],
                                'mode': Next[1]
                            })
            if (mode == 'video') and (not found):
                self.addVideo({
                    'category': 'host2',
                    'title': cItem['title'],
                    'url': cItem['url'],
                    'desc': cItem['desc'],
                    'import': cItem['import'],
                    'icon': cItem['icon'],
                    'hst': 'tshost',
                    'EPG': EPG
                })
        if search:
            self.addDir({
                'category': 'search',
                'title': tscolor('\c00????30') + _('Search'),
                'search_item': True,
                'page': 1,
                'hst': 'tshost',
                'import': cItem['import'],
                'icon': cItem['icon']
            })
        return (data, TAB0)

    def std_host_name(self, name_, direct=False):
        if '|' in name_:
            n1 = name_.split('|')[-1]
            n2 = name_.replace(name_.split('|')[-1], '')
            if direct == 'direct':
                name_ = n2 + tscolor('\c0090??20') + n1.replace('embed.',
                                                                '').title()
            elif self.ts_urlpars.checkHostSupportbyname(n1):
                name_ = n2 + tscolor('\c0090??20') + n1.replace('embed.',
                                                                '').title()
            elif self.ts_urlpars.checkHostNotSupportbyname(n1):
                name_ = n2 + tscolor('\c00??1020') + n1.replace('embed.',
                                                                '').title()
            else:
                name_ = n2 + tscolor('\c00999999') + n1.replace('embed.',
                                                                '').title()
        else:
            if direct == 'direct':
                name_ = tscolor('\c0090??20') + name_.replace('embed.',
                                                              '').title()
            elif self.ts_urlpars.checkHostSupportbyname(name_):
                name_ = tscolor('\c0090??20') + name_.replace('embed.',
                                                              '').title()
            elif self.ts_urlpars.checkHostNotSupportbyname(name_):
                name_ = tscolor('\c00??5050') + name_.replace('embed.',
                                                              '').title()

        return name_

    def std_url(self, url):
        url1 = url
        printDBG('url0=' + url1)
        url1 = url1.replace('://', 'rgy11soft')
        url1 = url1.replace('?', 'rgy22soft')
        url1 = url1.replace('&', 'rgy33soft')
        url1 = url1.replace('=', 'rgy44soft')
        url1 = urllib.unquote(url1)
        url1 = urllib.quote(url1)
        url1 = url1.replace('rgy11soft', '://')
        url1 = url1.replace('rgy22soft', '?')
        url1 = url1.replace('rgy33soft', '&')
        url1 = url1.replace('rgy44soft', '=')
        printDBG('url1=' + url1)
        return url1

    def uniform_titre(self, titre, year_op=0):
        titre = titre.replace('مشاهدة وتحميل مباشر',
                              '').replace('مشاهدة',
                                          '').replace('اون لاين', '')
        tag_type = [
            'مدبلج للعربية', 'مترجمة للعربية', 'مترجم للعربية', 'مدبلجة',
            'مترجمة', 'مترجم', 'مدبلج', 'مسلسل', 'عرض', 'انمي', 'فيلم'
        ]
        tag_qual = [
            '1080p', '720p', 'WEB-DL', 'BluRay', 'DVDRip', 'HDCAM', 'HDTC',
            'HDRip', 'HD', '1080P', '720P', 'DVBRip', 'TVRip', 'DVD', 'SD'
        ]
        tag_saison = [('الموسم الثاني', '02'), ('الموسم الاول', '01'),
                      ('الموسم الثالث', '03'), ('الموسم الرابع', '04'),
                      ('الموسم الخامس', '05'), ('الموسم السادس', '06'),
                      ('الموسم السابع', '07'), ('الموسم الثامن', '08'),
                      ('الموسم التاسع', '09'), ('الموسم العاشر', '10')]
        type_ = tscolor('\c00????00') + 'Type: ' + tscolor('\c00??????')
        qual = tscolor('\c00????00') + 'Quality: ' + tscolor('\c00??????')
        sais = tscolor('\c00????00') + 'Saison: ' + tscolor('\c00??????')
        desc = ''
        saison = ''

        for elm in tag_saison:
            if elm[0] in titre:
                sais = sais + elm[1]
                titre = titre.replace(elm[0], '')
                break

        for elm in tag_type:
            if elm in titre:
                titre = titre.replace(elm, '')
                type_ = type_ + elm + ' | '
        for elm in tag_qual:
            if elm in titre:
                #re_st = re.compile(re.escape(elm.lower()), re.IGNORECASE)
                #titre=re_st.sub('', titre)
                titre = titre.replace(elm, '')
                qual = qual + elm + ' | '

        data = re.findall('((19|20)\d{2})', titre, re.S)
        if data:
            year_ = data[0][0]
            year_out = tscolor('\c0000????') + data[0][0] + tscolor(
                '\c00??????')
            if year_op == 0:
                titre = year_out + '  ' + titre.replace(year_, '')
                desc = tscolor('\c00????00') + 'Year: ' + tscolor(
                    '\c00??????') + year_ + '\n'
            elif year_op == -1:
                titre = year_out + '  ' + titre.replace(year_, '')
                desc = ''
            elif year_op == 1:
                titre = titre.replace(year_, '')
                desc = tscolor('\c00????00') + 'Year: ' + tscolor(
                    '\c00??????') + year_ + '\n'
            elif year_op == 2:
                titre = titre.replace(year_, '')
                desc = year_

        if year_op < 2:
            if sais != tscolor('\c00????00') + 'Saison: ' + tscolor(
                    '\c00??????'):
                desc = desc + sais + '\n'
            if type_ != tscolor('\c00????00') + 'Type: ' + tscolor(
                    '\c00??????'):
                desc = desc + type_[:-3] + '\n'
            if qual != tscolor('\c00????00') + 'Quality: ' + tscolor(
                    '\c00??????'):
                desc = desc + qual[:-3] + '\n'

        pat = 'موسم.*?([0-9]{1,2}).*?حلقة.*?([0-9]{1,2})'
        data = re.findall(pat, titre, re.S)
        if data:
            sa = data[0][0]
            ep = data[0][1]
            if len(sa) == 1: sa = '0' + sa
            if len(ep) == 1: ep = '0' + ep
            ep_out = tscolor('\c0000????') + 'S' + sa + tscolor(
                '\c0000????') + 'E' + ep + tscolor('\c00??????')
            titre = ep_out + ' ' + re.sub(pat, '', titre)

        return desc, self.cleanHtmlStr(titre).replace('()', '').strip()

    def informAboutGeoBlockingIfNeeded(self, country, onlyOnce=True):
        try:
            if onlyOnce and self.isGeoBlockingChecked: return
        except Exception:
            self.isGeoBlockingChecked = False
        sts, data = self.cm.getPage(
            'https://dcinfos.abtasty.com/geolocAndWeather.php')
        if not sts: return
        try:
            data = json_loads(data.strip()[1:-1], '', True)
            if data['country'] != country:
                message = _(
                    '%s uses "geo-blocking" measures to prevent you from accessing the services from outside the %s Territory.'
                )
                GetIPTVNotify().push(message % (self.getMainUrl(), country),
                                     'info', 5)
            self.isGeoBlockingChecked = True
        except Exception:
            printExc()

    def listsTab(self, tab, cItem, type='dir'):
        defaultType = type
        for item in tab:
            params = dict(cItem)
            params.update(item)
            params['name'] = 'category'
            type = item.get('type', defaultType)
            if type == 'dir': self.addDir(params)
            elif type == 'marker': self.addMarker(params)
            else: self.addVideo(params)

    def listSubItems(self, cItem):
        printDBG("TSCBaseHostClass.listSubItems")
        self.currList = cItem['sub_items']

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

    def getMainUrl(self):
        return self.MAIN_URL

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

    def getFullUrl(self, url, currUrl=None):
        if currUrl == None or not self.cm.isValidUrl(currUrl):
            try:
                currUrl = self.getMainUrl()
            except Exception:
                currUrl = None
            if currUrl == None or not self.cm.isValidUrl(currUrl):
                currUrl = 'http://fake/'
        return self.cm.getFullUrl(url, currUrl)

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

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

    @staticmethod
    def cleanHtmlStr(str):
        return CParsingHelper.cleanHtmlStr(str)

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

    def getCurrList(self):
        return self.currList

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

    def getCurrItem(self):
        return self.currItem

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

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

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

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

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

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

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

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

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

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

    def getFavouriteData(self, cItem):
        try:
            return json_dumps(cItem)
        except Exception:
            printExc()
        return ''

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

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

    def getLinksForItem(self, cItem):
        # for backward compatibility
        return self.getLinksForVideo(cItem)

    def markSelectedLink(self, cacheLinks, linkId, keyId='url', marker="*"):
        # mark requested link as used one
        if len(cacheLinks.keys()):
            for key in cacheLinks:
                for idx in range(len(cacheLinks[key])):
                    if linkId in cacheLinks[key][idx][keyId]:
                        if not cacheLinks[key][idx]['name'].startswith(marker):
                            cacheLinks[key][idx]['name'] = marker + cacheLinks[
                                key][idx]['name'] + marker
                        break

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

    def endHandleService(self, index, refresh):
        if 2 == refresh:  # refresh for more items
            currList = self.currList
            self.currList = self.beforeMoreItemList
            for item in currList:
                if 'more' == item['type'] or (
                        item not in self.beforeMoreItemList
                        and item not in self.afterMoreItemList):
                    self.currList.append(item)
            self.currList.extend(self.afterMoreItemList)
            self.beforeMoreItemList = []
            self.afterMoreItemList = []
        self.moreMode = False
class Wgrane:
    MAINURL = 'http://www.wgrane.pl'
    CAT_URL = MAINURL + '/categories.html'
    VID_URL = MAINURL + '/watch.html?category=%s&sort=%s&page=%s'
    SEARCH_URL = MAINURL + '/szukaj/'

    SERVICE_MENU_TABLE = {
        1: "Kategorie",
        2: "Wyszukaj",
        3: "Historia wyszukiwania"
    }
    
    SORT_FILTERS_TABLE = [{'title':'Ostatnio dodane',         'sort':''        },
                          {'title':'Najczęściej oglądane',    'sort':'views'   },
                          {'title':'Najwyżej oceniane',       'sort':'points'  },
                          {'title':'Najczęściej komentowane', 'sort':'comments'},
                          {'title':'Ostatnio oglądane',       'sort':'recent'  }]
 
    def __init__(self):
        self.up = urlparser.urlparser()
        self.cm = common()
        self.history = CSearchHistoryHelper('Wgrane')
        # temporary data
        self.currList = []
        self.currItem = {}

    def getCurrList(self):
        return self.currList

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

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

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

    def listsMainMenu(self, table):
        for num, val in table.items():
            params = {'name': 'main-menu', 'title': val, 'category': val}
            self.addDir(params)
            
    def listCategories(self, url, cat):
        printDBG("listCategories for url[%s] cat[%s]" % (url, cat))
        # add all item
        params = {'category': cat, 'title': '--Wszystkie--' , 'cat_id': ''}
        self.addDir(params)

        sts, data = self.cm.getPage(url)
        if not sts: return
        sts, data = CParsingHelper.getDataBeetwenMarkers(data, "<div class='window_title'>", "<div class='footer'>")
        if not sts: return False
        data = data.split("<div class='list_title'>")
        if len(data) > 1:
            del data[0]
            for item in data:
                # cat_id: match.group(2) & title: match.group(1) & img: self.MAINURL + match.group(3)
                match = re.search("<b>([^<]+?)</b></a></div><a href='[^']*?category=([0-9]+?)'><img[^>]*?src='([^']+?)'", item)
                if not match: continue
                # plot
                printDBG('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA: [%s]' % match.group(2))
                plot = CParsingHelper.removeDoubles(remove_html_markup(item, ' ').replace(match.group(1), ''), ' ')
                params = {'category': cat, 'title': match.group(1) , 'cat_id': match.group(2) , 'icon': self.MAINURL + "/" + match.group(3), 'plot':plot}
                self.addDir(params)
                
    def listFilters(self, table, cat, cat_id, icon):
        printDBG("listFilters for cat[%s] cat_id[%s]" % (cat, cat_id))
        for item in table:
            item['category'] = cat
            item['cat_id'] = cat_id
            item['icon'] = icon
            self.addDir(item)
            
                    
    def listVideos(self, baseUrl, cat, cat_id, sort, page, search_pattern = ''):
        url = baseUrl % (cat_id, sort, page)
        printDBG("listVideos for url[%s]" % url)

        sts, data = self.cm.getPage(url)
        if not sts: return
        
        nextPage = False
        if -1 < data.find("class='black'>&raquo;</a>"):
            nextPage = True

        sts, data = CParsingHelper.getDataBeetwenMarkers(data, "<div class='window_title'>", "<div class='footer'>")
        if not sts: return False
        data = data.split("<div class='list' style='width: 173px;'>")
        if len(data) > 1:
            del data[0]
            for item in data:
                # vid_hash & img
                match = re.search("href='([0-9a-fA-F]{32})'[^>]*?><img[^>]*?src='([^']+?)'", item)
                if not match: continue
                vid_hash = match.group(1)
                img = self.MAINURL + "/" + match.group(2)
                if not match: continue
                # title
                match = re.search("<div class='list_title'><a href='%s'>([^<]+?)</a></div>" % vid_hash, item)
                if not match: continue
                title = match.group(1)
                # plot
                plot = CParsingHelper.removeDoubles(remove_html_markup(item, ' ').replace(title, ''), ' ')
            
                params = { 'title': title, 'url': self.MAINURL + "/" +vid_hash, 'icon': img, 'plot': plot}
                if 'Rozmiar:' in item:
                    continue
                else:
                    self.playVideo(params)
            
        if nextPage:
            params = {'title': "Następna strona", 'category': cat, 'cat_id':cat_id, 'sort':sort, 'page':str(int(page)+1), 'search_pattern':search_pattern}
            self.addDir(params)
        
    def getSearchResult(self, baseUrl, cat, page):
        printDBG("getSearchResult for url[%s] page[%s]" % (baseUrl, page))
        
        if 1 < int(page) != '1': url = baseUrl + page
        else: url = baseUrl
        sts, data = self.cm.getPage(url)
        if not sts: return
        
        nextPage = False
        if -1 < data.find("class='pagination_next'"):
            nextPage = True

        sts, data = self.getDataBeetwenMarkers(data, '<td valign="top">', '<div class="menu_dol">', withMarkers = False)
        if not sts: return
      
        data = data.split('<td valign="top">')
        for item in data:
            # url & title
            match = re.search('<div class="video_title">[^<]*?<a href="([^"]+?)">([^<]+?)</a>', item)
            if match: 
                url = match.group(1)
                title = match.group(2)
            else: continue
            # img
            match = re.search('src="([^"]+?)"', item)
            if match: img = match.group(1)
            else: img = ''
            # plot
            match = re.search('<div class="video_details">(.+?)</td>', item, re.DOTALL)
            if match: plot = remove_html_markup(match.group(1)) #.replace("</div>", " ")
            else: plot = ''
            
            params = { 'title': title, 'url': url, 'icon': img, 'plot': plot}
            if 'Rozmiar:' in item:
                continue
            else:
                self.playVideo(params)
            
        if nextPage:
            params = {'title': "Następna strona", 'url': baseUrl, 'category': cat, 'page':str(int(page)+1)}
            self.addDir(params)
                
    def listsHistory(self):
        list = self.history.getHistoryList()
        for item in list:
            params = { 'name': 'history', 'category': 'Wyszukaj', 'title': item, 'plot': 'Szukaj: "%s"' % item}
            self.addDir(params)

    def getHostingTable(self, url):
        printDBG("getHostingTable for url[%s]" % url)
        
        directUrl = self.up.getVideoLink(url)
        if directUrl:
            return [{'name': self.up.getHostName(url), 'url': directUrl}]
        else:
            return []

    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", '1')
        icon     = self.currItem.get("icon", '')
        url      = self.currItem.get("url", '')
        cat_id   = self.currItem.get("cat_id", '')
        sort     = self.currItem.get("sort", '')
        search_pattern = self.currItem.get("search_pattern", '') 
        printDBG( "handleService: |||||||||||||||||||||||||||||||||||| name[%s], category[%s] " % (name, category) )
        self.currList = []
        
    #MAIN MENU
        if name == None:
            self.listsMainMenu(self.SERVICE_MENU_TABLE)
    #KATEGORIE
        elif category == "Kategorie":
            self.listCategories(self.CAT_URL, 'add_filter')
        elif category == "add_filter":
            self.listFilters(self.SORT_FILTERS_TABLE, "video_category", cat_id, icon)
        elif category == "video_category":
            self.listVideos(self.VID_URL, category, cat_id, sort, page)
    #WYSZUKAJ
        elif category == "Wyszukaj":
            pattern = searchPattern.replace(" ", "+")
            self.listVideos(self.VID_URL + "&search=" + pattern, "search_next", '', '', page, pattern)
        elif category == "search_next":
            pattern = search_pattern
            self.listVideos(self.VID_URL + "&search=" + pattern, "search_next", '', '', page, pattern)
    #HISTORIA WYSZUKIWANIA
        elif category == "Historia wyszukiwania":
            self.listsHistory()
Exemple #20
0
class CBaseHostClass:
    def __init__(self, params={}):
        self.sessionEx = MainSessionWrapper() 
        self.up = urlparser()
        
        proxyURL = params.get('proxyURL', '')
        useProxy = params.get('useProxy', False)
        if 'MozillaCookieJar' == params.get('cookie_type', ''):
            self.cm = common(proxyURL, useProxy, True)
        else:
            self.cm = common(proxyURL, useProxy)

        self.currList = []
        self.currItem = {}
        if '' != params.get('history', ''):
            self.history = CSearchHistoryHelper(params['history'], params.get('history_store_type', False))
        if '' != params.get('cookie', ''):
            self.COOKIE_FILE = GetCookieDir(params['cookie'])
        self.moreMode = False
    
    def listsTab(self, tab, cItem, type='dir'):
        for item in tab:
            params = dict(cItem)
            params.update(item)
            params['name']  = 'category'
            if type == 'dir':
                self.addDir(params)
            else: self.addVideo(params)
    
    def getMainUrl(self):
        return self.MAIN_URL
    
    def getFullUrl(self, url):
        if url.startswith('//'):
            url = 'http:' + url
        elif url.startswith('://'):
            url = 'http' + url
        elif url.startswith('/'):
            url = self.getMainUrl() + url[1:]
        elif 0 < len(url) and '://' not in url:
            url =  self.getMainUrl() + url
        return url
        
    def getFullIconUrl(self, url):
        return url
        
    def getDefaulIcon(self, cItem=None):
        try: return self.DEFAULT_ICON_URL
        except Exception:
            pass
        return ''
    
    @staticmethod 
    def cleanHtmlStr(str):
        str = str.replace('<', ' <')
        str = str.replace('&nbsp;', ' ')
        str = str.replace('&nbsp', ' ')
        str = clean_html(str)
        str = str.replace('\n', ' ').replace('\r', ' ').replace('\t', ' ')
        return CParsingHelper.removeDoubles(str, ' ').strip()

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

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

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

    def addDir(self, params):
        params['type'] = 'category'
        self.currList.append(params)
        return
        
    def addMore(self, params):
        params['type'] = 'more'
        self.currList.append(params)
        return
        
    def addVideo(self, params):
        params['type'] = 'video'
        self.currList.append(params)
        return
        
    def addAudio(self, params):
        params['type'] = 'audio'
        self.currList.append(params)
        return
    
    def addPicture(self, params):
        params['type'] = 'picture'
        self.currList.append(params)
        return
  
    def addArticle(self, params):
        params['type'] = 'article'
        self.currList.append(params)
        return
    
    def listsHistory(self, baseItem={'name': 'history', 'category': 'Wyszukaj'}, desc_key='plot', desc_base=(_("Type: ")) ):
        list = self.history.getHistoryList()
        for histItem in list:
            plot = ''
            try:
                if type(histItem) == type({}):
                    pattern     = histItem.get('pattern', '')
                    search_type = histItem.get('type', '')
                    if '' != search_type: plot = desc_base + _(search_type)
                else:
                    pattern     = histItem
                    search_type = None
                params = dict(baseItem)
                params.update({'title': pattern, 'search_type': search_type,  desc_key: plot})
                self.addDir(params)
            except Exception: printExc()
            
    def setInitListFromFavouriteItem(self, fav_data):
        return False
    
    def handleService(self, index, refresh=0, searchPattern='', searchType=''):
        self.moreMode = False
        if 0 == refresh:
            if len(self.currList) <= index:
                return
            if -1 == index:
                self.currItem = { "name": None }
            else:
                self.currItem = self.currList[index]
        if 2 == refresh: # refresh for more items
            printDBG(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> endHandleService index[%s]" % index)
            # remove item more and store items before and after item more
            self.beforeMoreItemList = self.currList[0:index]
            self.afterMoreItemList = self.currList[index+1:]
            self.moreMode = True
            if -1 == index:
                self.currItem = { "name": None }
            else:
                self.currItem = self.currList[index]
    
    def endHandleService(self, index, refresh):
        if 2 == refresh: # refresh for more items
            currList = self.currList
            self.currList = self.beforeMoreItemList
            for item in currList:
                if 'more' == item['type'] or (item not in self.beforeMoreItemList and item not in self.afterMoreItemList):
                    self.currList.append(item)
            self.currList.extend(self.afterMoreItemList)
            self.beforeMoreItemList = []
            self.afterMoreItemList  = []
        self.moreMode = False
class AleKinoTV:
    MAINURL = 'http://www.mototube.pl'
    SEARCH_URL = MAINURL + '/szukaj/'

    SERVICE_MENU_TABLE = {
        1: "Kategorie",
        2: "Wyszukaj",
        3: "Historia wyszukiwania"
    }

    def __init__(self):
        self.up = urlparser.urlparser()
        self.cm = pCommon.common()
        self.history = CSearchHistoryHelper('MotoTube')
        # temporary data
        self.currList = []
        self.currItem = {}

    def getCurrList(self):
        return self.currList

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

    def getCurrItem(self):
        return self.currItem

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

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

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

    def fWrite(self, file, data):
        #helper to see html returned by ajax
        file_path = '/mnt/hdd/' + file
        text_file = open(file_path, "w")
        text_file.write(data)
        text_file.close()

    def getDataBeetwenMarkers(self, data, marker1, marker2, withMarkers=True):
        idx1 = data.find(marker1)
        if -1 == idx1: return False, None
        idx2 = data.find(marker2, idx1 + len(marker1))
        if -1 == idx2: return False, None

        if withMarkers:
            idx2 = idx2 + len(marker2)
        else:
            idx1 = idx1 + len(marker1)

        return True, data[idx1:idx2]

    def setTable(self):
        return self.SERVICE_MENU_TABLE

    def listsMainMenu(self, table):
        for num, val in table.items():
            params = {'name': 'main-menu', 'title': val, 'category': val}
            self.addDir(params)

    def listCategories(self, url, cat):
        printDBG("listCategories for url[%s] cat[%s]" % (url, cat))
        sts, data = self.cm.getPage(url)
        if not sts: return
        sts, data = self.getDataBeetwenMarkers(data,
                                               '<div class="submenu">',
                                               '</div>',
                                               withMarkers=False)
        if not sts: return
        match = re.compile(
            '<a class="submenu" href="([^"]+?)">([^<]+?)</a>').findall(data)
        if match:
            for i in range(len(match)):
                params = {
                    'title': match[i][1],
                    'url': match[i][0],
                    'category': cat,
                    'plot': match[i][0]
                }
                self.addDir(params)

    def listVideos(self, baseUrl, cat, page):
        printDBG("listVideos for url[%s] page[%s]" % (baseUrl, page))

        if 1 < int(page) != '1': url = baseUrl + page
        else: url = baseUrl
        sts, data = self.cm.getPage(url)
        if not sts: return

        nextPage = False
        if -1 < data.find("class='pagination_next'"):
            nextPage = True

        sts, data = self.getDataBeetwenMarkers(data,
                                               '<td class="video">',
                                               '</table>',
                                               withMarkers=False)
        if not sts: return

        data = data.split('<td class="video">')
        for item in data:
            # url & title
            match = re.search(
                'class="video_title"><a href="([^"]+?)">([^<]+?)</a>', item)
            if match:
                url = match.group(1)
                title = match.group(2)
            else:
                continue
            # img
            match = re.search('src="([^"]+?)"', item)
            if match: img = match.group(1)
            else: img = ''
            # plot
            match = re.search(
                '<p style="margin:5px;" class="video_details">(.+?)</p>', item,
                re.DOTALL)
            if match: plot = remove_html_markup(match.group(1))
            else: plot = ''

            params = {'title': title, 'url': url, 'icon': img, 'plot': plot}
            self.playVideo(params)

        if nextPage:
            params = {
                'title': "Następna strona",
                'url': baseUrl,
                'category': cat,
                'page': str(int(page) + 1)
            }
            self.addDir(params)

    def getSearchResult(self, baseUrl, cat, page):
        printDBG("getSearchResult for url[%s] page[%s]" % (baseUrl, page))

        if 1 < int(page) != '1': url = baseUrl + page
        else: url = baseUrl
        sts, data = self.cm.getPage(url)
        if not sts: return

        nextPage = False
        if -1 < data.find("class='pagination_next'"):
            nextPage = True

        sts, data = self.getDataBeetwenMarkers(data,
                                               '<td valign="top">',
                                               '<div class="menu_dol">',
                                               withMarkers=False)
        if not sts: return

        data = data.split('<td valign="top">')
        for item in data:
            # url & title
            match = re.search(
                '<div class="video_title">[^<]*?<a href="([^"]+?)">([^<]+?)</a>',
                item)
            if match:
                url = match.group(1)
                title = match.group(2)
            else:
                continue
            # img
            match = re.search('src="([^"]+?)"', item)
            if match: img = match.group(1)
            else: img = ''
            # plot
            match = re.search('<div class="video_details">(.+?)</td>', item,
                              re.DOTALL)
            if match:
                plot = remove_html_markup(
                    match.group(1))  #.replace("</div>", " ")
            else:
                plot = ''

            params = {'title': title, 'url': url, 'icon': img, 'plot': plot}
            self.playVideo(params)

        if nextPage:
            params = {
                'title': "Następna strona",
                'url': baseUrl,
                'category': cat,
                'page': str(int(page) + 1)
            }
            self.addDir(params)

    def listsHistory(self):
        list = self.history.getHistoryList()
        for item in list:
            params = {
                'name': 'history',
                'category': 'Wyszukaj',
                'title': item,
                'plot': 'Szukaj: "%s"' % item
            }
            self.addDir(params)

    def getHostingTable(self, url):
        printDBG("getHostingTable for url[%s]" % url)

        sts, data = self.cm.getPage(url)
        if not sts:
            return []
        #check for internal link
        match = re.search('addVariable\("file","\.\.([^"]+?)"', data)
        if match:
            directUrl = self.MAINURL + match.group(1)
            return [{'name': 'Internal_Link', 'url': directUrl}]
        #check for external link
        match = re.search('<embed src="([^"]+?)"', data)
        if match:
            return self.getLink(match.group(1))
        return []

    def getLink(self, url):
        printDBG('getLink for url[%s]' % (url))

        directUrl = self.up.getVideoLink(url)
        if directUrl:
            return [{'name': self.up.getHostName(url), 'url': directUrl}]
        else:
            return []

    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", '1')
        icon = self.currItem.get("icon", '')
        url = self.currItem.get("url", '')
        printDBG(
            "handleService: |||||||||||||||||||||||||||||||||||| name[%s], category[%s] "
            % (name, category))
        self.currList = []

        #MAIN MENU
        if name == None:
            self.listsMainMenu(self.SERVICE_MENU_TABLE)
    #KATEGORIE
        elif category == "Kategorie":
            self.listCategories(self.MAINURL + "/najnowsze/", 'video_category')
        elif category == "video_category":
            self.listVideos(url, category, page)
    #WYSZUKAJ
        elif category == "Wyszukaj":
            pattern = searchPattern.replace(" ", "-")
            self.getSearchResult(self.SEARCH_URL + pattern + "/",
                                 "search_next", page)
        elif category == "search_next":
            self.getSearchResult(url, "search_next", page)

    #HISTORIA WYSZUKIWANIA
        elif category == "Historia wyszukiwania":
            self.listsHistory()
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 ''
Exemple #23
0
class CBaseHostClass:
    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'], params.get('history_store_type', False))
        if '' != params.get('cookie', ''):
            self.COOKIE_FILE = GetCookieDir(params['cookie'])
        self.moreMode = False

    def informAboutGeoBlockingIfNeeded(self, country, onlyOnce=True):
        try:
            if onlyOnce and self.isGeoBlockingChecked: return
        except Exception:
            self.isGeoBlockingChecked = False
        sts, data = self.cm.getPage(
            'https://dcinfos.abtasty.com/geolocAndWeather.php')
        if not sts: return
        try:
            data = json_loads(data.strip()[1:-1], '', True)
            if data['country'] != country:
                message = _(
                    '%s uses "geo-blocking" measures to prevent you from accessing the services from abroad.\n Host country: %s, your country: %s'
                )
                GetIPTVNotify().push(
                    message % (self.getMainUrl(), country, data['country']),
                    'info', 5)
            self.isGeoBlockingChecked = True
        except Exception:
            printExc()

    def listsTab(self, tab, cItem, type='dir'):
        defaultType = type
        for item in tab:
            params = dict(cItem)
            params.update(item)
            params['name'] = 'category'
            type = item.get('type', defaultType)
            if type == 'dir': self.addDir(params)
            elif type == 'marker': self.addMarker(params)
            else: self.addVideo(params)

    def listSubItems(self, cItem):
        printDBG("CBaseHostClass.listSubItems")
        self.currList = cItem['sub_items']

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

    def getMainUrl(self):
        return self.MAIN_URL

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

    def getFullUrl(self, url, currUrl=None):
        if currUrl == None or not self.cm.isValidUrl(currUrl):
            try:
                currUrl = self.getMainUrl()
            except Exception:
                currUrl = None
            if currUrl == None or not self.cm.isValidUrl(currUrl):
                currUrl = 'http://fake/'
        return self.cm.getFullUrl(url, currUrl)

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

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

    @staticmethod
    def cleanHtmlStr(str):
        return CParsingHelper.cleanHtmlStr(str)

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

    def getCurrList(self):
        return self.currList

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

    def getCurrItem(self):
        return self.currItem

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

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

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

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

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

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

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

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

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

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

    def getFavouriteData(self, cItem):
        try:
            return json_dumps(cItem)
        except Exception:
            printExc()
        return ''

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

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

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

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

    def endHandleService(self, index, refresh):
        if 2 == refresh:  # refresh for more items
            currList = self.currList
            self.currList = self.beforeMoreItemList
            for item in currList:
                if 'more' == item['type'] or (
                        item not in self.beforeMoreItemList
                        and item not in self.afterMoreItemList):
                    self.currList.append(item)
            self.currList.extend(self.afterMoreItemList)
            self.beforeMoreItemList = []
            self.afterMoreItemList = []
        self.moreMode = False
class TSCBaseHostClass:
    def __init__(self, params={}):
        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))
        if '' != params.get('cookie', ''):
            self.COOKIE_FILE = GetCookieDir(params['cookie'])
        self.moreMode = False

    def std_host_name(self, name_, direct=False):
        if '|' in name_:
            n1 = name_.split('|')[-1]
            n2 = name_.replace(name_.split('|')[-1], '')
            if direct == 'direct':
                name_ = n2 + tscolor('\c0090??20') + n1.replace('embed.',
                                                                '').title()
            elif self.ts_urlpars.checkHostSupportbyname(n1):
                name_ = n2 + tscolor('\c0090??20') + n1.replace('embed.',
                                                                '').title()
            elif self.ts_urlpars.checkHostNotSupportbyname(n1):
                name_ = n2 + tscolor('\c00??1020') + n1.replace('embed.',
                                                                '').title()
            else:
                name_ = n2 + tscolor('\c00999999') + n1.replace('embed.',
                                                                '').title()
        else:
            if direct == 'direct':
                name_ = tscolor('\c0090??20') + name_.replace('embed.',
                                                              '').title()
            elif self.ts_urlpars.checkHostSupportbyname(name_):
                name_ = tscolor('\c0090??20') + name_.replace('embed.',
                                                              '').title()
            elif self.ts_urlpars.checkHostNotSupportbyname(name_):
                name_ = tscolor('\c00??5050') + name_.replace('embed.',
                                                              '').title()

        return name_

    def uniform_titre(self, titre, year_op=0):
        titre = titre.replace('مشاهدة وتحميل مباشر',
                              '').replace('مشاهدة',
                                          '').replace('اون لاين', '')
        tag_type = [
            'مدبلج للعربية', 'مدبلجة', 'مترجمة', 'مترجم', 'مدبلج', 'مسلسل',
            'عرض', 'انمي', 'فيلم'
        ]
        tag_qual = [
            '1080p', '720p', 'WEB-DL', 'BluRay', 'DVDRip', 'HDCAM', 'HDTC',
            'HDRip', 'HD', '1080P', '720P', 'DVBRip', 'TVRip', 'DVD', 'SD'
        ]
        tag_saison = [('الموسم الثاني', '02'), ('الموسم الاول', '01'),
                      ('الموسم الثالث', '03'), ('الموسم الرابع', '04'),
                      ('الموسم الخامس', '05'), ('الموسم السادس', '06'),
                      ('الموسم السابع', '07'), ('الموسم الثامن', '08'),
                      ('الموسم التاسع', '09'), ('الموسم العاشر', '10')]
        type_ = tscolor('\c00????00') + 'Type: ' + tscolor('\c00??????')
        qual = tscolor('\c00????00') + 'Quality: ' + tscolor('\c00??????')
        sais = tscolor('\c00????00') + 'Saison: ' + tscolor('\c00??????')
        desc = ''
        saison = ''

        for elm in tag_saison:
            if elm[0] in titre:
                sais = sais + elm[1]
                titre = titre.replace(elm[0], '')
                break

        for elm in tag_type:
            if elm in titre:
                titre = titre.replace(elm, '')
                type_ = type_ + elm + ' | '
        for elm in tag_qual:
            if elm in titre:
                #re_st = re.compile(re.escape(elm.lower()), re.IGNORECASE)
                #titre=re_st.sub('', titre)
                titre = titre.replace(elm, '')
                qual = qual + elm + ' | '

        data = re.findall('((19|20)\d{2})', titre, re.S)
        if data:
            year_ = data[0][0]
            year_out = tscolor('\c0000????') + data[0][0] + tscolor(
                '\c00??????')
            if year_op == 0:
                titre = year_out + '  ' + titre.replace(year_, '')
                desc = tscolor('\c00????00') + 'Year: ' + tscolor(
                    '\c00??????') + year_ + '\n'
            elif year_op == -1:
                titre = year_out + '  ' + titre.replace(year_, '')
                desc = ''
            elif year_op == 1:
                titre = titre.replace(year_, '')
                desc = tscolor('\c00????00') + 'Year: ' + tscolor(
                    '\c00??????') + year_ + '\n'
            elif year_op == 2:
                titre = titre.replace(year_, '')
                desc = year_

        if year_op < 2:
            if sais != tscolor('\c00????00') + 'Saison: ' + tscolor(
                    '\c00??????'):
                desc = desc + sais + '\n'
            if type_ != tscolor('\c00????00') + 'Type: ' + tscolor(
                    '\c00??????'):
                desc = desc + type_[:-3] + '\n'
            if qual != tscolor('\c00????00') + 'Quality: ' + tscolor(
                    '\c00??????'):
                desc = desc + qual[:-3] + '\n'

        pat = 'موسم.*?([0-9]{1,2}).*?حلقة.*?([0-9]{1,2})'
        data = re.findall(pat, titre, re.S)
        if data:
            sa = data[0][0]
            ep = data[0][1]
            if len(sa) == 1: sa = '0' + sa
            if len(ep) == 1: ep = '0' + ep
            ep_out = tscolor('\c0000????') + 'S' + sa + tscolor(
                '\c0000????') + 'E' + ep + tscolor('\c00??????')
            titre = ep_out + ' ' + re.sub(pat, '', titre)

        return desc, self.cleanHtmlStr(titre).replace('()', '').strip()

    def informAboutGeoBlockingIfNeeded(self, country, onlyOnce=True):
        try:
            if onlyOnce and self.isGeoBlockingChecked: return
        except Exception:
            self.isGeoBlockingChecked = False
        sts, data = self.cm.getPage(
            'https://dcinfos.abtasty.com/geolocAndWeather.php')
        if not sts: return
        try:
            data = json_loads(data.strip()[1:-1], '', True)
            if data['country'] != country:
                message = _(
                    '%s uses "geo-blocking" measures to prevent you from accessing the services from outside the %s Territory.'
                )
                GetIPTVNotify().push(message % (self.getMainUrl(), country),
                                     'info', 5)
            self.isGeoBlockingChecked = True
        except Exception:
            printExc()

    def listsTab(self, tab, cItem, type='dir'):
        defaultType = type
        for item in tab:
            params = dict(cItem)
            params.update(item)
            params['name'] = 'category'
            type = item.get('type', defaultType)
            if type == 'dir': self.addDir(params)
            elif type == 'marker': self.addMarker(params)
            else: self.addVideo(params)

    def listSubItems(self, cItem):
        printDBG("TSCBaseHostClass.listSubItems")
        self.currList = cItem['sub_items']

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

    def getMainUrl(self):
        return self.MAIN_URL

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

    def getFullUrl(self, url, currUrl=None):
        if currUrl == None or not self.cm.isValidUrl(currUrl):
            try:
                currUrl = self.getMainUrl()
            except Exception:
                currUrl = None
            if currUrl == None or not self.cm.isValidUrl(currUrl):
                currUrl = 'http://fake/'
        return self.cm.getFullUrl(url, currUrl)

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

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

    @staticmethod
    def cleanHtmlStr(str):
        return CParsingHelper.cleanHtmlStr(str)

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

    def getCurrList(self):
        return self.currList

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

    def getCurrItem(self):
        return self.currItem

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

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

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

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

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

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

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

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

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

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

    def getFavouriteData(self, cItem):
        try:
            return json_dumps(cItem)
        except Exception:
            printExc()
        return ''

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

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

    def getLinksForItem(self, cItem):
        # for backward compatibility
        return self.getLinksForVideo(cItem)

    def markSelectedLink(self, cacheLinks, linkId, keyId='url', marker="*"):
        # mark requested link as used one
        if len(cacheLinks.keys()):
            for key in cacheLinks:
                for idx in range(len(cacheLinks[key])):
                    if linkId in cacheLinks[key][idx][keyId]:
                        if not cacheLinks[key][idx]['name'].startswith(marker):
                            cacheLinks[key][idx]['name'] = marker + cacheLinks[
                                key][idx]['name'] + marker
                        break

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

    def endHandleService(self, index, refresh):
        if 2 == refresh:  # refresh for more items
            currList = self.currList
            self.currList = self.beforeMoreItemList
            for item in currList:
                if 'more' == item['type'] or (
                        item not in self.beforeMoreItemList
                        and item not in self.afterMoreItemList):
                    self.currList.append(item)
            self.currList.extend(self.afterMoreItemList)
            self.beforeMoreItemList = []
            self.afterMoreItemList = []
        self.moreMode = False
class serialeo:
    SERVICE = 'serialeo'
    mainUrl = 'http://serialeonline.org.pl/'
    NewUrl = 'http://serialeonline.org.pl/nowe-odcinki'
    SerchUrl = 'http://serialeonline.org.pl/index.php?menu=search&query='

    SERVICE_MENU_TABLE =  {
        1: "Kategorie seriali",
        2: "Ostatnio uzupełnione seriale",
        3: "Wyszukaj",
        4: "Historia wyszukiwania"
    }

    def __init__(self):

        
        printDBG('Loading ' + serialeo.SERVICE)
        

        self.cm = common()
        self.up = urlparser.urlparser()
        self.history = CSearchHistoryHelper('serialeo')
        

        self.tabMenu = []
        self.currList = []

    def getCurrList(self):
        return self.currList

    def setCurrList(self, list):
        self.currList = list
        return
    
    def setTable(self):
        return self.SERVICE_MENU_TABLE

    def listsMainMenu(self, table):
        tabMenu = []
        for num, val in table.items():
            tabMenu.append(val)
        for i in range(len(tabMenu)):
            type = CListItem.TYPE_CATEGORY
            if tabMenu[i] == 'Wyszukaj':
                type = CListItem.TYPE_SEARCH
                
            item = CListItem( name = 'main-menu',
                              title = tabMenu[i],
                              category = tabMenu[i],
                              iconimage = '',
                              type = type )
            
            self.currList.append(item)
        self.tabMenu = tabMenu

    def listsKATMenu(self, url):
        sts,data = self.cm.getPage(url)
        if not sts: return
        match = re.compile(self.mainUrl + 'tv-tagi/(.+?)">(.+?)</a>').findall(data)
        if len(match) > 0:
            for i in range(len(match)):
                page = self.mainUrl + 'tv-tagi/' + match[i][0]
                item = CListItem(   name = 'kat-menu',
                                    title = match[i][1],
                                    page = page,
                                    type = CListItem.TYPE_CATEGORY )
                self.currList.append(item)

    def getLastParts(self, url):
        sts,data = self.cm.getPage(url)
        if not sts: return
        match = re.compile('portfolio(.+?)pagination', re.DOTALL).findall(data)
        if len(match) > 0:
                match2 = re.compile('href="(.+?)" class="spec-border-ie.+?\n.+?php.+?src=(.+?)&amp').findall(match[0])
                match3 = re.compile('href="http://serialeonline.org.pl/index.php.+?title="(.+?)">').findall(match[0])
                match4 = re.compile('<p class="left">(.+?)</p>').findall(match[0])
                if len(match2) and len (match3) > 0:
                        for i in range(len(match2)):
                                item = CListItem(   title = match3[i] + ' - ' + match4[i],
                                                    page = match2[i][0],
                                                    iconimage = match2[i][1],
                                                    type =  CListItem.TYPE_VIDEO )
                                self.currList.append(item)

    def showKATParts(self, page , url, pager):
        sts,data = self.cm.getPage(url)
        if not sts: return
        match = re.compile('poster(.+?)clear:both', re.DOTALL).findall(data)
        if len(match) > 0:
                match2 = re.compile('href="(.+?)" title="(.+?)">').findall(match[0])
                match3 = re.compile('timthumb.+?src=(.+?)&amp').findall(match[0])
                if len(match2) and len (match3) > 0:
                        for i in range(len(match2)):
                            item = CListItem(   title = match2[i][1],
                                                name = 'kat-parts',
                                                page = match2[i][0],
                                                iconimage = match3[i],
                                                type =  CListItem.TYPE_CATEGORY )
                            self.currList.append(item)
        match = re.compile('<li><a href="(.+?)">&raquo;</a></li>').findall(data)
        if len(match) > 0:
            item = CListItem(   title = 'Następna strona',
                                name = 'kat-menu',
                                page = page,
                                season = str(int(pager) + 1),
                                type =  CListItem.TYPE_CATEGORY )
            self.currList.append(item)

    def listsSerial(self, url, img, sezon):
        sts,data = self.cm.getPage(url)
        if not sts: return
        match = re.compile(sezon+'(.+?)tv_container', re.DOTALL).findall(data.replace('stylesheet', 'tv_container'))
        if len(match) > 0:
                match2 = re.compile('href="(.+?)">(.+?) <span class="tv_episode_name">(.+?)</span></a>').findall(match[0])
                if len(match2) > 0:
                        for i in range(len(match2)):
                                item = CListItem(   title = match2[i][1] + match2[i][2],
                                                    page = match2[i][0],
                                                    iconimage = img,
                                                    type =  CListItem.TYPE_VIDEO )
                                self.currList.append(item)

    def showSeason(self, url, img):
        sts,data = self.cm.getPage(url)
        if not sts: return
        r = re.compile('<h2>Sezon(.+?)</h2>').findall(data)
        if len(r)>0:
                for i in range(len(r)):
                    item = CListItem(   title = 'Sezon' + r[i],
                                        name = 'sezon',
                                        page = url,
                                        iconimage = img,
                                        type =  CListItem.TYPE_CATEGORY )
                    self.currList.append(item)

    def getListsSearch(self, text):
        sts,data = self.cm.getPage(self.SerchUrl + text)
        if not sts: return
        match = re.compile('<a class="link" href="(.+?)/season.+?" title="(.+?)">').findall(data)
        match2 = re.compile('timthumb.+?src=(.+?)&amp').findall(data)
        if len(match) and len (match2) > 0:
                for i in range(len(match)):
                    item = CListItem(   title = match[i][1],
                                        name = 'kat-parts',
                                        page = match[i][0],
                                        iconimage = match2[i],
                                        type =  CListItem.TYPE_CATEGORY )
                    self.currList.append(item)

    def listsHistory(self):
        list = self.history.getHistoryList()
        for item in list:
            item = CListItem(   title = item,
                                name = 'history',
                                plot = 'Szukaj: "%s"' % item,
                                type =  CListItem.TYPE_CATEGORY )
            self.currList.append(item)

    def getPlayTable(self,url):
        valTab = []
        sts,data = self.cm.getPage(url)
        if not sts: return valTab
        r = re.compile('row-pages-wrapper(.+?)disqus_thread', re.DOTALL).findall(data)
        if len(r)>0:
            r2 = re.compile('href="(.+?)" target="_blank">Oglądaj').findall(r[0])
            r3 = re.compile('http://serialeonline.org.pl/templates/trakt/images/(.+?).gif').findall(r[0])
            if len(r2)>0:
                for i in range(len(r2)):
                    title = r3[i].replace('pl1', 'Napisy').replace('eng', 'Oryginał').replace('pol', 'Lektor') + ' - ' + self.up.getHostName(r2[i])
                    valTab.append(self.cm.setLinkTable(r2[i], title))
                return valTab
        return valTab

    def handleService(self, index, refresh = 0, searchPattern = ''):
        if 0 == refresh:
            if len(self.currList) <= index:
                printDBG( "handleService wrond index: %s, len(self.currList): %d" % (index, len(self.currList)) )
                return
        
            if -1 == index:
                self.name        = None
                self.seltitle    = ''
                self.category    = ''
                self.page        = ''
                self.icon        = ''
                self.link        = ''
                self.service     = ''
                self.action      = ''
                self.sezon       = ''
                self.epizod      = ''
                self.serial      = ''
                self.searchPattern = ''


                printDBG("serialeo: handleService for first self.category")
            else:
                item             = self.currList[index]
                
                self.name        = item.name
                self.title       = item.title
                self.category    = item.category
                self.page        = item.page
                self.icon        = item.iconimage
                self.link        = item.page
                self.sezon       = item.season
                self.epizod      = item.episode
                self.serial      = item.tvshowtitle
                self.searchPattern = item.searchPattern

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

        if str(self.sezon)=='None' or self.sezon=='':
            self.sezon = '1'


        if self.name == None:
            self.listsMainMenu(self.SERVICE_MENU_TABLE)
        elif self.category == self.setTable()[1]:
            self.listsKATMenu(self.mainUrl)
        elif self.category == self.setTable()[2]:
            self.getLastParts(self.NewUrl)
        elif self.category == self.setTable()[3]:
            if self.searchPattern == '':
                text = searchPattern
            else:
                text = self.searchPattern
            self.history.addHistoryItem(text)
            self.getListsSearch(text)
        elif self.category == self.setTable()[4]:
            self.listsHistory()
        elif self.name == 'kat-menu':
            self.showKATParts(self.page ,self.page + '/abc/' + str(self.sezon), self.sezon)
        elif self.name == 'kat-parts':
            self.showSeason(self.page, self.icon)
        elif self.name == 'sezon':
            self.listsSerial(self.page, self.icon, self.title)
        elif self.name == 'history':
            self.getListsSearch(self.title)
Exemple #26
0
class CBaseHostClass:
    def __init__(self, params={}):
        self.sessionEx = MainSessionWrapper()
        self.up = urlparser()

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

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

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

    def informAboutGeoBlockingIfNeeded(self, country, onlyOnce=True):
        try:
            if onlyOnce and self.isGeoBlockingChecked: return
        except Exception:
            self.isGeoBlockingChecked = False
        sts, data = self.cm.getPage(
            'https://dcinfos.abtasty.com/geolocAndWeather.php')
        if not sts: return
        try:
            data = byteify(json.loads(data.strip()[1:-1]), '', True)
            if data['country'] != country:
                message = _(
                    '%s uses "geo-blocking" measures to prevent you from accessing the services from outside the %s Territory.'
                )
                GetIPTVNotify().push(message % (self.getMainUrl(), country),
                                     'info', 5)
            self.isGeoBlockingChecked = True
        except Exception:
            printExc()

    def listsTab(self, tab, cItem, type='dir'):
        defaultType = type
        for item in tab:
            params = dict(cItem)
            params.update(item)
            params['name'] = 'category'
            type = item.get('type', defaultType)
            if type == 'dir': self.addDir(params)
            elif type == 'marker': self.addMarker(params)
            else: self.addVideo(params)

    def getMainUrl(self):
        return self.MAIN_URL

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

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

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

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

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

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

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

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

    def getCurrList(self):
        return self.currList

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

    def getCurrItem(self):
        return self.currItem

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    def endHandleService(self, index, refresh):
        if 2 == refresh:  # refresh for more items
            currList = self.currList
            self.currList = self.beforeMoreItemList
            for item in currList:
                if 'more' == item['type'] or (
                        item not in self.beforeMoreItemList
                        and item not in self.afterMoreItemList):
                    self.currList.append(item)
            self.currList.extend(self.afterMoreItemList)
            self.beforeMoreItemList = []
            self.afterMoreItemList = []
        self.moreMode = False
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 ''
Exemple #28
0
class CBaseHostClass:
    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 listsTab(self, tab, cItem):
        for item in tab:
            params = dict(cItem)
            params.update(item)
            params['name']  = 'category'
            self.addDir(params)
        
    @staticmethod 
    def cleanHtmlStr(str):
        str = str.replace('<', ' <').replace('\n', ' ').replace('\r', ' ').replace('\t', ' ')
        return CParsingHelper.removeDoubles(clean_html(str), ' ').strip()

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

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

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

    def addDir(self, params):
        params['type'] = 'category'
        self.currList.append(params)
        return
        
    def addMore(self, params):
        params['type'] = 'more'
        self.currList.append(params)
        return
        
    def addVideo(self, params):
        params['type'] = 'video'
        self.currList.append(params)
        return
        
    def addAudio(self, params):
        params['type'] = 'audio'
        self.currList.append(params)
        return
    
    def addPicture(self, params):
        params['type'] = 'picture'
        self.currList.append(params)
        return
  
    def addArticle(self, params):
        params['type'] = 'article'
        self.currList.append(params)
        return
    
    def listsHistory(self, baseItem={'name': 'history', 'category': 'Wyszukaj'}, desc_key='plot', desc_base='Typ: '):
        list = self.history.getHistoryList()
        for histItem in list:
            plot = ''
            try:
                if type(histItem) == type({}):
                    pattern     = histItem.get('pattern', '')
                    search_type = histItem.get('type', '')
                    if '' != search_type: plot = desc_base + search_type
                else:
                    pattern     = histItem
                    search_type = None
                params = dict(baseItem)
                params.update({'title': pattern, 'search_type': search_type,  desc_key: plot})
                self.addDir(params)
            except: printExc()
    
    def handleService(self, index, refresh=0, searchPattern='', searchType=''):
        self.moreMode = False
        if 0 == refresh:
            if len(self.currList) <= index:
                return
            if -1 == index:
                self.currItem = { "name": None }
            else:
                self.currItem = self.currList[index]
        if 2 == refresh: # refresh for more items
            printDBG(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> endHandleService index[%s]" % index)
            # remove item more and store items before and after item more
            self.beforeMoreItemList = self.currList[0:index]
            self.afterMoreItemList = self.currList[index+1:]
            self.moreMode = True
    
    def endHandleService(self, index, refresh):
        if 2 == refresh: # refresh for more items
            currList = self.currList
            self.currList = self.beforeMoreItemList
            for item in currList:
                if 'more' == item['type'] or (item not in self.beforeMoreItemList and item not in self.afterMoreItemList):
                    self.currList.append(item)
            self.currList.extend(self.afterMoreItemList)
            self.beforeMoreItemList = []
            self.afterMoreItemList  = []
        self.moreMode = False
class AleKinoTV:
    MAINURL = 'http://www.mototube.pl'
    SEARCH_URL = MAINURL + '/szukaj/'

    SERVICE_MENU_TABLE = {
        1: "Kategorie",
        2: "Wyszukaj",
        3: "Historia wyszukiwania"
    }
 
    def __init__(self):
        self.up = urlparser.urlparser()
        self.cm = pCommon.common()
        self.history = CSearchHistoryHelper('MotoTube')
        # temporary data
        self.currList = []
        self.currItem = {}

    def getCurrList(self):
        return self.currList

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

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

    def addDir(self, params):
        params['type'] = 'category'
        self.currList.append(params)
        return
        
    def playVideo(self, params):
        params['type'] = 'video'
        self.currList.append(params)
        return
    
    def fWrite(self, file, data):
        #helper to see html returned by ajax
        file_path = '/mnt/hdd/' + file
        text_file = open(file_path, "w")
        text_file.write(data)
        text_file.close()    

    def getDataBeetwenMarkers(self, data, marker1, marker2, withMarkers = True):
        idx1 = data.find(marker1)
        if -1 == idx1: return False, None
        idx2 = data.find(marker2, idx1 + len(marker1))
        if -1 == idx2: return False, None
        
        if withMarkers:
            idx2 = idx2 + len(marker2)
        else:
            idx1 = idx1 + len(marker1)

        return True, data[idx1:idx2]

    def setTable(self):
        return self.SERVICE_MENU_TABLE

    def listsMainMenu(self, table):
        for num, val in table.items():
            params = {'name': 'main-menu', 'title': val, 'category': val}
            self.addDir(params)
            
    def listCategories(self, url, cat):
        printDBG("listCategories for url[%s] cat[%s]" % (url, cat))
        sts, data = self.cm.getPage(url)
        if not sts: return
        sts, data = self.getDataBeetwenMarkers(data, '<div class="submenu">', '</div>', withMarkers = False)
        if not sts: return
        match = re.compile('<a class="submenu" href="([^"]+?)">([^<]+?)</a>').findall(data)
        if match:
            for i in range(len(match)):
                params = {'title': match[i][1], 'url': match[i][0], 'category': cat, 'plot':match[i][0]}
                self.addDir(params)
                
    def listVideos(self, baseUrl, cat, page):
        printDBG("listVideos for url[%s] page[%s]" % (baseUrl, page))
        
        if 1 < int(page) != '1': url = baseUrl + page
        else: url = baseUrl
        sts, data = self.cm.getPage(url)
        if not sts: return
        
        nextPage = False
        if -1 < data.find("class='pagination_next'"):
            nextPage = True

        sts, data = self.getDataBeetwenMarkers(data, '<td class="video">', '</table>', withMarkers = False)
        if not sts: return
        
        data = data.split('<td class="video">')
        for item in data:
            # url & title
            match = re.search('class="video_title"><a href="([^"]+?)">([^<]+?)</a>', item)
            if match: 
                url = match.group(1)
                title = match.group(2)
            else: continue
            # img
            match = re.search('src="([^"]+?)"', item)
            if match: img = match.group(1)
            else: img = ''
            # plot
            match = re.search('<p style="margin:5px;" class="video_details">(.+?)</p>', item, re.DOTALL)
            if match: plot = remove_html_markup(match.group(1))
            else: plot = ''
            
            params = { 'title': title, 'url': url, 'icon': img, 'plot': plot}
            self.playVideo(params)
            
        if nextPage:
            params = {'title': "Następna strona", 'url': baseUrl, 'category': cat, 'page':str(int(page)+1)}
            self.addDir(params)
        
    def getSearchResult(self, baseUrl, cat, page):
        printDBG("getSearchResult for url[%s] page[%s]" % (baseUrl, page))
        
        if 1 < int(page) != '1': url = baseUrl + page
        else: url = baseUrl
        sts, data = self.cm.getPage(url)
        if not sts: return
        
        nextPage = False
        if -1 < data.find("class='pagination_next'"):
            nextPage = True

        sts, data = self.getDataBeetwenMarkers(data, '<td valign="top">', '<div class="menu_dol">', withMarkers = False)
        if not sts: return
      
        data = data.split('<td valign="top">')
        for item in data:
            # url & title
            match = re.search('<div class="video_title">[^<]*?<a href="([^"]+?)">([^<]+?)</a>', item)
            if match: 
                url = match.group(1)
                title = match.group(2)
            else: continue
            # img
            match = re.search('src="([^"]+?)"', item)
            if match: img = match.group(1)
            else: img = ''
            # plot
            match = re.search('<div class="video_details">(.+?)</td>', item, re.DOTALL)
            if match: plot = remove_html_markup(match.group(1)) #.replace("</div>", " ")
            else: plot = ''
            
            params = { 'title': title, 'url': url, 'icon': img, 'plot': plot}
            self.playVideo(params)
            
        if nextPage:
            params = {'title': "Następna strona", 'url': baseUrl, 'category': cat, 'page':str(int(page)+1)}
            self.addDir(params)
                
    def listsHistory(self):
        list = self.history.getHistoryList()
        for item in list:
            params = { 'name': 'history', 'category': 'Wyszukaj', 'title': item, 'plot': 'Szukaj: "%s"' % item}
            self.addDir(params)

    def getHostingTable(self, url):
        printDBG("getHostingTable for url[%s]" % url)
        
        sts, data = self.cm.getPage(url)
        if not sts:
            return []
        #check for internal link
        match = re.search('addVariable\("file","\.\.([^"]+?)"', data)
        if match:
            directUrl = self.MAINURL + match.group(1)
            return [{'name':'Internal_Link', 'url': directUrl}]
        #check for external link
        match = re.search('<embed src="([^"]+?)"', data)
        if match:
            return self.getLink(match.group(1))
        return []
            
    def getLink(self, url):
        printDBG('getLink for url[%s]' % (url))
        
        directUrl = self.up.getVideoLink(url)
        if directUrl:
            return [{'name': self.up.getHostName(url), 'url': directUrl}]
        else:
            return []

    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", '1')
        icon     = self.currItem.get("icon", '')
        url      = self.currItem.get("url", '')
        printDBG( "handleService: |||||||||||||||||||||||||||||||||||| name[%s], category[%s] " % (name, category) )
        self.currList = []
        
    #MAIN MENU
        if name == None:
            self.listsMainMenu(self.SERVICE_MENU_TABLE)
    #KATEGORIE
        elif category == "Kategorie":
            self.listCategories(self.MAINURL + "/najnowsze/", 'video_category')
        elif category == "video_category":
            self.listVideos(url, category, page)
    #WYSZUKAJ
        elif category == "Wyszukaj":
            pattern = searchPattern.replace(" ", "-")
            self.getSearchResult(self.SEARCH_URL + pattern + "/", "search_next", page)
        elif category == "search_next":
            self.getSearchResult(url, "search_next", page)
    #HISTORIA WYSZUKIWANIA
        elif category == "Historia wyszukiwania":
            self.listsHistory()
Exemple #30
0
class serialeo:
    SERVICE = 'serialeo'
    mainUrl = 'http://serialeonline.org.pl/'
    NewUrl = 'http://serialeonline.org.pl/nowe-odcinki'
    SerchUrl = 'http://serialeonline.org.pl/index.php?menu=search&query='

    SERVICE_MENU_TABLE = {
        1: "Kategorie seriali",
        2: "Ostatnio uzupełnione seriale",
        3: "Wyszukaj",
        4: "Historia wyszukiwania"
    }

    def __init__(self):

        printDBG('Loading ' + serialeo.SERVICE)

        self.cm = common()
        self.up = urlparser.urlparser()
        self.history = CSearchHistoryHelper('serialeo')

        self.tabMenu = []
        self.currList = []

    def getCurrList(self):
        return self.currList

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

    def setTable(self):
        return self.SERVICE_MENU_TABLE

    def listsMainMenu(self, table):
        tabMenu = []
        for num, val in table.items():
            tabMenu.append(val)
        for i in range(len(tabMenu)):
            type = CListItem.TYPE_CATEGORY
            if tabMenu[i] == 'Wyszukaj':
                type = CListItem.TYPE_SEARCH

            item = CListItem(name='main-menu',
                             title=tabMenu[i],
                             category=tabMenu[i],
                             iconimage='',
                             type=type)

            self.currList.append(item)
        self.tabMenu = tabMenu

    def listsKATMenu(self, url):
        sts, data = self.cm.getPage(url)
        if not sts: return
        match = re.compile(self.mainUrl +
                           'tv-tagi/(.+?)">(.+?)</a>').findall(data)
        if len(match) > 0:
            for i in range(len(match)):
                page = self.mainUrl + 'tv-tagi/' + match[i][0]
                item = CListItem(name='kat-menu',
                                 title=match[i][1],
                                 page=page,
                                 type=CListItem.TYPE_CATEGORY)
                self.currList.append(item)

    def getLastParts(self, url):
        sts, data = self.cm.getPage(url)
        if not sts: return
        match = re.compile('portfolio(.+?)pagination', re.DOTALL).findall(data)
        if len(match) > 0:
            match2 = re.compile(
                'href="(.+?)" class="spec-border-ie.+?\n.+?php.+?src=(.+?)&amp'
            ).findall(match[0])
            match3 = re.compile(
                'href="http://serialeonline.org.pl/index.php.+?title="(.+?)">'
            ).findall(match[0])
            match4 = re.compile('<p class="left">(.+?)</p>').findall(match[0])
            if len(match2) and len(match3) > 0:
                for i in range(len(match2)):
                    item = CListItem(title=match3[i] + ' - ' + match4[i],
                                     page=match2[i][0],
                                     iconimage=match2[i][1],
                                     type=CListItem.TYPE_VIDEO)
                    self.currList.append(item)

    def showKATParts(self, page, url, pager):
        sts, data = self.cm.getPage(url)
        if not sts: return
        match = re.compile('poster(.+?)clear:both', re.DOTALL).findall(data)
        if len(match) > 0:
            match2 = re.compile('href="(.+?)" title="(.+?)">').findall(
                match[0])
            match3 = re.compile('timthumb.+?src=(.+?)&amp').findall(match[0])
            if len(match2) and len(match3) > 0:
                for i in range(len(match2)):
                    item = CListItem(title=match2[i][1],
                                     name='kat-parts',
                                     page=match2[i][0],
                                     iconimage=match3[i],
                                     type=CListItem.TYPE_CATEGORY)
                    self.currList.append(item)
        match = re.compile('<li><a href="(.+?)">&raquo;</a></li>').findall(
            data)
        if len(match) > 0:
            item = CListItem(title='Następna strona',
                             name='kat-menu',
                             page=page,
                             season=str(int(pager) + 1),
                             type=CListItem.TYPE_CATEGORY)
            self.currList.append(item)

    def listsSerial(self, url, img, sezon):
        sts, data = self.cm.getPage(url)
        if not sts: return
        match = re.compile(sezon + '(.+?)tv_container', re.DOTALL).findall(
            data.replace('stylesheet', 'tv_container'))
        if len(match) > 0:
            match2 = re.compile(
                'href="(.+?)">(.+?) <span class="tv_episode_name">(.+?)</span></a>'
            ).findall(match[0])
            if len(match2) > 0:
                for i in range(len(match2)):
                    item = CListItem(title=match2[i][1] + match2[i][2],
                                     page=match2[i][0],
                                     iconimage=img,
                                     type=CListItem.TYPE_VIDEO)
                    self.currList.append(item)

    def showSeason(self, url, img):
        sts, data = self.cm.getPage(url)
        if not sts: return
        r = re.compile('<h2>Sezon(.+?)</h2>').findall(data)
        if len(r) > 0:
            for i in range(len(r)):
                item = CListItem(title='Sezon' + r[i],
                                 name='sezon',
                                 page=url,
                                 iconimage=img,
                                 type=CListItem.TYPE_CATEGORY)
                self.currList.append(item)

    def getListsSearch(self, text):
        sts, data = self.cm.getPage(self.SerchUrl + text)
        if not sts: return
        match = re.compile(
            '<a class="link" href="(.+?)/season.+?" title="(.+?)">').findall(
                data)
        match2 = re.compile('timthumb.+?src=(.+?)&amp').findall(data)
        if len(match) and len(match2) > 0:
            for i in range(len(match)):
                item = CListItem(title=match[i][1],
                                 name='kat-parts',
                                 page=match[i][0],
                                 iconimage=match2[i],
                                 type=CListItem.TYPE_CATEGORY)
                self.currList.append(item)

    def listsHistory(self):
        list = self.history.getHistoryList()
        for item in list:
            item = CListItem(title=item,
                             name='history',
                             plot='Szukaj: "%s"' % item,
                             type=CListItem.TYPE_CATEGORY)
            self.currList.append(item)

    def getPlayTable(self, url):
        valTab = []
        sts, data = self.cm.getPage(url)
        if not sts: return valTab
        r = re.compile('row-pages-wrapper(.+?)disqus_thread',
                       re.DOTALL).findall(data)
        if len(r) > 0:
            r2 = re.compile('href="(.+?)" target="_blank">Oglądaj').findall(
                r[0])
            r3 = re.compile(
                'http://serialeonline.org.pl/templates/trakt/images/(.+?).gif'
            ).findall(r[0])
            if len(r2) > 0:
                for i in range(len(r2)):
                    title = r3[i].replace('pl1', 'Napisy').replace(
                        'eng', 'Oryginał').replace(
                            'pol', 'Lektor') + ' - ' + self.up.getHostName(
                                r2[i])
                    valTab.append(self.cm.setLinkTable(r2[i], title))
                return valTab

    def handleService(self, index, refresh=0, searchPattern=''):
        if 0 == refresh:
            if len(self.currList) <= index:
                printDBG(
                    "handleService wrond index: %s, len(self.currList): %d" %
                    (index, len(self.currList)))
                return

            if -1 == index:
                self.name = None
                self.seltitle = ''
                self.category = ''
                self.page = ''
                self.icon = ''
                self.link = ''
                self.service = ''
                self.action = ''
                self.sezon = ''
                self.epizod = ''
                self.serial = ''
                self.searchPattern = ''

                printDBG("serialeo: handleService for first self.category")
            else:
                item = self.currList[index]

                self.name = item.name
                self.title = item.title
                self.category = item.category
                self.page = item.page
                self.icon = item.iconimage
                self.link = item.page
                self.sezon = item.season
                self.epizod = item.episode
                self.serial = item.tvshowtitle
                self.searchPattern = item.searchPattern

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

        if str(self.sezon) == 'None' or self.sezon == '':
            self.sezon = '1'

        if self.name == None:
            self.listsMainMenu(self.SERVICE_MENU_TABLE)
        elif self.category == self.setTable()[1]:
            self.listsKATMenu(self.mainUrl)
        elif self.category == self.setTable()[2]:
            self.getLastParts(self.NewUrl)
        elif self.category == self.setTable()[3]:
            if self.searchPattern == '':
                text = searchPattern
            else:
                text = self.searchPattern
            self.history.addHistoryItem(text)
            self.getListsSearch(text)
        elif self.category == self.setTable()[4]:
            self.listsHistory()
        elif self.name == 'kat-menu':
            self.showKATParts(self.page, self.page + '/abc/' + str(self.sezon),
                              self.sezon)
        elif self.name == 'kat-parts':
            self.showSeason(self.page, self.icon)
        elif self.name == 'sezon':
            self.listsSerial(self.page, self.icon, self.title)
        elif self.name == 'history':
            self.getListsSearch(self.title)
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 ''
Exemple #32
0
class iPtak:
    MAINURL = 'http://iptak.pl/'
    
    M_NOWOSCI          = "Nowo dodane"
    M_POLECAMY         = "Polecamy"
    M_DISIAJ_NAJLEPSZE = "Najlepsze z tygodnia"
    M_KATRGORIE_FILMOW = "Kategorie filmów"
    M_WYSZUKAJ         = "Wyszukaj"
    M_HISTORIA         = "Historia wyszukiwania"
    
    SERVICE_MENU_TABLE = [
        M_NOWOSCI,
        M_POLECAMY,
        M_DISIAJ_NAJLEPSZE,
        M_KATRGORIE_FILMOW,
        M_WYSZUKAJ,
        M_HISTORIA
    ]
    def __init__(self):
        self.up = urlparser.urlparser()
        self.cm = pCommon.common()
        self.history = CSearchHistoryHelper('iptak')
        # temporary data
        self.currList = []
        self.currItem = {}
        
        # for cache to speedUp
        self.menuData = None

    def getCurrList(self):
        return self.currList

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

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

    def addDir(self, params):
        params['type'] = 'category'
        self.currList.append(params)
        return
        
    def addVideo(self, params):
        params['type'] = 'video'
        self.currList.append(params)
        return
        
    def getMenuData(self):
        printDBG("getMenuData start")
        if self.menuData == None:
            sts, self.menuData = self.cm.getPage( self.MAINURL )
            if False == sts:
                printDBG("getMenuData problem")
                self.menuData = None
        return self.menuData
        
    def getPropertiesValues(self, properties, data):
        retDict = dict()
        for prop in properties:
            match = re.search(prop + '="([^"]+?)"', data)
            if match: 
                retDict[prop] = match.group(1)
        return retDict

    def listsMainMenu(self, table):
        for val in table:
            params = { 'name': 'main-menu','category': val, 'title': val, 'icon': ''}
            self.addDir(params)
    
    def listMainBase(self, addMethod, category, mark1, mark2, splitMark):
        printDBG('listMainBase category[%s]: mark1[%s], mark2[%s], splitMark[%s]' % (category, mark1, mark2, splitMark) )
        data = self.getMenuData()
        if data == None: return
        sts, data = self.cm.ph.getDataBeetwenMarkers(data, mark1, mark2)
        
        if False == sts: return
        data = data.split(splitMark)
        del data[0]
        printDBG('listMainBase len(data)[%r]' % len(data))
        for item in data:
            retDict = self.getPropertiesValues(['href', 'src', 'title'], item) 
            if 'href' in retDict:
                img = retDict.get('src', '')
                if not img.startswith('http://'):
                    img = self.MAINURL + img.replace('../', '')
                params = {'name': 'sub', 'category': category, 'title': retDict.get('title', ''), 'page': retDict['href'], 'icon': img}
                addMethod( params )
    # end listMainBase
    
    def listsMenuNowosci(self):
        printDBG("listsMenuNowosci start")
        self.listMainBase(addMethod=self.addVideo, category=self.M_NOWOSCI, mark1='<h3>Nowo dodane:</h3>', mark2='<div id="footer">', splitMark='<div id="item"')
    # end listsMenuNowosci
        
    def listsMenuPolecamy(self):
        printDBG("listsMenuPolecamy start")
        self.listMainBase(addMethod=self.addVideo, category=self.M_POLECAMY, mark1='<div class="banner">', mark2='<script', splitMark='<a')
    # end listsMenuPolecamy
    
    def listsMenuDzisiajNajlepsze(self):
        printDBG("listsMenuDzisiajNajlepsze start")
        data = self.getMenuData()
        if data == None:
            return
        sts, data = self.cm.ph.getDataBeetwenMarkers(data, 'Najlepsze z tygodnia', '</ul>')
        if False == sts:
            return
        data = data.split('<li')
        del data[0]
        for item in data:
            retDict = self.getPropertiesValues(['href'], item) 
            if 'href' in retDict:
                # title
                match = re.search('>([^<]+?)<span', item)
                if match: title = match.group(1)
                else: title = ''
                # vote
                match = re.search('>([^<]+?)</span', item)
                if match: vote = match.group(1)
                else: vote = ''
                params = {'name': 'sub', 'category': self.M_DISIAJ_NAJLEPSZE, 'title': title, 'plot': ' Ocena: ' + vote, 'page': retDict['href']}
                self.addVideo( params )
    # end listsMenuDzisiajNajlepsze
    
    def listsMenuKategorieFilmow(self):
        printDBG("listsMenuKategorieFilmow start")
        data = self.getMenuData()
        if data == None:
            return
        sts, data = self.cm.ph.getDataBeetwenReMarkers(data, re.compile('<a[^>]+?href="http://iptak.pl/kategoria/wszystkie/"[^>]*?>'), re.compile('<script>'))
        if False == sts: return
        data = data.split('</li>')
        for item in data:
            retDict = self.getPropertiesValues(['href'], item) 
            if 'href' in retDict:
                # title
                match = re.search('<h5>([^<]+?)</h5>', item)
                if match: title = match.group(1)
                else: title = ''
                params = {'name': 'sub', 'category': self.M_KATRGORIE_FILMOW, 'title': title, 'page': retDict['href']}
                self.addDir( params )
        #self.listMainBase(addMethod=self.addDir, category=self.M_KATRGORIE_FILMOW, mark1='<div id="category" style="border:none !important">', mark2='</ul>', splitMark='<li>')
    # end listsMenuKategorieFilmow
    
    def listsVideosForCategory(self, catUrl):
        printDBG("listsVideosForCategory start catUrl[%s]" % catUrl)
        sts, data = self.cm.getPage( catUrl )
        if not sts: return
        
        #next Page
        match = re.search('<a class="next page-numbers" href="([^"]+?)">', data)
        if match:
            nextPageParams = {'name': 'sub', 'category': self.M_KATRGORIE_FILMOW, 'title': 'Następna strona', 'page': match.group(1)}
        else:
            nextPageParams = None
        
        sts, data = self.cm.ph.getDataBeetwenMarkers(data, '<div class="wyszukiwanie">', '<div id="top100">')
        if not sts: return
        
        sts, data = self.cm.ph.getDataBeetwenMarkers(data, '<div id="item"', '<script', True)
        if False == sts: return

        data = data.split('<div id="item"')
        for item in data:
            retDict = self.getPropertiesValues(['href', 'title', 'src', 'alt'], item) 
            if 'href' in retDict:
                # title
                title = retDict.get('title', '')
                if title == '': title = self.cm.ph.getSearchGroups(item, '<h6>([^<]+?)</h6>')[0]
                if title == '': title = retDict.get('alt', '')

                params = {'name': 'sub', 'category': self.M_KATRGORIE_FILMOW, 'title': title, 'page': retDict['href'], 'icon': retDict.get('src', '')}
                self.addVideo( params )
        
        if nextPageParams:
            self.addDir( nextPageParams )
    # end listsVideosForCategory

    def getHostingTable(self, url):
        printDBG("getHostingTable url[%s]" % url)
        retTab = []
        sts, data = self.cm.getPage( url )
        if False == sts:
            printDBG("getHostingTable get page problem")
            return retTab
        sts, data = self.cm.ph.getDataBeetwenMarkers(data, '<span id="mirrors">', '<span id="ocenHosting"')
        if False == sts:
            printDBG("getHostingTable separete uselfull HTML problem")
            return retTab
        data = data.split('<a')
        del data[0]
        for item in data:
            match = re.search("playMovie\('([^']+?)'\,'([^']+?)'\)", item)
            if match: 
                host = match.group(2)
                url = ''
                if host == 'yt':
                    hostName = 'YouTube'
                    url  = 'http://www.youtube.com/watch?v=' + match.group(1)
                elif host == 'cda':
                    hostName = 'CDA'
                    url  = 'http://ebd.cda.pl/630x430/' + match.group(1)
                else:
                    printDBG("HOST iPTAK UNKNOWN HOST [%s]" % host)
                    continue
                printDBG('getHostingTable add %s[%s]'  % (hostName, url))
                # resolve url to get direct url to video file
                retTab.extend(self.up.getVideoLinkExt( url ))
        return retTab

    def listsHistory(self):
            list = self.history.getHistoryList()
            for item in list:
                params = { 'name': 'history', 'category': self.M_WYSZUKAJ, 'title': item, 'plot': 'Szukaj: "%s"' % item}
                self.addDir(params)

    def getVideoUrl(self, url):
        retTab = []
        return retTab
        
    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 = []
        
        # reset cache due to refresh
        if name == 'main-menu' and 1 == refresh:
            self.menuData = None
 
    #MAIN MENU
        if name == None:
            self.listsMainMenu(self.SERVICE_MENU_TABLE)
    #NOWOSCI
        elif category == self.M_NOWOSCI:
            self.listsMenuNowosci()
    #POLECAMY
        elif category == self.M_POLECAMY:
            self.listsMenuPolecamy()
    #DISIAJ NAJLEPSZE
        elif category == self.M_DISIAJ_NAJLEPSZE:
            self.listsMenuDzisiajNajlepsze()
    #KATRGORIE FILMOW
        elif category == self.M_KATRGORIE_FILMOW:
            if name == 'main-menu':
                self.listsMenuKategorieFilmow()
            else:
                self.listsVideosForCategory(page)
    #WYSZUKAJ
        elif category == self.M_WYSZUKAJ:
            text = searchPattern
            self.listsVideosForCategory(self.MAINURL + "?s=" + urllib.quote_plus(text))
    #HISTORIA WYSZUKIWANIA
        elif category == self.M_HISTORIA:
            self.listsHistory()
    #WRONG WAY
        else:
            printDBG('handleService WRONG WAY')