コード例 #1
0
class Youtube(CBaseHostClass):
    def __init__(self):
        printDBG("Youtube.__init__")
        CBaseHostClass.__init__(self, {
            'history': 'ytlist',
            'cookie': 'youtube.cookie'
        })
        self.UTLIST_FILE = 'ytlist.txt'
        self.DEFAULT_ICON_URL = 'http://www.mm229.com/images/youtube-button-psd-450203.png'
        self.MAIN_GROUPED_TAB = [{'category': 'from_file',             'title': _("User links"),     'desc': _("User links stored in the ytlist.txt file.")}, \
                                 {'category': 'search',                'title': _("Search"),         'desc': _("Search youtube materials "), 'search_item':True}, \
                                 {'category': 'search_history',        'title': _("Search history"), 'desc': _("History of searched phrases.")}]
        self.SEARCH_TYPES = [(_("Video"), "video"), (_("Channel"), "channel"),
                             (_("Playlist"), "playlist"),
                             (_("Movie"), "movie"), (_("Live"), "live")]
        #("Program",            "show"    ),
        #("traylist",           "traylist"),
        self.ytp = YouTubeParser()
        self.currFileHost = None

    def _getCategory(self, url):
        printDBG("Youtube._getCategory")
        if '/playlist?list=' in url:
            category = 'playlist'
        elif url.split('?')[0].endswith('/playlists'):
            category = 'playlists'
        elif None != re.search('/watch\?v=[^\&]+?\&list=', url):
            category = 'traylist'
        elif 'user/' in url or ('channel/' in url
                                and not url.endswith('/live')):
            category = 'channel'
        else:
            category = 'video'
        return category

    def listsMainMenu(self):
        printDBG("Youtube.listsMainMenu")
        for item in self.MAIN_GROUPED_TAB:
            params = {'name': 'category'}
            params.update(item)
            self.addDir(params)

    def listCategory(self, cItem, searchMode=False):
        printDBG("Youtube.listCategory cItem[%s]" % cItem)

        sortList = True
        filespath = config.plugins.iptvplayer.Sciezkaurllist.value
        groupList = True
        if 'sub_file_category' not in cItem:
            self.currFileHost = IPTVFileHost()
            self.currFileHost.addFile(filespath + self.UTLIST_FILE,
                                      encoding='utf-8')
            tmpList = self.currFileHost.getGroups(sortList)
            if 0 < len(tmpList):
                params = dict(cItem)
                params.update({
                    'sub_file_category': 'all',
                    'group': 'all',
                    'title': _("--All--")
                })
                self.addDir(params)
            for item in tmpList:
                if '' == item: title = _("--Other--")
                else: title = item
                params = dict(cItem)
                params.update({
                    'sub_file_category': 'group',
                    'title': title,
                    'group': item
                })
                self.addDir(params)
        else:
            if 'all' == cItem['sub_file_category']:
                tmpList = self.currFileHost.getAllItems(sortList)
                for item in tmpList:
                    params = dict(cItem)
                    category = self._getCategory(item['url'])
                    params.update({
                        'good_for_fav': True,
                        'title': item['full_title'],
                        'url': item['url'],
                        'desc': item['url'],
                        'category': category
                    })
                    if 'video' == category:
                        self.addVideo(params)
                    else:
                        self.addDir(params)
            elif 'group' == cItem['sub_file_category']:
                tmpList = self.currFileHost.getItemsInGroup(
                    cItem['group'], sortList)
                for item in tmpList:
                    if '' == item['title_in_group']:
                        title = item['full_title']
                    else:
                        title = item['title_in_group']
                    params = dict(cItem)
                    category = self._getCategory(item['url'])
                    params.update({
                        'good_for_fav': True,
                        'title': title,
                        'url': item['url'],
                        'desc': item['url'],
                        'category': category
                    })
                    if 'video' == category:
                        self.addVideo(params)
                    else:
                        self.addDir(params)

    def listItems(self, cItem):
        printDBG('Youtube.listItems cItem[%s]' % (cItem))
        category = cItem.get("category", '')
        url = cItem.get("url", '')
        page = cItem.get("page", '1')

        if "playlists" == category:
            self.currList = self.ytp.getListPlaylistsItems(
                url, category, page, cItem)

        for idx in range(len(self.currList)):
            if self.currList[idx]['category'] in [
                    "channel", "playlist", "movie", "traylist"
            ]:
                self.currList[idx]['good_for_fav'] = True

    def getVideos(self, cItem):
        printDBG('Youtube.getVideos cItem[%s]' % (cItem))

        category = cItem.get("category", '')
        url = cItem.get("url", '')
        page = cItem.get("page", '1')

        if "channel" == category:
            if -1 == url.find('browse_ajax'):
                if url.endswith('/videos'):
                    url = url + '?flow=list&view=0&sort=dd'
                else:
                    url = url + '/videos?flow=list&view=0&sort=dd'
            self.currList = self.ytp.getVideosFromChannelList(
                url, category, page, cItem)
        elif "playlist" == category:
            self.currList = self.ytp.getVideosFromPlaylist(
                url, category, page, cItem)
        elif "traylist" == category:
            self.currList = self.ytp.getVideosFromTraylist(
                url, category, page, cItem)
        else:
            printDBG('YTlist.getVideos Error unknown category[%s]' % category)

    def listSearchResult(self, cItem, pattern, searchType):
        page = self.currItem.get("page", '1')
        tmpList = self.ytp.getSearchResult(
            urllib.quote_plus(pattern), searchType, page, 'search',
            config.plugins.iptvplayer.ytSortBy.value)
        for item in tmpList:
            item.update({'name': 'category'})
            if 'video' == item['type']:
                self.addVideo(item)
            else:
                if item['category'] in [
                        "channel", "playlist", "movie", "traylist"
                ]:
                    item['good_for_fav'] = True
                self.addDir(item)

    def getLinksForVideo(self, cItem):
        printDBG("Youtube.getLinksForVideo cItem[%s]" % cItem)
        urlTab = self.up.getVideoLinkExt(cItem['url'])
        if config.plugins.iptvplayer.ytUseDF.value and 0 < len(urlTab):
            return [urlTab[0]]
        return urlTab

    def getFavouriteData(self, cItem):
        printDBG('Youtube.getFavouriteData')
        return json.dumps(cItem)

    def getLinksForFavourite(self, fav_data):
        printDBG('Youtube.getLinksForFavourite')
        links = []
        try:
            cItem = byteify(json.loads(fav_data))
            links = self.getLinksForVideo(cItem)
        except Exception:
            printExc()
            return self.getLinksForVideo({'url': fav_data})
        return links

    def setInitListFromFavouriteItem(self, fav_data):
        printDBG('Youtube.setInitListFromFavouriteItem')
        try:
            params = byteify(json.loads(fav_data))
        except Exception:
            params = {}
            printExc()
        self.addDir(params)
        return True

    def handleService(self, index, refresh=0, searchPattern='', searchType=''):
        printDBG('Youtube.handleService start')

        CBaseHostClass.handleService(self, index, refresh, searchPattern,
                                     searchType)

        name = self.currItem.get("name", '')
        category = self.currItem.get("category", '')
        printDBG("Youtube.handleService: ---------> name[%s], category[%s] " %
                 (name, category))
        self.currList = []

        if None == name:
            self.listsMainMenu()
        elif 'from_file' == category:
            self.listCategory(self.currItem)
        elif category in ["channel", "playlist", "movie", "traylist"]:
            self.getVideos(self.currItem)
        elif category == 'playlists':
            self.listItems(self.currItem)
    #SEARCH
        elif category in ["search", "search_next_page"]:
            cItem = dict(self.currItem)
            cItem.update({'search_item': False, 'name': 'category'})
            self.listSearchResult(cItem, searchPattern, searchType)

    #HISTORIA SEARCH
        elif category == "search_history":
            self.listsHistory({
                'name': 'history',
                'category': 'search'
            }, 'desc', _("Type: "))
        else:
            printExc()

        CBaseHostClass.endHandleService(self, index, refresh)
