Esempio n. 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)
Esempio n. 2
0
class MaxtvGO(CBaseHostClass):
    
    def __init__(self):
        CBaseHostClass.__init__(self, {'history':'maxtvgo.com', 'cookie':'maxtvgo.com.cookie'})
        self.DEFAULT_ICON_URL = 'https://maxtvgo.com/images/logo_37.png'
        self.USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0'
        self.MAIN_URL = 'https://maxtvgo.com/'
        self.HTTP_HEADER = {'User-Agent': self.USER_AGENT, 'DNT':'1', 'Accept': 'text/html', 'Accept-Encoding':'gzip, deflate', 'Referer':self.getMainUrl(), 'Origin':self.getMainUrl()}
        self.AJAX_HEADER = dict(self.HTTP_HEADER)
        self.AJAX_HEADER.update( {'X-Requested-With': 'XMLHttpRequest', 'Accept-Encoding':'gzip, deflate', 'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8', 'Accept':'application/json, text/javascript, */*; q=0.01'} )
        
        self.defaultParams = {'header':self.HTTP_HEADER, 'use_cookie': True, 'load_cookie': True, 'save_cookie': True, 'cookiefile': self.COOKIE_FILE}
        
        self.MAIN_CAT_TAB = [{'category':'list_items',        'title': 'MaxTVGo',             'url':self.getFullUrl('/api/videos.php?action=find')},
                             {'category':'list_yt_channel',   'title': 'Max Kolonko - MaxTV', 'url':'https://www.youtube.com/user/Media2000Corp/videos' },
                             {'category':'list_yt_channel',   'title': 'MaxTVNews',           'url':'https://www.youtube.com/user/MaxTVTUBE/videos'},
                             {'category':'search',          'title': _('Search'), 'search_item':True, },
                             {'category':'search_history',  'title': _('Search history'),             } 
                            ]
        self.ytp = YouTubeParser()
        self.loggedIn = None
        self.login    = ''
        self.password = ''
        
    def getPage(self, baseUrl, addParams = {}, post_data = None):
        if addParams == {}: addParams = dict(self.defaultParams)
        origBaseUrl = baseUrl
        baseUrl = self.cm.iriToUri(baseUrl)
        def _getFullUrl(url):
            if self.cm.isValidUrl(url): return url
            else: return urlparse.urljoin(baseUrl, url)
        addParams['cloudflare_params'] = {'domain':self.up.getDomain(baseUrl), 'cookie_file':self.COOKIE_FILE, 'User-Agent':self.USER_AGENT, 'full_url_handle':_getFullUrl}
        return self.cm.getPageCFProtection(baseUrl, addParams, post_data)
        
    def listMainMenu(self, cItem, nextCategory):
        printDBG("MaxtvGO.listMainMenu")
        self.listsTab(self.MAIN_CAT_TAB, cItem)
        
    def getFullIconUrl(self, url):
        url = CBaseHostClass.getFullIconUrl(self, url.strip())
        if url == '': return ''
        cookieHeader = self.cm.getCookieHeader(self.COOKIE_FILE)
        return strwithmeta(url, {'Cookie':cookieHeader, 'User-Agent':self.USER_AGENT, 'Referer':self.getMainUrl()})
        
    def listItems(self, cItem, nextCategory):
        printDBG("MaxtvGO.listItems [%s]" % cItem)
        
        sts, data = self.getPage(cItem['url'])
        if not sts: return
        
        try:
            data = byteify(json.loads(data))
            if data.get('error') != None:
                SetIPTVPlayerLastHostError(str(data['error']['message']))
            for item in data['data']:
                sTitle = self.cleanHtmlStr(item['name'])
                subItems = []
                for it in item['videos']:
                    title = self.cleanHtmlStr(it['title'])
                    #icon = self.getFullIconUrl(it['image'])
                    icon = str(it.get('vimeoPosterId', ''))
                    if icon != '': icon = 'http://i.vimeocdn.com/video/%s.jpg?mw=300' % icon
                    url = self.getFullUrl('video.php?film=') + it['code']
                    params = dict(cItem)
                    params.update({'type':'video', 'good_for_fav':True, 'title':title, 'url':url, 'icon':icon})
                    subItems.append(params)
                
                if len(subItems):
                    params = dict(cItem)
                    params.update({'category':nextCategory, 'good_for_fav':False, 'title':sTitle, 'sub_items':subItems})
                    self.addDir(params)
            
        except Exception:
            printExc()
        
            if self.loggedIn != True and 0 == len(self.currList):
                msg = _('The host %s requires registration. \nPlease fill your login and password in the host configuration. Available under blue button.' % self.getMainUrl())
                GetIPTVNotify().push(msg, 'error', 10)
        
    def listYTChannel(self, cItem):
        printDBG('MaxtvGO.getVideos cItem[%s]' % (cItem))
        
        category = cItem.get("category", '')
        url      = cItem.get("url", '')
        page     = cItem.get("page", '1')
        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'
        params = dict(cItem)
        self.currList = self.ytp.getVideosFromChannelList(url, category, page, params)
        for idx in range(len(self.currList)):
            if self.currList[idx].get('type', '') == 'video':
                self.currList[idx]['good_for_fav'] = True
        
    def getLinksForVideo(self, cItem):
        printDBG("MaxtvGO.getLinksForVideo [%s]" % cItem)
        
        if 1 == self.up.checkHostSupport(cItem.get('url', '')):
            videoUrl = cItem['url'].replace('youtu.be/', 'youtube.com/watch?v=')
            return self.up.getVideoLinkExt(videoUrl)
        
        self.tryTologin()
        
        retTab = []
        
        sts, data = self.getPage(cItem['url'])
        if not sts: return
        
        cookieHeader = self.cm.getCookieHeader(self.COOKIE_FILE)
        
        tmp = self.cm.ph.getDataBeetwenMarkers(data, '<video', '</video>')[1]
        tmp = self.cm.ph.getAllItemsBeetwenMarkers(tmp, '<source', '>')
        for item in tmp:
            url = self.getFullUrl(self.cm.ph.getSearchGroups(item, '''src=['"]([^'^"]+?)['"]''')[0])
            if not self.cm.isValidUrl(url): continue
            type = self.getFullUrl(self.cm.ph.getSearchGroups(item, '''type=['"]([^'^"]+?)['"]''')[0]).lower()
            if 'mp4' in type:
                url = strwithmeta(self.getFullUrl(url), {'Cookie':cookieHeader, 'User-Agent':self.USER_AGENT, 'Referer':cItem['url']})
                retTab.append({'name':'direct', 'url':url, 'need_resolve':0})
            else:
                printDBG("Unknown source: [%s]" % item)
        
        data = self.cm.ph.getDataBeetwenNodes(data, ('<div', '>', 'player'), ('</div', '>'), False)[1]
        videoUrl = self.getFullUrl(self.cm.ph.getSearchGroups(data, '''<iframe[^>]+?src=['"]([^"^']+?)['"]''', 1, True)[0], self.cm.meta['url'])
        if videoUrl != '':
            videoUrl = strwithmeta(videoUrl, {'User-Agent':self.USER_AGENT, 'Referer':self.cm.meta['url']})
            retTab.extend(self.up.getVideoLinkExt(videoUrl))
        
        return retTab
        
    def listSearchResult(self, cItem, searchPattern, searchType):
        printDBG("MaxtvGO.listSearchResult cItem[%s], searchPattern[%s] searchType[%s]" % (cItem, searchPattern, searchType))
        self.tryTologin()
        
        cItem = dict(cItem)
        cItem['url'] = self.getFullUrl('/api/videos.php?action=find&fullText=') + urllib.quote_plus(searchPattern)
        self.listItems(cItem, 'sub_items')
    
    def tryTologin(self):
        printDBG('tryTologin start')
        
        if None == self.loggedIn or self.login != config.plugins.iptvplayer.maxtvgo_login.value or\
            self.password != config.plugins.iptvplayer.maxtvgo_password.value:
        
            self.login = config.plugins.iptvplayer.maxtvgo_login.value
            self.password = config.plugins.iptvplayer.maxtvgo_password.value
            
            rm(self.COOKIE_FILE)
            
            self.loggedIn = False
            
            if '' == self.login.strip() or '' == self.password.strip():
                return False
            
            sts, data = self.getPage(self.getFullUrl('/login.php'))
            if not sts: return False
            
            sts, data = self.cm.ph.getDataBeetwenNodes(data, ('<form', '>', 'login'), ('</form', '>'))
            if not sts: return False
            actionUrl = self.getFullUrl(self.cm.ph.getSearchGroups(data, '''action=['"]([^'^"]+?)['"]''')[0])
            data = self.cm.ph.getAllItemsBeetwenMarkers(data, '<input', '>')
            post_data = {}
            for item in data:
                name  = self.cm.ph.getSearchGroups(item, '''name=['"]([^'^"]+?)['"]''')[0]
                value = self.cm.ph.getSearchGroups(item, '''value=['"]([^'^"]+?)['"]''')[0]
                post_data[name] = value
            
            post_data.update({'email':self.login, 'pass':self.password})
            
            httpParams = dict(self.defaultParams)
            httpParams['header'] = dict(httpParams['header'])
            httpParams['header']['Referer'] = self.getFullUrl('/index.php')
            sts, data = self.cm.getPage(actionUrl, httpParams, post_data)
            if sts and 'logout.php' in data:
                printDBG('tryTologin OK')
                self.loggedIn = True
            else:
                self.sessionEx.open(MessageBox, _('Login failed.'), type = MessageBox.TYPE_ERROR, timeout = 10)
                printDBG('tryTologin failed')
        return self.loggedIn
        
    def getArticleContent(self, cItem, data=None):
        printDBG("MaxtvGO.getArticleContent [%s]" % cItem)
        self.tryTologin()
        
        if self.up.getDomain(cItem['url']) not in self.up.getDomain(self.getMainUrl()):
            return []
        
        sts, data = self.getPage(cItem['url'])
        if not sts: return []
        
        videoID = self.cm.ph.getSearchGroups(data, '''(<input[^>]+?videoID[^>]+?>)''', 1, True)[0]
        videoID = self.cm.ph.getSearchGroups(videoID, '''\svalue=['"]([^'^"]+?)['"]''', 1, True)[0]
        
        if videoID == '':
            return []
        
        otherInfo = {}
        retTab = []
        desc = []
        
        desc = self.cm.ph.getDataBeetwenNodes(data, ('<div', '>', 'chat_round'), ('<div', '>', 'CommentsSection'))[1]
        desc = [self.cleanHtmlStr(desc.replace('</p>', '[/br]')) + '[/br][/br]']
        
        icon = self.cm.ph.getDataBeetwenNodes(data, ('<video', '>'), ('</video', '>'))[1]
        icon = self.getFullIconUrl(self.cm.ph.getSearchGroups(icon, '''poster=['"]([^'^"]+?)['"]''')[0])
        #icon = ''
        title = self.cleanHtmlStr(self.cm.ph.getDataBeetwenNodes(data, ('<div', '>', 'video-title'), ('</p', '>'), False)[1])
        
        urlBase = self.getFullUrl('/api/comments.php?action=get&videoID=%s' % videoID)
        try:
            for page in range(4):
                url = urlBase
                if page > 0:
                    url += '&page=%s' % page
                
                sts, data = self.getPage(url)
                if sts:
                    data = byteify(json.loads(data))
                    for item in data['data']:
                        author = self.cleanHtmlStr(item['nick'])
                        date   = self.cleanHtmlStr(item['date'])
                        text   = self.cleanHtmlStr(item['text'])
                        desc.append('%s | %s[/br]%s[/br]' % (date, author, text))
                        printDBG("============================================================================")
                        printDBG('%s\t%s\n%s\n' % (author, date, text))
        except Exception:
            printExc()
        
        desc = '------------------------------------------------------------------------------[/br]'.join(desc)
        
        if title == '': title = cItem['title']
        if desc == '':  desc = cItem.get('desc', '')
        if icon == '':  icon = cItem.get('icon', self.DEFAULT_ICON_URL)
        
        return [{'title':self.cleanHtmlStr( title ), 'text': self.cleanHtmlStr( desc ), 'images':[{'title':'', 'url':self.getFullIconUrl(icon)}], 'other_info':otherInfo}]
    
    def handleService(self, index, refresh = 0, searchPattern = '', searchType = ''):
        printDBG('handleService start')
        
        self.tryTologin()
        
        CBaseHostClass.handleService(self, index, refresh, searchPattern, searchType)

        name     = self.currItem.get("name", '')
        category = self.currItem.get("category", '')
        mode     = self.currItem.get("mode", '')
        
        printDBG( "handleService: || name[%s], category[%s] " % (name, category) )
        self.currList = []
        
    #MAIN MENU
        if name == None:
            self.listMainMenu({'name':'category'}, 'list_genres')
        elif category == 'list_filters':
            self.listFilters(self.currItem, 'list_items')
        elif category == 'list_items':
            self.listItems(self.currItem, 'sub_items')
        elif category == 'list_yt_channel':
            self.listYTChannel(self.currItem)
        elif category == 'sub_items':
            self.currList = self.currItem.get('sub_items', [])
    #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)
Esempio n. 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()
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()
Esempio n. 5
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)
Esempio n. 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)