コード例 #2
0
class Youtube(CBaseHostClass):
    UTLIST_FILE = 'ytlist.txt'
    MAIN_GROUPED_TAB = [{'category': 'from_file',             'title': _("User links"),     'desc': _("User links stored in the ytlist.txt file.")}, \
                        {'category': 'Wyszukaj',              'title': _("Search"),         'desc': _("Search youtube materials "), 'search_item':True}, \
                        {'category': 'Historia wyszukiwania', 'title': _("Search history"), 'desc': _("History of searched phrases.")}]
    SEARCH_TYPES = [(_("Video"), "video"), (_("Channel"), "channel"),
                    (_("Playlist"), "playlist"), (_("Movie"), "movie"),
                    (_("Live"), "live")]

    #("Program",            "show"    ),
    #("traylist",           "traylist"),

    def __init__(self):
        printDBG("Youtube.__init__")
        CBaseHostClass.__init__(self, {
            'history': 'ytlist',
            'cookie': 'youtube.cookie'
        })
        self.ytp = YouTubeParser()
        self.currFileHost = None

    def _cleanHtmlStr(self, str):
        str = self.cm.ph.replaceHtmlTags(str, ' ').replace('\n', ' ')
        return clean_html(
            self.cm.ph.removeDoubles(str, ' ').replace(' )', ')').strip())

    def _getCategory(self, url):
        printDBG("Youtube._getCategory")
        if '/playlist?list=' in url:
            category = 'playlist'
        elif None != re.search('/watch\?v=[^\&]+?\&list=', url):
            category = 'traylist'
        elif 'user/' in url or 'channel/' in url:
            category = 'channel'
        else:
            category = 'video'
        return category

    def listsMainMenu(self):
        printDBG("Youtube.listsMainMenu")
        for item in Youtube.MAIN_GROUPED_TAB:
            params = {'name': 'category'}
            params.update(item)
            self.addDir(params)

    def listCategory(self, cItem, searchMode=False):
        printDBG("Youtube.listCategory cItem[%s]" % cItem)

        sortList = True
        filespath = config.plugins.iptvplayer.Sciezkaurllist.value
        groupList = True
        if 'sub_file_category' not in cItem:
            self.currFileHost = IPTVFileHost()
            self.currFileHost.addFile(filespath + Youtube.UTLIST_FILE,
                                      encoding='utf-8')
            tmpList = self.currFileHost.getGroups(sortList)
            if 0 < len(tmpList):
                params = dict(cItem)
                params.update({
                    'sub_file_category': 'all',
                    'group': 'all',
                    'title': _("--All--")
                })
                self.addDir(params)
            for item in tmpList:
                if '' == item: title = _("--Other--")
                else: title = item
                params = dict(cItem)
                params.update({
                    'sub_file_category': 'group',
                    'title': title,
                    'group': item
                })
                self.addDir(params)
        else:
            if 'all' == cItem['sub_file_category']:
                tmpList = self.currFileHost.getAllItems(sortList)
                for item in tmpList:
                    params = dict(cItem)
                    category = self._getCategory(item['url'])
                    params.update({
                        'title': item['full_title'],
                        'url': item['url'],
                        'desc': item['url'],
                        'category': category
                    })
                    if 'video' == category:
                        self.addVideo(params)
                    else:
                        self.addDir(params)
            elif 'group' == cItem['sub_file_category']:
                tmpList = self.currFileHost.getItemsInGroup(
                    cItem['group'], sortList)
                for item in tmpList:
                    if '' == item['title_in_group']:
                        title = item['full_title']
                    else:
                        title = item['title_in_group']
                    params = dict(cItem)
                    category = self._getCategory(item['url'])
                    params.update({
                        'title': title,
                        'url': item['url'],
                        'desc': item['url'],
                        'category': category
                    })
                    if 'video' == category:
                        self.addVideo(params)
                    else:
                        self.addDir(params)

    def getVideos(self, cItem):
        printDBG('Youtube.getVideos cItem[%s]' % (cItem))

        category = cItem.get("category", '')
        url = cItem.get("url", '')
        page = cItem.get("page", '1')

        if "channel" == category:
            if -1 == url.find('browse_ajax'):
                if url.endswith('/videos'):
                    url = url + '?flow=list&view=0&sort=dd'
                else:
                    url = url + '/videos?flow=list&view=0&sort=dd'
            self.currList = self.ytp.getVideosFromChannelList(
                url, category, page, cItem)
        elif "playlist" == category:
            self.currList = self.ytp.getVideosFromPlaylist(
                url, category, page, cItem)
        elif "traylist" == category:
            self.currList = self.ytp.getVideosFromTraylist(
                url, category, page, cItem)
        else:
            printDBG('YTlist.getVideos Error unknown category[%s]' % category)

    def getSearchResult(self, cItem, pattern, searchType):
        page = self.currItem.get("page", '1')
        tmpList = self.ytp.getSearchResult(
            pattern, searchType, page, 'Wyszukaj',
            config.plugins.iptvplayer.ytSortBy.value)
        for item in tmpList:
            item.update({'name': 'category'})
            if 'video' == item['type']:
                self.addVideo(item)
            else:
                self.addDir(item)

    def getLinksForVideo(self, url):
        printDBG("Youtube.getLinksForVideo url[%s]" % url)
        ytformats = config.plugins.iptvplayer.ytformat.value
        maxRes = int(config.plugins.iptvplayer.ytDefaultformat.value) * 1.1
        dash = config.plugins.iptvplayer.ytShowDash.value

        if not url.startswith("http://") and not url.startswith("https://"):
            url = 'http://www.youtube.com/' + url
        tmpTab, dashTab = self.ytp.getDirectLinks(url,
                                                  ytformats,
                                                  dash,
                                                  dashSepareteList=True)

        def __getLinkQuality(itemLink):
            tab = itemLink['format'].split('x')
            return int(tab[0])

        tmpTab = CSelOneLink(tmpTab, __getLinkQuality, maxRes).getSortedLinks()
        if config.plugins.iptvplayer.ytUseDF.value and 0 < len(tmpTab):
            tmpTab = [tmpTab[0]]

        videoUrls = []
        for item in tmpTab:
            videoUrls.append({
                'name': item['format'] + ' | ' + item['ext'],
                'url': item['url']
            })
        for item in dashTab:
            videoUrls.append({
                'name':
                _("[dash] ") + item['format'] + ' | ' + item['ext'],
                'url':
                item['url']
            })
        return videoUrls

    def getFavouriteData(self, cItem):
        return cItem['url']

    def getLinksForFavourite(self, fav_data):
        return self.getLinksForVideo(fav_data)

    def handleService(self, index, refresh=0, searchPattern='', searchType=''):
        printDBG('Youtube.handleService start')
        CBaseHostClass.handleService(self, index, refresh, searchPattern,
                                     searchType)
        name = self.currItem.get("name", None)
        category = self.currItem.get("category", '')
        printDBG("Youtube.handleService: ---------> name[%s], category[%s] " %
                 (name, category))
        self.currList = []

        if None == name:
            self.listsMainMenu()
        elif 'from_file' == category:
            self.listCategory(self.currItem)
        elif category in ["channel", "playlist", "movie", "traylist"]:
            self.getVideos(self.currItem)
    #WYSZUKAJ
        elif category == 'Wyszukaj':
            pattern = urllib.quote_plus(searchPattern)
            printDBG("Wyszukaj pattern[%s], type[%s]" % (pattern, searchType))
            self.getSearchResult(self.currItem, pattern, searchType)

    #HISTORIA WYSZUKIWANIAmain_item
        elif category == 'Historia wyszukiwania':
            self.listsHistory()
コード例 #3
0
class Youtube(CBaseHostClass):
    UTLIST_FILE      = 'ytlist.txt'
    MAIN_GROUPED_TAB = [{'category': 'from_file',             'title': _("User links"),     'desc': _("User links stored in the ytlist.txt file.")}, \
                        {'category': 'Wyszukaj',              'title': _("Search"),         'desc': _("Search youtube materials "), 'search_item':True}, \
                        {'category': 'Historia wyszukiwania', 'title': _("Search history"), 'desc': _("History of searched phrases.")}]
    SEARCH_TYPES = [  (_("Video"),    "video"   ), 
                      (_("Channel"),  "channel" ),
                      (_("Playlist"), "playlist"),
                      (_("Movie"),    "movie"   ),
                      (_("Live"),     "live"    ) ]
                      #("Program",            "show"    ),
                      #("traylist",           "traylist"),
        
    def __init__(self):
        printDBG("Youtube.__init__")
        CBaseHostClass.__init__(self, {'history':'ytlist', 'cookie':'youtube.cookie'})            
        self.ytp = YouTubeParser()
        self.currFileHost = None
    
    def _cleanHtmlStr(self, str):
            str = self.cm.ph.replaceHtmlTags(str, ' ').replace('\n', ' ')
            return clean_html(self.cm.ph.removeDoubles(str, ' ').replace(' )', ')').strip())
            
    def _getCategory(self, url):
        printDBG("Youtube._getCategory")
        if '/playlist?list=' in url:
            category = 'playlist'
        elif None != re.search('/watch\?v=[^\&]+?\&list=',  url):
            category = 'traylist'
        elif 'user/' in url or 'channel/' in url:
            category = 'channel'
        else:
            category = 'video'
        return category
        
    def listsMainMenu(self):
        printDBG("Youtube.listsMainMenu")
        for item in Youtube.MAIN_GROUPED_TAB:
            params = {'name': 'category'}
            params.update(item)
            self.addDir(params)
        
    def listCategory(self, cItem, searchMode=False):
        printDBG("Youtube.listCategory cItem[%s]" % cItem)
        
        sortList = True
        filespath = config.plugins.iptvplayer.Sciezkaurllist.value
        groupList = True
        if 'sub_file_category'  not in cItem:
            self.currFileHost = IPTVFileHost()
            self.currFileHost.addFile(filespath + Youtube.UTLIST_FILE, encoding='utf-8')
            tmpList = self.currFileHost.getGroups(sortList)
            if 0 < len(tmpList):
                params = dict(cItem)
                params.update({'sub_file_category':'all', 'group': 'all', 'title':_("--All--")})
                self.addDir(params)
            for item in tmpList:
                if '' == item: title = _("--Other--")
                else:          title = item
                params = dict(cItem)
                params.update({'sub_file_category':'group', 'title':title, 'group':item})
                self.addDir(params)
        else:
            if 'all' == cItem['sub_file_category']:
                tmpList = self.currFileHost.getAllItems(sortList)
                for item in tmpList:
                    params = dict(cItem)
                    category = self._getCategory(item['url'])
                    params.update({'title':item['full_title'], 'url':item['url'], 'desc': item['url'], 'category': category})
                    if 'video' == category:
                        self.addVideo(params)
                    else:
                        self.addDir(params)
            elif 'group' == cItem['sub_file_category']:
                tmpList = self.currFileHost.getItemsInGroup(cItem['group'], sortList)
                for item in tmpList:
                    if '' == item['title_in_group']:
                        title = item['full_title']
                    else:
                        title = item['title_in_group']
                    params = dict(cItem)
                    category = self._getCategory(item['url'])
                    params.update({'title':title, 'url':item['url'], 'desc': item['url'], 'category': category})
                    if 'video' == category:
                        self.addVideo(params)
                    else:
                        self.addDir(params)
                        
    def getVideos(self, cItem):
        printDBG('Youtube.getVideos cItem[%s]' % (cItem))
        
        category = cItem.get("category", '')
        url      = cItem.get("url", '')
        page     = cItem.get("page", '1')
                
        if "channel" == category:
            if -1 == url.find('browse_ajax'):
                if url.endswith('/videos'): 
                    url = url + '?flow=list&view=0&sort=dd'
                else:
                    url = url + '/videos?flow=list&view=0&sort=dd'
            self.currList = self.ytp.getVideosFromChannelList(url, category, page, cItem)
        elif "playlist" == category:
            self.currList = self.ytp.getVideosFromPlaylist(url, category, page, cItem)   
        elif "traylist" == category:
            self.currList = self.ytp.getVideosFromTraylist(url, category, page, cItem)
        else:
            printDBG('YTlist.getVideos Error unknown category[%s]' % category)
            
    def getSearchResult(self, cItem, pattern, searchType):
        page = self.currItem.get("page", '1')
        tmpList =  self.ytp.getSearchResult(pattern, searchType, page, 'Wyszukaj', config.plugins.iptvplayer.ytSortBy.value)
        for item in tmpList:
            item.update({'name':'category'})
            if 'video' == item['type']:
                self.addVideo(item)
            else:
                self.addDir(item)
                
    def getLinksForVideo(self, url):
        printDBG("Youtube.getLinksForVideo url[%s]" % url)
        ytformats = config.plugins.iptvplayer.ytformat.value
        maxRes    = int(config.plugins.iptvplayer.ytDefaultformat.value) * 1.1
        dash      = config.plugins.iptvplayer.ytShowDash.value

        if not url.startswith("http://") and not url.startswith("https://") :
            url = 'http://www.youtube.com/' + url
        tmpTab, dashTab = self.ytp.getDirectLinks(url, ytformats, dash, dashSepareteList = True)
        
        def __getLinkQuality( itemLink ):
            tab = itemLink['format'].split('x')
            return int(tab[0])
        tmpTab = CSelOneLink(tmpTab, __getLinkQuality, maxRes).getSortedLinks()
        if config.plugins.iptvplayer.ytUseDF.value and 0 < len(tmpTab):
            tmpTab = [tmpTab[0]]
        
        videoUrls = []
        for item in tmpTab:
            videoUrls.append({'name': item['format'] + ' | ' + item['ext'] , 'url':item['url']})
        for item in dashTab:
            videoUrls.append({'name': _("[dash] ") + item['format'] + ' | ' + item['ext'] , 'url':item['url']})
        return videoUrls
        
    def getFavouriteData(self, cItem):
        return cItem['url']
        
    def getLinksForFavourite(self, fav_data):
        return self.getLinksForVideo(fav_data)
    
    def handleService(self, index, refresh=0, searchPattern='', searchType=''):
        printDBG('Youtube.handleService start')
        CBaseHostClass.handleService(self, index, refresh, searchPattern, searchType)
        name     = self.currItem.get("name", None)
        category = self.currItem.get("category", '')
        printDBG( "Youtube.handleService: ---------> name[%s], category[%s] " % (name, category) )
        self.currList = []
        
        if None == name:
            self.listsMainMenu()
        elif 'from_file' == category :
            self.listCategory(self.currItem)
        elif category in ["channel","playlist","movie","traylist"]:
            self.getVideos(self.currItem)
    #WYSZUKAJ
        elif category == 'Wyszukaj':
            pattern = urllib.quote_plus(searchPattern)
            printDBG("Wyszukaj pattern[%s], type[%s]" % (pattern, searchType))
            self.getSearchResult(self.currItem, pattern, searchType)
    #HISTORIA WYSZUKIWANIAmain_item
        elif category == 'Historia wyszukiwania':
            self.listsHistory()
コード例 #4
0
class Youtube(CBaseHostClass):
    def __init__(self):
        printDBG("Youtube.__init__")
        CBaseHostClass.__init__(self, {
            'history': 'ytlist',
            'cookie': 'youtube.cookie'
        })
        self.UTLIST_FILE = 'ytlist.txt'
        self.DEFAULT_ICON_URL = 'https://www.vippng.com/png/full/85-853653_patreon-logo-png-transparent-background-youtube-logo.png'
        self.MAIN_GROUPED_TAB = [{
            'category':
            'from_file',
            'title':
            _("User links"),
            'desc':
            _("User links stored in the ytlist.txt file.")
        }, {
            'category': 'search',
            'title': _("Search"),
            'desc': _("Search youtube materials "),
            'search_item': True
        }, {
            'category': 'feeds',
            'title': _("Trending"),
            'desc': _("Browse youtube trending feeds")
        }, {
            'category': 'search_history',
            'title': _("Search history"),
            'desc': _("History of searched phrases.")
        }]

        self.SEARCH_TYPES = [
            (_("Video"), "video"),
            (_("Channel"), "channel"),
            (_("Playlist"), "playlist"),
            #(_("Movie"),    "movie"   ),
            (_("Live"), "live")
        ]
        #("Program",            "show"    ),
        #("traylist",           "traylist"),
        self.ytp = YouTubeParser()
        self.currFileHost = None

    def _getCategory(self, url):
        printDBG("Youtube._getCategory")
        if '/playlist?list=' in url:
            category = 'playlist'
        elif url.split('?')[0].endswith('/playlists'):
            category = 'playlists'
        elif None != re.search('/watch\?v=[^\&]+?\&list=', url):
            category = 'traylist'
        elif 'user/' in url or (('channel/' in url or '/c/' in url)
                                and not url.endswith('/live')):
            category = 'channel'
        else:
            category = 'video'
        return category

    def listMainMenu(self):
        printDBG("Youtube.listsMainMenu")
        for item in self.MAIN_GROUPED_TAB:
            params = {'name': 'category'}
            params.update(item)
            self.addDir(params)

    def listCategory(self, cItem, searchMode=False):
        printDBG("Youtube.listCategory cItem[%s]" % cItem)

        sortList = True
        filespath = config.plugins.iptvplayer.Sciezkaurllist.value
        groupList = True
        if 'sub_file_category' not in cItem:
            self.currFileHost = IPTVFileHost()
            self.currFileHost.addFile(filespath + self.UTLIST_FILE,
                                      encoding='utf-8')
            tmpList = self.currFileHost.getGroups(sortList)
            if 0 < len(tmpList):
                params = dict(cItem)
                params.update({
                    'sub_file_category': 'all',
                    'group': 'all',
                    'title': _("--All--")
                })
                self.addDir(params)
            for item in tmpList:
                if '' == item:
                    title = _("--Other--")
                else:
                    title = item
                params = dict(cItem)
                params.update({
                    'sub_file_category': 'group',
                    'title': title,
                    'group': item
                })
                self.addDir(params)
        else:
            if 'all' == cItem['sub_file_category']:
                tmpList = self.currFileHost.getAllItems(sortList)
                for item in tmpList:
                    params = dict(cItem)
                    category = self._getCategory(item['url'])
                    params.update({
                        'good_for_fav': True,
                        'title': item['full_title'],
                        'url': item['url'],
                        'desc': item['url'],
                        'category': category
                    })
                    if 'video' == category:
                        self.addVideo(params)
                    elif 'more' == category:
                        self.addMore(params)
                    else:
                        self.addDir(params)
            elif 'group' == cItem['sub_file_category']:
                tmpList = self.currFileHost.getItemsInGroup(
                    cItem['group'], sortList)
                for item in tmpList:
                    if '' == item['title_in_group']:
                        title = item['full_title']
                    else:
                        title = item['title_in_group']
                    params = dict(cItem)
                    category = self._getCategory(item['url'])
                    params.update({
                        'good_for_fav': True,
                        'title': title,
                        'url': item['url'],
                        'desc': item['url'],
                        'category': category
                    })
                    if 'video' == category:
                        self.addVideo(params)
                    elif 'more' == category:
                        self.addMore(params)
                    else:
                        self.addDir(params)

    def listItems(self, cItem):
        printDBG('Youtube.listItems cItem[%s]' % (cItem))
        category = cItem.get("category", '')
        url = cItem.get("url", '')
        page = cItem.get("page", '1')

        if "playlists" == category:
            self.currList = self.ytp.getListPlaylistsItems(
                url, category, page, cItem)

        for idx in range(len(self.currList)):
            if self.currList[idx]['category'] in [
                    "channel", "playlist", "movie", "traylist"
            ]:
                self.currList[idx]['good_for_fav'] = True

    def listFeeds(self, cItem):
        printDBG('Youtube.listFeeds cItem[%s]' % (cItem))
        if cItem['category'] == "feeds_video":
            sts, data = self.cm.getPage(cItem['url'])
            data2 = self.cm.ph.getAllItemsBeetwenMarkers(
                data, "videoRenderer", "watchEndpoint")
            for item in data2:
                url = "https://www.youtube.com/watch?v=" + self.cm.ph.getDataBeetwenMarkers(
                    item, 'videoId":"', '","thumbnail":', False)[1]
                icon = self.cm.ph.getDataBeetwenMarkers(
                    item, '},{"url":"', '==', False)[1]
                title = self.cm.ph.getDataBeetwenMarkers(
                    item, '"title":{"runs":[{"text":"', '"}]', False)[1]
                desc = _("Channel") + ': ' + self.cm.ph.getDataBeetwenMarkers(
                    item, 'longBylineText":{"runs":[{"text":"',
                    '","navigationEndpoint"', False
                )[1] + "\n" + _(
                    "Release:"
                ) + ' ' + self.cm.ph.getDataBeetwenMarkers(
                    item, '"publishedTimeText":{"simpleText":"',
                    '"},"lengthText":', False
                )[1] + "\n" + _(
                    "Duration:"
                ) + ' ' + self.cm.ph.getDataBeetwenMarkers(
                    item,
                    '"lengthText":{"accessibility":{"accessibilityData":{"label":"',
                    '"}},"simpleText":',
                    False)[1] + "\n" + self.cm.ph.getDataBeetwenMarkers(
                        item, '"viewCountText":{"simpleText":"',
                        '"},"navigationEndpoint":', False)[1]
                params = {
                    'title': title,
                    'url': url,
                    'icon': icon,
                    'desc': desc
                }
                self.addVideo(params)
        else:
            title = _("Trending")
            url = "https://www.youtube.com/feed/trending"
            params = {'category': 'feeds_video', 'title': title, 'url': url}
            self.addDir(params)
            title = _("Music")
            url = "https://www.youtube.com/feed/trending?bp=4gINGgt5dG1hX2NoYXJ0cw%3D%3D"
            params = {'category': 'feeds_video', 'title': title, 'url': url}
            self.addDir(params)
            title = _("Games")
            url = "https://www.youtube.com/feed/trending?bp=4gIcGhpnYW1pbmdfY29ycHVzX21vc3RfcG9wdWxhcg%3D%3D"
            params = {'category': 'feeds_video', 'title': title, 'url': url}
            self.addDir(params)
            title = _("Movies")
            url = "https://www.youtube.com/feed/trending?bp=4gIKGgh0cmFpbGVycw%3D%3D"
            params = {'category': 'feeds_video', 'title': title, 'url': url}
            self.addDir(params)

    def getVideos(self, cItem):
        printDBG('Youtube.getVideos cItem[%s]' % (cItem))

        category = cItem.get("category", '')
        url = strwithmeta(cItem.get("url", ''))
        page = cItem.get("page", '1')

        if "channel" == category:
            if not ('browse' in url) and (not 'ctoken' in url):
                if url.endswith('/videos'):
                    url = url + '?flow=list&view=0&sort=dd'
                else:
                    url = url + '/videos?flow=list&view=0&sort=dd'
            self.currList = self.ytp.getVideosFromChannelList(
                url, category, page, cItem)
        elif "playlist" == category:
            self.currList = self.ytp.getVideosFromPlaylist(
                url, category, page, cItem)
        elif "traylist" == category:
            self.currList = self.ytp.getVideosFromTraylist(
                url, category, page, cItem)
        else:
            printDBG('YTlist.getVideos Error unknown category[%s]' % category)

    def listSearchResult(self, cItem, pattern, searchType):
        page = cItem.get("page", '1')
        url = cItem.get("url", "")

        if url:
            printDBG("URL ricerca -----------> %s" % url)
            tmpList = self.ytp.getSearchResult(
                urllib.quote_plus(pattern), searchType, page, 'search',
                config.plugins.iptvplayer.ytSortBy.value, url)
        else:
            tmpList = self.ytp.getSearchResult(
                urllib.quote_plus(pattern), searchType, page, 'search',
                config.plugins.iptvplayer.ytSortBy.value)

        for item in tmpList:
            item.update({'name': 'category'})
            if 'video' == item['type']:
                self.addVideo(item)
            elif 'more' == item['type']:
                self.addMore(item)
            else:
                if item['category'] in [
                        "channel", "playlist", "movie", "traylist"
                ]:
                    item['good_for_fav'] = True
                self.addDir(item)

    def getLinksForVideo(self, cItem):
        printDBG("Youtube.getLinksForVideo cItem[%s]" % cItem)
        urlTab = self.up.getVideoLinkExt(cItem['url'])
        if config.plugins.iptvplayer.ytUseDF.value and 0 < len(urlTab):
            return [urlTab[0]]
        return urlTab

    def getFavouriteData(self, cItem):
        printDBG('Youtube.getFavouriteData')
        return json.dumps(cItem)

    def getLinksForFavourite(self, fav_data):
        printDBG('Youtube.getLinksForFavourite')
        links = []
        try:
            cItem = byteify(json.loads(fav_data))
            links = self.getLinksForVideo(cItem)
        except Exception:
            printExc()
            return self.getLinksForVideo({'url': fav_data})
        return links

    def setInitListFromFavouriteItem(self, fav_data):
        printDBG('Youtube.setInitListFromFavouriteItem')
        try:
            params = byteify(json.loads(fav_data))
        except Exception:
            params = {}
            printExc()
        self.addDir(params)
        return True

    def handleService(self, index, refresh=0, searchPattern='', searchType=''):
        printDBG('Youtube.handleService start')

        CBaseHostClass.handleService(self, index, refresh, searchPattern,
                                     searchType)

        name = self.currItem.get("name", '')
        category = self.currItem.get("category", '')
        printDBG("Youtube.handleService: ---------> name[%s], category[%s] " %
                 (name, category))
        self.currList = []

        if None == name:
            self.listMainMenu()
        elif 'from_file' == category:
            self.listCategory(self.currItem)
        elif category in ["channel", "playlist", "movie", "traylist"]:
            self.getVideos(self.currItem)
        elif category.startswith("feeds"):
            self.listFeeds(self.currItem)
        elif category == 'playlists':
            self.listItems(self.currItem)
        #SEARCH
        elif category in ["search", "search_next_page"]:
            cItem = dict(self.currItem)
            cItem.update({'search_item': False, 'name': 'category'})
            self.listSearchResult(cItem, searchPattern, searchType)
        #HISTORIA SEARCH
        elif category == "search_history":
            self.listsHistory({
                'name': 'history',
                'category': 'search'
            }, 'desc', _("Type: "))
        else:
            printExc()

        CBaseHostClass.endHandleService(self, index, refresh)

    def getSuggestionsProvider(self, index):
        printDBG('Youtube.getSuggestionsProvider')
        from Plugins.Extensions.IPTVPlayer.suggestions.google import SuggestionsProvider
        return SuggestionsProvider(True)
コード例 #5
0
class HDKinoMir(CBaseHostClass):
    def __init__(self):
        CBaseHostClass.__init__(self, {
            'history': 'HDKinoMir',
            'cookie': 'HDKinoMir.cookie'
        })
        self.USER_AGENT = "Mozilla/5.0 (Linux; U; Android 4.1.1; en-us; androVM for VirtualBox ('Tablet' version with phone caps) Build/JRO03S) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30"
        self.HEADER = {'User-Agent': self.USER_AGENT, 'Accept': 'text/html'}

        self.defaultParams = {
            'use_cookie': True,
            'load_cookie': True,
            'save_cookie': True,
            'cookiefile': self.COOKIE_FILE
        }
        self.sortCache = []
        self.catCache = []
        self.moonwalkParser = MoonwalkParser()
        self.ytParser = YouTubeParser()

        self.MAIN_URL = 'http://hdkinomir.com/'
        self.DEFAULT_ICON_URL = self.getFullIconUrl(
            '/templates/prokino/images/logo.png')

        self.MAIN_CAT_TAB = [{
            'category': 'categories',
            'title': _('Movie categories'),
            'url': self.getMainUrl()
        }, {
            'category': 'search',
            'title': _('Search'),
            'search_item': True
        }, {
            'category': 'search_history',
            'title': _('Search history')
        }]

        self.encoding = ''

    def getPage(self, url, params={}, post_data=None):
        sts, data = self.cm.getPage(url, params, post_data)
        if sts and self.encoding == '':
            self.encoding = self.cm.ph.getSearchGroups(data,
                                                       'charset=([^"]+?)"')[0]
        return sts, data

    def getFullUrl(self, url):
        url = url.replace('&amp;', '&')
        return CBaseHostClass.getFullUrl(self, url)

    def listMainMenu(self, cItem, category):
        printDBG("HDKinoMir.listCategories")
        sts, data = self.getPage(cItem['url'])
        if not sts: return

        if 0 == len(self.sortCache):
            sorData = self.cm.ph.getDataBeetwenMarkers(
                data, '<form name="news_set_sort"', '/> ', False)[1]
            sorData = re.compile(
                "dle_change_sort\('([^']+?)','([^']+?)'\)[^>]*?>([^<]+?)<"
            ).findall(sorData)
            for item in sorData:
                post_data = {
                    'dlenewssortby': item[0],
                    'dledirection': item[1],
                    'set_new_sort': 'dle_sort_cat',
                    'set_direction_sort': 'dle_direction_cat'
                }
                params = {'title': item[2], 'post_data': post_data}
                self.sortCache.append(params)

        if 0 == len(self.catCache):
            catData = self.cm.ph.getDataBeetwenMarkers(
                data, '<div class="films-category">', '</div> ', False)[1]
            catData = re.compile('href="([^"]+?)"[^>]*?>([^<]+?)<').findall(
                catData)
            for item in catData:
                params = dict(cItem)
                params.update({
                    'category': category,
                    'title': item[1],
                    'url': self.getFullUrl(item[0])
                })
                self.catCache.append(params)

        mainMenuData = self.cm.ph.getDataBeetwenMarkers(
            data, '<div class="top-menu-block">', '</ul>', False)[1]
        mainMenuData = re.compile('href="([^"]+?)"[^>]*?>([^<]+?)<').findall(
            mainMenuData)
        for item in mainMenuData:
            if item[0] in ['/actors/', '/podborki-filmov.html']: continue
            params = dict(cItem)
            params.update({
                'category': category,
                'title': item[1],
                'url': self.getFullUrl(item[0])
            })
            self.addDir(params)

        self.listsTab(self.MAIN_CAT_TAB, {'name': 'category'})

    def listContent(self, cItem, category):
        printDBG("HDKinoMir.listContent")
        sts, data = self.getPage(cItem['url'])
        if not sts: return

        desc = self.cm.ph.getDataBeetwenMarkers(
            data, '<div class="full-right-detailes">',
            '<div style="clear:both;">', False)[1]
        desc = self.cleanHtmlStr(desc)
        title = cItem['title']

        seriesData = self.cm.ph.getAllItemsBeetwenMarkers(
            data, '<strong class="seria">', '</center>', False)
        if len(seriesData) > 1:
            for item in seriesData:
                url = self.cm.ph.getSearchGroups(
                    item, '<iframe[^>]+?src="([^"]+?)"', 1, True)[0]
                if url.startswith('//'):
                    url = 'http:' + url
                params = dict(cItem)
                params['desc'] = desc
                params['url'] = url
                hostName = self.up.getHostName(url)
                if 'youtube' in hostName and 'list=' in url:
                    params.update({
                        'host_name': 'youtube_tray',
                        'category': category,
                        'title': self.cleanHtmlStr(item),
                        'serie_title': title
                    })
                    self.addDir(params)
                    continue
                if 1 == self.up.checkHostSupport(url):
                    params['title'] = '{0} - {1}'.format(
                        title, self.cleanHtmlStr(item))
                    self.addVideo(params)
            return

        data = re.compile('<iframe[^>]+?src="([^"]+?)"',
                          re.IGNORECASE).findall(data)
        for url in data:
            if url.startswith('//'):
                url = 'http:' + url
            params = dict(cItem)
            params['desc'] = desc
            params['url'] = url
            hostName = self.up.getHostName(url)
            if hostName in [
                    'serpens.nl', '37.220.36.15', 'daaidaij.com',
                    'mastarti.com'
            ]:
                hostName = 'moonwalk.cc'

            if hostName == 'moonwalk.cc' and '/serial/' in url:
                params.update({'category': category, 'serie_title': title})
                season = self.moonwalkParser.getSeasonsList(url)
                for item in season:
                    param = dict(params)
                    param.update({
                        'host_name': 'moonwalk',
                        'title': item['title'],
                        'season_id': item['id'],
                        'url': item['url']
                    })
                    self.addDir(param)
                return
            if 1 == self.up.checkHostSupport(url):
                self.addVideo(params)

    def listEpisodes(self, cItem):
        printDBG("HDKinoMir.listEpisodes")

        hostName = cItem['host_name']
        if hostName == 'moonwalk':
            title = cItem['serie_title']
            id = cItem['season_id']
            episodes = self.moonwalkParser.getEpiodesList(cItem['url'], id)

            for item in episodes:
                params = dict(cItem)
                params.update({
                    'title':
                    '{0} - s{1}e{2} {3}'.format(title, id, item['id'],
                                                item['title']),
                    'url':
                    item['url']
                })
                self.addVideo(params)
        elif hostName == 'youtube_tray':
            try:
                list = self.ytParser.getVideosFromTraylist(
                    cItem['url'], 'video', 1, cItem)
            except Exception:
                printExc()
                return
            for item in list:
                if item['category'] != 'video': continue
                self.addVideo(item)

    def listItems(self, cItem, category):
        printDBG("HDKinoMir.listItems")

        tmp = cItem['url'].split('?')
        url = tmp[0]
        if len(tmp) > 1:
            arg = tmp[1]
        else:
            arg = ''

        page = cItem.get('page', 1)
        if page > 1:
            url += 'page/%s/' % page
        if '' != arg:
            url += '?' + arg

        post_data = cItem.get('post_data', None)
        sts, data = self.getPage(url, {}, post_data)
        if not sts: return

        nextPage = False
        if ('/page/%s/' % (page + 1)) in data:
            nextPage = True

        m1 = '<div class="filmposters">'
        data = self.cm.ph.getDataBeetwenNodes(data,
                                              ('<div', '>', 'filmposters'),
                                              ('<div', '>', 'center'),
                                              False)[1]
        data = data.split(m1)

        if len(data): data[-1] = data[-1].split('<div class="navigation">')[0]
        for item in data:
            url = self.cm.ph.getSearchGroups(item, 'href="([^"]+?)"')[0]
            title = self.cm.ph.getSearchGroups(item, 'alt="([^"]+?)"')[0]
            if title == '{title}':
                title = self.cm.ph.getDataBeetwenMarkers(
                    item, '<span>', '</span>', False)[1]
            title = self.cleanHtmlStr(title)

            if title == '': continue
            icon = self.cm.ph.getSearchGroups(item, 'src="([^"]+?)"')[0]
            desc = self.cleanHtmlStr(item.split('<div class="ribbon">')[-1])
            params = dict(cItem)
            params.update({
                'category': category,
                'title': title,
                'icon': self.getFullUrl(icon),
                'desc': desc,
                'url': self.getFullUrl(url)
            })
            self.addDir(params)

        if nextPage:
            params = dict(cItem)
            params.update({
                'title': _('Next page'),
                'page': cItem.get('page', 1) + 1
            })
            self.addDir(params)

    def listSearchResult(self, cItem, searchPattern, searchType):
        #searchPattern = 'ОРБИТА'

        if self.encoding == '':
            sts, data = self.getPage(self.getMainUrl())
            if not sts: return

        try:
            searchPattern = searchPattern.decode('utf-8').encode(
                self.encoding, 'ignore')
        except Exception:
            searchPattern = ''

        post_data = {
            'do': 'search',
            'subaction': 'search',
            'story': searchPattern,
            'x': 0,
            'y': 0
        }

        sts, data = self.getPage(self.getMainUrl(), post_data=post_data)
        if not sts: return

        m1 = '<div class="filmposters">'
        data = self.cm.ph.getDataBeetwenMarkers(data, m1, '<div class="main">',
                                                False)[1]
        data = data.split(m1)
        for item in data:
            title = self.cleanHtmlStr(
                self.cm.ph.getDataBeetwenMarkers(item, '<h2', '</h2>')[1])
            if title == '':
                title = self.cleanHtmlStr(
                    self.cm.ph.getSearchGroups(
                        item, '''alt=['"]([^'^"]+?)['"]''')[0])
            icon = self.getFullIconUrl(
                self.cm.ph.getSearchGroups(item,
                                           '''src=['"]([^'^"]+?)['"]''')[0])
            url = self.getFullUrl(
                self.cm.ph.getSearchGroups(item,
                                           '''href=['"]([^'^"]+?)['"]''')[0])
            desc = self.cleanHtmlStr(
                self.cm.ph.getDataBeetwenMarkers(item, '</h2>', '</div>')[1])
            if self.cm.isValidUrl(url):
                params = dict(cItem)
                params.update({
                    'category': 'list_content',
                    'title': title,
                    'icon': icon,
                    'desc': desc,
                    'url': url
                })
                self.addDir(params)

    def getLinksForVideo(self, cItem):
        printDBG("HDKinoMir.getLinksForVideo [%s]" % cItem)
        urlTab = []
        urlTab.append({
            'name': 'Main url',
            'url': cItem['url'],
            'need_resolve': 1
        })
        return urlTab

    def getVideoLinks(self, videoUrl):
        printDBG("HDKinoMir.getVideoLinks [%s]" % videoUrl)
        urlTab = []

        if 'HDKinoMir.com' in videoUrl:
            sts, data = self.getPage(videoUrl)
            if not sts: return []
            data = self.cm.ph.getDataBeetwenMarkers(
                data, '<div class="wbox2 video dark">', '</iframe>', False)[1]
            videoUrl = self.cm.ph.getSearchGroups(
                data, '<iframe[^>]+?src="(http[^"]+?)"', 1, True)[0]

        if videoUrl.startswith('http'):
            urlTab = self.up.getVideoLinkExt(videoUrl)
        return urlTab

    def getFavouriteData(self, cItem):
        return cItem['url']

    def getLinksForFavourite(self, fav_data):
        return self.getLinksForVideo({'url': fav_data})

    def handleService(self, index, refresh=0, searchPattern='', searchType=''):
        printDBG('handleService start')

        CBaseHostClass.handleService(self, index, refresh, searchPattern,
                                     searchType)

        name = self.currItem.get("name", '')
        category = self.currItem.get("category", '')
        printDBG(
            "handleService: |||||||||||||||||||||||||||||||||||| name[%s], category[%s] "
            % (name, category))
        self.currList = []

        #MAIN MENU
        if name == None:
            self.listMainMenu(
                {
                    'name': 'category',
                    'icon': self.DEFAULT_ICON_URL,
                    'url': self.MAIN_URL
                }, 'show_sort')
        elif category == 'categories':
            self.listsTab(self.catCache, self.currItem)
        elif category == 'show_sort':
            cItem = dict(self.currItem)
            cItem['category'] = 'list_items'
            self.listsTab(self.sortCache, cItem)
        elif category == 'list_items':
            self.listItems(self.currItem, 'list_content')
        elif category == 'list_content':
            self.listContent(self.currItem, 'list_episodes')
        elif category == 'list_episodes':
            self.listEpisodes(self.currItem)
    #SEARCH
        elif category in ["search", "search_next_page"]:
            cItem = dict(self.currItem)
            cItem.update({'search_item': False, 'name': 'category'})
            self.listSearchResult(cItem, searchPattern, searchType)

    #HISTORIA SEARCH
        elif category == "search_history":
            self.listsHistory({
                'name': 'history',
                'category': 'search'
            }, 'desc', _("Type: "))
        else:
            printExc()

        CBaseHostClass.endHandleService(self, index, refresh)
コード例 #6
0
class Youtube(CBaseHostClass):
    def __init__(self):
        printDBG("Youtube.__init__")
        CBaseHostClass.__init__(self, {
            'history': 'ytlist',
            'cookie': 'youtube.cookie'
        })
        self.UTLIST_FILE = 'ytlist.txt'
        self.DEFAULT_ICON_URL = 'https://www.mm229.com/images/youtube-button-psd-450203.png'
        self.yeah = self.lenhistory()
        self.MAIN_GROUPED_TAB = [{
            'category':
            'from_file',
            'title':
            _('User links'),
            'desc':
            _('User links stored in the ytlist.txt file.')
        }, {
            'category': 'search',
            'title': _('Search'),
            'desc': _('Search youtube materials '),
            'search_item': True
        }, {
            'category': 'feeds',
            'title': _('Explore'),
            'desc': _('Popular trending videos')
        }, {
            'category': 'search_history',
            'title': _('Search history'),
            'desc': _('History of searched phrases.')
        }, {
            'category': 'delete_history',
            'title': _('Delete search history'),
            'desc': self.yeah
        }]

        self.SEARCH_TYPES = [
            (_("Video"), "video"),
            (_("Channel"), "channel"),
            (_("Playlist"), "playlist"),
            #(_("Movie"),    "movie"   ),
            (_("Live"), "live")
        ]
        #("Program",            "show"    ),
        #("traylist",           "traylist"),
        self.ytp = YouTubeParser()
        self.HTTP_HEADER = {
            'User-Agent':
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36',
            'X-YouTube-Client-Name': '1',
            'X-YouTube-Client-Version': '2.20211019.01.00',
            'X-Requested-With': 'XMLHttpRequest'
        }
        self.http_params = {'header': self.HTTP_HEADER, 'return_data': True}
        self.currFileHost = None

    def _getCategory(self, url):
        printDBG("Youtube._getCategory")
        if '/playlist?list=' in url:
            category = 'playlist'
        elif url.split('?')[0].endswith('/playlists'):
            category = 'playlists'
        elif None != re.search('/watch\?v=[^\&]+?\&list=', url):
            category = 'traylist'
        elif 'user/' in url or ('channel/' in url
                                and not url.endswith('/live')):
            category = 'channel'
        else:
            category = 'video'
        return category

    def listMainMenu(self):
        printDBG("Youtube.listsMainMenu")
        for item in self.MAIN_GROUPED_TAB:
            params = {'name': 'category'}
            params.update(item)
            self.addDir(params)

    def listCategory(self, cItem, searchMode=False):
        printDBG("Youtube.listCategory cItem[%s]" % cItem)

        sortList = True
        filespath = config.plugins.iptvplayer.Sciezkaurllist.value
        groupList = True
        if 'sub_file_category' not in cItem:
            self.currFileHost = IPTVFileHost()
            self.currFileHost.addFile(filespath + self.UTLIST_FILE,
                                      encoding='utf-8')
            tmpList = self.currFileHost.getGroups(sortList)
            if 0 < len(tmpList):
                params = dict(cItem)
                params.update({
                    'sub_file_category': 'all',
                    'group': 'all',
                    'title': _("--All--")
                })
                self.addDir(params)
            for item in tmpList:
                if '' == item:
                    title = _("--Other--")
                else:
                    title = item
                params = dict(cItem)
                params.update({
                    'sub_file_category': 'group',
                    'title': title,
                    'group': item
                })
                self.addDir(params)
        else:
            if 'all' == cItem['sub_file_category']:
                tmpList = self.currFileHost.getAllItems(sortList)
                for item in tmpList:
                    params = dict(cItem)
                    category = self._getCategory(item['url'])
                    params.update({
                        'good_for_fav': True,
                        'title': item['full_title'],
                        'url': item['url'],
                        'desc': item['url'],
                        'category': category
                    })
                    if 'video' == category:
                        self.addVideo(params)
                    elif 'more' == category:
                        self.addMore(params)
                    else:
                        self.addDir(params)
            elif 'group' == cItem['sub_file_category']:
                tmpList = self.currFileHost.getItemsInGroup(
                    cItem['group'], sortList)
                for item in tmpList:
                    if '' == item['title_in_group']:
                        title = item['full_title']
                    else:
                        title = item['title_in_group']
                    params = dict(cItem)
                    category = self._getCategory(item['url'])
                    params.update({
                        'good_for_fav': True,
                        'title': title,
                        'url': item['url'],
                        'desc': item['url'],
                        'category': category
                    })
                    if 'video' == category:
                        self.addVideo(params)
                    elif 'more' == category:
                        self.addMore(params)
                    else:
                        self.addDir(params)

    def listItems(self, cItem):
        printDBG('Youtube.listItems cItem[%s]' % (cItem))
        category = cItem.get("category", '')
        url = strwithmeta(cItem.get("url", ''))
        page = cItem.get("page", '1')

        if "playlists" == category:
            self.currList = self.ytp.getListPlaylistsItems(
                url, category, page, cItem)

        for idx in range(len(self.currList)):
            if self.currList[idx]['category'] in [
                    "channel", "playlist", "movie", "traylist"
            ]:
                self.currList[idx]['good_for_fav'] = True

    def listFeeds(self, cItem):
        printDBG('Youtube.listFeeds cItem[%s]' % (cItem))
        if cItem['category'] == "feeds_video":
            sts, data = self.cm.getPage(cItem['url'], self.http_params)
            data2 = self.cm.ph.getAllItemsBeetwenMarkers(
                data, "videoRenderer", "watchEndpoint")
            for item in data2:
                url = "https://www.youtube.com/watch?v=" + self.cm.ph.getDataBeetwenMarkers(
                    item, 'videoId":"', '","thumbnail":', False)[1]
                icon = self.cm.ph.getDataBeetwenMarkers(
                    item, '},{"url":"', '==', False)[1]
                title = self.cm.ph.getDataBeetwenMarkers(
                    item, '"title":{"runs":[{"text":"', '"}]', False)[1]
                desc = "Készítette: " + self.cm.ph.getDataBeetwenMarkers(
                    item, 'longBylineText":{"runs":[{"text":"',
                    '","navigationEndpoint"', False
                )[1] + "\n" + "Megjelent " + self.cm.ph.getDataBeetwenMarkers(
                    item, '"publishedTimeText":{"simpleText":"',
                    '"},"lengthText":', False
                )[1] + "\n" + "Videó hossza: " + self.cm.ph.getDataBeetwenMarkers(
                    item,
                    '"lengthText":{"accessibility":{"accessibilityData":{"label":"',
                    '"}},"simpleText":',
                    False)[1] + "\n" + self.cm.ph.getDataBeetwenMarkers(
                        item, '"viewCountText":{"simpleText":"',
                        '"},"navigationEndpoint":', False)[1]
                params = {
                    'title': title,
                    'url': url,
                    'icon': icon,
                    'desc': desc
                }
                self.addVideo(params)
        else:
            title = "Trending videos"
            url = "https://www.youtube.com/feed/trending"
            params = {'category': 'feeds_video', 'title': title, 'url': url}
            self.addDir(params)
            title = "Music"
            url = "https://www.youtube.com/feed/trending?bp=4gINGgt5dG1hX2NoYXJ0cw%3D%3D"
            params = {'category': 'feeds_video', 'title': title, 'url': url}
            self.addDir(params)
            title = "Gaming"
            url = "https://www.youtube.com/feed/trending?bp=4gIcGhpnYW1pbmdfY29ycHVzX21vc3RfcG9wdWxhcg%3D%3D"
            params = {'category': 'feeds_video', 'title': title, 'url': url}
            self.addDir(params)
            title = "Films"
            url = "https://www.youtube.com/feed/trending?bp=4gIKGgh0cmFpbGVycw%3D%3D"
            params = {'category': 'feeds_video', 'title': title, 'url': url}
            self.addDir(params)

    def getVideos(self, cItem):
        printDBG('Youtube.getVideos cItem[%s]' % (cItem))

        category = cItem.get("category", '')
        url = cItem.get("url", '')
        page = cItem.get("page", '1')

        if "channel" == category:
            if not ('browse' in url) and (not 'ctoken' in url):
                if url.endswith('/videos'):
                    url = url + '?flow=list&view=0&sort=dd'
                else:
                    url = url + '/videos?flow=list&view=0&sort=dd'
            self.currList = self.ytp.getVideosFromChannelList(
                url, category, page, cItem)
        elif "playlist" == category:
            self.currList = self.ytp.getVideosFromPlaylist(
                url, category, page, cItem)
        elif "traylist" == category:
            self.currList = self.ytp.getVideosFromTraylist(
                url, category, page, cItem)
        else:
            printDBG('YTlist.getVideos Error unknown category[%s]' % category)

    def listSearchResult(self, cItem, pattern, searchType):
        page = cItem.get("page", '1')
        url = cItem.get("url", "")

        if url:
            printDBG("URL ricerca -----------> %s" % url)
            tmpList = self.ytp.getSearchResult(
                urllib.quote_plus(pattern), searchType, page, 'search',
                config.plugins.iptvplayer.ytSortBy.value, url)
        else:
            tmpList = self.ytp.getSearchResult(
                urllib.quote_plus(pattern), searchType, page, 'search',
                config.plugins.iptvplayer.ytSortBy.value)

        for item in tmpList:
            item.update({'name': 'category'})
            if 'video' == item['type']:
                self.addVideo(item)
            elif 'more' == item['type']:
                self.addMore(item)
            else:
                if item['category'] in [
                        "channel", "playlist", "movie", "traylist"
                ]:
                    item['good_for_fav'] = True
                self.addDir(item)

    def getLinksForVideo(self, cItem):
        printDBG("Youtube.getLinksForVideo cItem[%s]" % cItem)
        urlTab = self.up.getVideoLinkExt(cItem['url'])
        if config.plugins.iptvplayer.ytUseDF.value and 0 < len(urlTab):
            return [urlTab[0]]
        return urlTab

    def getFavouriteData(self, cItem):
        printDBG('Youtube.getFavouriteData')
        return json.dumps(cItem)

    def getLinksForFavourite(self, fav_data):
        printDBG('Youtube.getLinksForFavourite')
        links = []
        try:
            cItem = byteify(json.loads(fav_data))
            links = self.getLinksForVideo(cItem)
        except Exception:
            printExc()
            return self.getLinksForVideo({'url': fav_data})
        return links

    def setInitListFromFavouriteItem(self, fav_data):
        printDBG('Youtube.setInitListFromFavouriteItem')
        try:
            params = byteify(json.loads(fav_data))
        except Exception:
            params = {}
            printExc()
        self.addDir(params)
        return True

    def handleService(self, index, refresh=0, searchPattern='', searchType=''):
        printDBG('Youtube.handleService start')

        CBaseHostClass.handleService(self, index, refresh, searchPattern,
                                     searchType)

        name = self.currItem.get("name", '')
        category = self.currItem.get("category", '')
        printDBG("Youtube.handleService: ---------> name[%s], category[%s] " %
                 (name, category))
        self.currList = []

        if None == name:
            self.listMainMenu()
        elif 'from_file' == category:
            self.listCategory(self.currItem)
        elif category in ["channel", "playlist", "movie", "traylist"]:
            self.getVideos(self.currItem)
        elif category.startswith("feeds"):
            self.listFeeds(self.currItem)
        elif category == 'playlists':
            self.listItems(self.currItem)
        #SEARCH
        elif category in ["search", "search_next_page"]:
            cItem = dict(self.currItem)
            cItem.update({'search_item': False, 'name': 'category'})
            self.listSearchResult(cItem, searchPattern, searchType)
        #HISTORIA SEARCH
        elif category == "search_history":
            self.listsHistory({
                'name': 'history',
                'category': 'search'
            }, 'desc', _("Type: "))
        elif category == "delete_history":
            self.delhistory()
        else:
            printExc()
        self.yeah = self.lenhistory()

        CBaseHostClass.endHandleService(self, index, refresh)

    def delhistory(self):
        printDBG('Youtube.delhistory')
        msg = 'Are you sure you want to delete search history?'
        ret = self.sessionEx.waitForFinishOpen(MessageBox,
                                               msg,
                                               type=MessageBox.TYPE_YESNO,
                                               default=True)
        if ret[0]:
            self.doit()

    def doit(self):
        try:
            os.remove(GetSearchHistoryDir("ytlist.txt"))
            msg = 'Search History successfully deleted.'
            ret = self.sessionEx.waitForFinishOpen(MessageBox,
                                                   msg,
                                                   type=MessageBox.TYPE_INFO)
        except:
            msg = 'Unable to comply. Search History is empty.'
            ret = self.sessionEx.waitForFinishOpen(MessageBox,
                                                   msg,
                                                   type=MessageBox.TYPE_INFO)

    def lenhistory(self):
        num = 0

        try:
            file = codecs.open(GetSearchHistoryDir("ytlist.txt"), 'r', 'utf-8',
                               'ignore')
            for line in file:
                num = num + 1
            file.close()
        except:
            return ("Search History is empty.")
        return ("Number of items in search history: " + str(num))

    def getSuggestionsProvider(self, index):
        printDBG('Youtube.getSuggestionsProvider')
        from Plugins.Extensions.IPTVPlayer.suggestions.google import SuggestionsProvider
        return SuggestionsProvider(True)