def errorlist(params,url,category):
	xbmc.output("[descargadoslist.py] errorlist")

	# Crea el directorio de la lista de descargas con error si no existe
	try:
		os.mkdir(DOWNLOAD_PATH)
	except:
		pass
	try:
		os.mkdir(ERROR_PATH)
	except:
		pass

	# Crea un listado con las entradas de favoritos
	xbmc.output("[downloadall.py] ERROR_PATH="+ERROR_PATH)
	ficheros = os.listdir(ERROR_PATH)
	for fichero in ficheros:
		xbmc.output("[downloadall.py] fichero="+fichero)
		try:
			# Lee el bookmark
			titulo,thumbnail,plot,server,url = readbookmarkfile(fichero,ERROR_PATH)

			# Crea la entrada
			# En la categoría va el nombre del fichero para poder borrarlo
			xbmctools.addnewvideo( CHANNELNAME , "playerror" , os.path.join( ERROR_PATH, fichero ) , server , titulo , url , thumbnail, plot )
		except:
			pass
			xbmc.output("[downloadall.py] error al leer bookmark")
			for line in sys.exc_info():
				xbmc.output( "%s" % line , xbmc.LOGERROR )

	# Label (top-right)...
	xbmcplugin.setPluginCategory( handle=int( sys.argv[ 1 ] ), category=category )
	xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_NONE )
	xbmcplugin.endOfDirectory( handle=int( sys.argv[ 1 ] ), succeeded=True )
def build_featured_directory( page ):
	save_page = page
	data = getUrl( 'http://www.traileraddict.com/attraction/' + str( int( page ) + 1) )
	url_thumb_x_title = re.compile( '<a href="/trailer/(.+?)"><img src="(.+?)" border="0" alt="(.+?)" title="(.+?)" style="margin:8px 5px 2px 5px;"></a>' ).findall( data )
	totalItems = len(url_thumb_x_title)
	for url, thumb, x, title in url_thumb_x_title:
		title = title.rsplit( ' - ' )
		name1 = clean( title[0] )
		if len( title ) > 1:
			name2 = clean( title[0] ) + ' (' + clean( title[1] ) + ')'
		else:
			name2 = clean( title[0] )
		url = 'http://www.traileraddict.com/trailer/' + url
		thumb = 'http://www.traileraddict.com' + thumb
		cm = []
		run = sys.argv[0] + '?' + urllib.urlencode({ 'mode': '5', 'name': name2, 'url': url, 'download': 'True' })
		cm.append( (settings.getLocalizedString(30059), "XBMC.RunPlugin(%s)" % run) )
		cm.append( (settings.getLocalizedString(30014), "XBMC.RunPlugin(plugin://plugin.video.couchpotato_manager/movies/add?title=%s)" % name1) )
		u = { 'mode': '5', 'name': name2, 'url': url }
		addListItem(label = name1, image = thumb, url = u, isFolder = False, totalItems = totalItems, infoLabels = False, cm = cm)
	u = { 'mode': '6', 'page': str( int( save_page ) + 1 ) }
	addListItem(label = '[ Next Page (' + str( int( save_page ) + 2 ) + ') ]', image = next_thumb, url = u, isFolder =  True, totalItems = 0, infoLabels = False)
	xbmcplugin.addSortMethod( handle = int(sys.argv[1]), sortMethod = xbmcplugin.SORT_METHOD_NONE )
	setViewMode("500", "movies")
	xbmcplugin.endOfDirectory( int( sys.argv[1] ) )
def build_main_directory():
	main=[
		( settings.getLocalizedString(30000), search_thumb, '0' ),
		( settings.getLocalizedString(30001), film_reel_thumb, '1' ),
		( settings.getLocalizedString(30002), clapperboard_thumb, '2' ),
		( settings.getLocalizedString(30003), oscar_thumb, '3' ),
		( settings.getLocalizedString(30004), popcorn_thumb, '6' ),
		( settings.getLocalizedString(30015), library_thumb, '7' )
		]
	for name, thumbnailImage, mode in main:
		listitem = xbmcgui.ListItem( label = name, iconImage = "DefaultVideo.png", thumbnailImage = thumbnailImage )
		u = { 'mode': mode, 'name': name }
		addListItem(label = name, image = thumbnailImage, url = u, isFolder = True, totalItems = 0, infoLabels = False)
	data = getUrl( 'http://www.traileraddict.com' )
	url_thumb_x_title = re.compile( '<a href="/trailer/(.+?)"><img src="(.+?)" border="0" alt="(.+?)" title="(.+?)" style="margin:2px 10px 8px 10px;">' ).findall( data )
	totalItems = len(url_thumb_x_title)
	for url, thumb, x, title in url_thumb_x_title:
		title = title.rsplit( ' - ' )
		name1 = clean( title[0] )
		if len( title ) > 1:
			name2 = clean( title[0] ) + ' (' + clean( title[1] ) + ')'
		else:
			name2 = clean( title[0] )
		url = 'http://www.traileraddict.com/trailer/' + url
		thumb = 'http://www.traileraddict.com' + thumb
		cm = []
		run = sys.argv[0] + '?' + urllib.urlencode({ 'mode': '5', 'name': name2, 'url': url, 'download': 'True' })
		cm.append( (settings.getLocalizedString(30059), "XBMC.RunPlugin(%s)" % run) )
		cm.append( (settings.getLocalizedString(30014), "XBMC.RunPlugin(plugin://plugin.video.couchpotato_manager/movies/add?title=%s)" % name1) )
		u = { 'mode': '5', 'name': name2, 'url': url }
		addListItem(label = name1, image = thumb, url = u, isFolder = False, totalItems = totalItems, infoLabels = False, cm = cm)
	xbmcplugin.addSortMethod( handle = int(sys.argv[1]), sortMethod = xbmcplugin.SORT_METHOD_NONE )
	setViewMode("500", "movies")
	xbmcplugin.endOfDirectory( int( sys.argv[1] ) )
Пример #4
0
def build_programs_directory( name, page ):
	start = str( 200 * page )
	#data = cove.programs.filter(fields='associated_images,mediafiles,categories',filter_categories__namespace__name='COVE Taxonomy',order_by='title',limit_start=start)['results']
	if name:
		data = cove.programs.filter(fields='associated_images,mediafiles',filter_producer__name='PBS',order_by='title',limit_start=start,filter_title=name)['results']
	else:
		data = cove.programs.filter(fields='associated_images,mediafiles',filter_producer__name='PBS',order_by='title',limit_start=start)['results']
	for results in data:
		if len(results['nola_root'].strip()) != 0:
			if len(results['associated_images']) >= 2:
				thumb = results['associated_images'][1]['url']
			else:
				thumb = programs_thumb
			program_id = re.compile( '/cove/v1/programs/(.*?)/' ).findall( results['resource_uri'] )[0]
			listitem = xbmcgui.ListItem( label = results['title'], iconImage = thumb, thumbnailImage = thumb )
			listitem.setProperty('fanart_image',fanart)
			listitem.setInfo( type="Video", infoLabels={ "Title": results['title'].encode('utf-8'), "Plot": clean(results['long_description']) } )
			u = sys.argv[0] + '?mode=0&name=' + urllib.quote_plus( results['title'].encode('utf-8') ) + '&program_id=' + urllib.quote_plus( program_id )
			ok = xbmcplugin.addDirectoryItem( handle = int( sys.argv[1] ), url = u, listitem = listitem, isFolder = True )
	if ( len(data) ) == 200:
		listitem = xbmcgui.ListItem( label = '[Next Page (' + str( int( page ) + 2 ) + ')]' , iconImage = next_thumb, thumbnailImage = next_thumb )
		listitem.setProperty('fanart_image',fanart)
		u = sys.argv[0] + '?mode=1&page=' + str( int( page ) + 1 )
		ok = xbmcplugin.addDirectoryItem( handle = int( sys.argv[1] ), url = u, listitem = listitem, isFolder = True )
	xbmcplugin.addSortMethod( handle = int(sys.argv[1]), sortMethod = xbmcplugin.SORT_METHOD_NONE )
	xbmcplugin.endOfDirectory( int( sys.argv[1] ) )
def build_search_directory(name, url):
	if url != 'library':
		keyboard = xbmc.Keyboard( '', settings.getLocalizedString(30007) )
		keyboard.doModal()
		if ( keyboard.isConfirmed() == False ):
			return
		search_string = keyboard.getText().replace( ' ', '+' )
		if len( search_string ) == 0:
			return
	else:
		search_string = name
	data = getUrl( 'http://www.traileraddict.com/search.php?q=' + search_string )
	image = re.compile( '<center>\r\n<div style="background:url\((.*?)\);" class="searchthumb">', re.DOTALL ).findall( data )
	link_title = re.compile( '</div><a href="/tags/(.*?)">(.*?)</a><br />' ).findall( data )
	if len( link_title ) == 0:
		if url == 'library':
			return None
		dialog = xbmcgui.Dialog()
		ok = dialog.ok( plugin , settings.getLocalizedString(30009) + search_string + '.\n' + settings.getLocalizedString(30010) )
		build_main_directory()
		return
	item_count=0
	totalItems = len(link_title)
	if url == 'library':
		return link_title[0][0]
	for url, title in link_title:
		url = 'http://www.traileraddict.com/tags/' + url
		thumb = 'http://www.traileraddict.com' + image[item_count].replace( '/pthumb.php?dir=', '' ).replace( '\r\n', '' )
		u = { 'mode': '4', 'name': clean( title ), 'url': url }
		addListItem(label = clean( title ), image = thumb, url = u, isFolder = True, totalItems = totalItems, infoLabels = False)
		item_count = item_count + 1
	xbmcplugin.addSortMethod( handle = int( sys.argv[1] ), sortMethod = xbmcplugin.SORT_METHOD_NONE )
	xbmcplugin.endOfDirectory( int( sys.argv[1] ) )
def listChannels(type):
        xbmcplugin.addSortMethod(pluginhandle, xbmcplugin.SORT_METHOD_LABEL)
        content = getUrl("http://redux.com/hg.shellinit")
        content = content[content.find('"'+type+'":'):]
        content = content[:content.find('</div>\\n</div>\\n\\n",')]
        spl=content.split("<div class='chan'")
        for i in range(1,len(spl),1):
            entry=spl[i]
            match=re.compile("<div class='title'>(.+?)</div>", re.DOTALL).findall(entry)
            match2=re.compile("<div class=&#39;title&#39;>(.+?)</div>", re.DOTALL).findall(entry)
            if len(match)>0:
              title=match[0]
            elif len(match2)>0:
              title=match2[0]
            title=cleanTitle(title)
            id = entry[entry.find('chid=\\"')+7:]
            id = id[:id.find('\\"')]
            match=re.compile("preload='(.+?)'", re.DOTALL).findall(entry)
            thumb=match[0]
            if tvMode==True:
              addLink(title,id,'playAll',thumb)
            else:
              addDir(title,id,'listVideos',thumb)
        xbmcplugin.endOfDirectory(pluginhandle)
        if forceViewMode==True:
          xbmc.executebuiltin('Container.SetViewMode('+viewMode+')')
def mainlist(params,url,category):
	logger.info("[favoritos.py] mainlist")

	import xbmctools

	# Crea un listado con las entradas de favoritos
	if usingsamba:
		ficheros = samba.get_files(BOOKMARK_PATH)
	else:
		ficheros = os.listdir(BOOKMARK_PATH)
	ficheros.sort()
	for fichero in ficheros:

		try:
			# Lee el bookmark
			titulo,thumbnail,plot,server,url = readbookmark(fichero)

			# Crea la entrada
			# En la categoría va el nombre del fichero para poder borrarlo
			xbmctools.addnewvideo( CHANNELNAME , "play" , os.path.join( BOOKMARK_PATH, fichero ) , server , titulo , url , thumbnail, plot )
		except:
			pass

	# Label (top-right)...
	xbmcplugin.setPluginCategory( handle=int( sys.argv[ 1 ] ), category=category )
	xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_NONE )
	xbmcplugin.endOfDirectory( handle=int( sys.argv[ 1 ] ), succeeded=True )
def searchresults(params,url,category):
	xbmc.output("[peliculasyonkis.py] searchresults")

	if xbmctools.getPluginSetting("forceview")=="true":
		xbmc.executebuiltin("Container.SetViewMode(53)")  #53=icons

	# Descarga la página
	data = scrapertools.cachePage(url)
	#xbmc.output(data)

	# Extrae las entradas (carpetas)
	#<li> <a href="http://www.peliculasyonkis.com/pelicula/las-edades-de-lulu-1990/" title="Las edades de Lulú (1990)"><img width="77" height="110" src="http://images.peliculasyonkis.com/thumbs/las-edades-de-lulu-1990.jpg" alt="Las edades de Lulú (1990)" align="right" />
	
	patronvideos  = '<li> <a href="([^"]+)" title="([^"]+)"><img.*?src="([^"]+)"'
	matches = re.compile(patronvideos,re.DOTALL).findall(data)
	scrapertools.printMatches(matches)

	for match in matches:
		scrapedtitle = match[1]
		scrapedurl = match[0]
		scrapedthumbnail = match[2]
		scrapedplot = ""
		if (DEBUG): xbmc.output("title=["+scrapedtitle+"], url=["+scrapedurl+"], thumbnail=["+scrapedthumbnail+"]")
		xbmctools.addnewvideo( CHANNELNAME , "detail" , category , "Megavideo" , scrapedtitle , scrapedurl , scrapedthumbnail , scrapedplot )

	# Label (top-right)...
	xbmcplugin.setPluginCategory( handle=int( sys.argv[ 1 ] ), category=category )

	# Disable sorting...
	xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_NONE )

	# End of directory...
	xbmcplugin.endOfDirectory( handle=int( sys.argv[ 1 ] ), succeeded=True )
def mainlist(params, url, category):
    xbmc.output("[veocine.py] mainlist")

    # Añade al listado de XBMC
    xbmctools.addnewfolder(CHANNELNAME, "videolist", "", "Peliculas", "http://www.veocine.es/peliculas.html", "", "")
    xbmctools.addnewfolder(
        CHANNELNAME, "videolist", "", "Documentales", "http://www.veocine.es/documentales.html", "", ""
    )
    xbmctools.addnewfolder(
        CHANNELNAME, "videolist", "", "Peliculas infantiles", "http://www.veocine.es/infantil.html", "", ""
    )
    xbmctools.addnewfolder(
        CHANNELNAME, "videolist", "", "Peliculas VOS", "http://www.veocine.es/peliculavos.html", "", ""
    )
    xbmctools.addnewfolder(CHANNELNAME, "videolist", "", "Anime", "http://www.veocine.es/anime.html", "", "")

    if xbmctools.getPluginSetting("singlechannel") == "true":
        xbmctools.addSingleChannelOptions(params, url, category)

        # Label (top-right)...
    xbmcplugin.setPluginCategory(handle=int(sys.argv[1]), category=category)

    # Disable sorting...
    xbmcplugin.addSortMethod(handle=int(sys.argv[1]), sortMethod=xbmcplugin.SORT_METHOD_NONE)

    # End of directory...
    xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=True)
Пример #10
0
def getCats(byCountry):
    log("> getCats() byCountry=%s" % byCountry)
    ok = False

    doc = getURL(URL_INDEX, FILE_INDEX_PAGE)
    if doc:
        log("getCats() parsing ...")
        try:
            # get section
            baseRE = '<p>Browse by $SECTION.*?</div>(.+?)</tr></tbody></table></div><br />'
            if byCountry:
                sectionRE = baseRE.replace('$SECTION','country')
            else:
                sectionRE = baseRE.replace('$SECTION','genre')
            #section = re.search(sectionRE, doc, re.IGNORECASE + re.MULTILINE + re.DOTALL).group(1)
            section = re.search('(?ims)' + sectionRE, doc).group(1)

            # parse info from section
            p=re.compile('<a href="(.+?)".*?>(.+?)</a', re.IGNORECASE)
            matches = p.findall(section)
            for page, name in matches:
                url = "/".join([BASE_URL,page])
                addDirectoryItem(name,url,1)

            xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_LABEL )
            ok = True
        except:
            errorOK("getCats()")

    log("< getCats() ok=%s" % ok)
    return ok
def ListadoTotal(params,url,category):
	logger.info("[peliculas24h.py] ListadoTotal")

	# Descarga la p�gina
	data = scrapertools.cachePage(url)
	#logger.info(data)

	# Patron de las entradas
	patron = "<a dir='ltr' href='([^']+)'>(.*?)</a>"
	matches = re.compile(patron,re.DOTALL).findall(data)
	scrapertools.printMatches(matches)

	# A�ade las entradas encontradas
	for match in matches:
		# Atributos
		scrapedtitle = match[1]
		scrapedurl = match[0]
		scrapedthumbnail = ""
		scrapedplot = ""
		if (DEBUG): logger.info("title=["+scrapedtitle+"], url=["+scrapedurl+"], thumbnail=["+scrapedthumbnail+"]")

		# A�ade al listado de XBMC
		xbmctools.addnewfolder( CHANNELNAME , "detail" , category , scrapedtitle , scrapedurl , scrapedthumbnail, scrapedplot )

	# Asigna el t�tulo, desactiva la ordenaci�n, y cierra el directorio
	xbmcplugin.setPluginCategory( handle=pluginhandle, category=category )
	xbmcplugin.addSortMethod( handle=pluginhandle, sortMethod=xbmcplugin.SORT_METHOD_NONE )
	xbmcplugin.endOfDirectory( handle=pluginhandle, succeeded=True )
def novedades(params,url,category):
    logger.info("[redestv.py] parseweb")
 
    # ------------------------------------------------------
    # Descarga la página
    # ------------------------------------------------------
    data = scrapertools.cachePage(url)
    #logger.info(data)
 
    #<div style="text-align: justify;">Cre?amos que el ser humano era el ?nico animal capaz de sentir empat?a.  Sin embargo, el altruismo existe en muchos otros animales. Estar  conectado con los dem?s, entenderlos y sentir su dolor no es exclusivo  del ser humano. El prim?tologo Frans de Waal, gran estudiador de las  emociones animales, habla con Punset sobre empat?a y simpat?a,  capacidades clave para el ?xito en la vida social.</div><div class="jcomments-links"> <a href="/index.php?option=com_content&amp;view=article&amp;id=161:501-nuestro-cerebro-altruista&amp;catid=2:cermen&amp;Itemid=10#addcomments" class="comment-link">Escribir un comentario</a></div> 
 
    patronvideos  = '<td class="contentheading" width="100%">.+?<a href="(.+?)" class="contentpagetitle">\s+(\d+.+?)</a>'
    #patronvideos  = '<div style="text-align: justify;">.+?</div>.+?<a href="(.+?)#'
 
    #logger.info("web"+data)
    matches = re.compile(patronvideos,re.DOTALL).findall(data)
    if DEBUG:
        scrapertools.printMatches(matches)
    #xbmctools.addnewfolder( CHANNELNAME , "buscavideos" , category, "redestv" , "http://www.redes-tv.com"+matches[0][0] , "" , "")
    #scrapertools.printMatches(matches)
 
    #    patronvideos1 = 'src="http://www.megavideo.com/v/(.{8}).+?".+?></embed>.*?<p>(.+?)</p><div'
    #    matches1 = re.compile(patronvideos1,re.DOTALL).findall(data)
    #    if DEBUG:
    #        scrapertools.printMatches(matches1)
 
    for i in range(len(matches)):
        xbmctools.addnewvideo( CHANNELNAME , "buscavideos" , category , "redestv" , matches[i][1] , matches[i][0] , "thumbnail" , "")
 
    xbmcplugin.setPluginCategory( handle=int( sys.argv[ 1 ] ), category=category )
    xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_NONE )
    xbmcplugin.endOfDirectory( handle=int( sys.argv[ 1 ] ), succeeded=True )
def listchannels(params,url,category):
    logger.info("channelselector.listchannels")

    lista = filterchannels(category)
    for channel in lista:
        if channel.type=="xbmc" or channel.type=="generic":
            if channel.channel=="personal":
                thumbnail=config.get_setting("personalchannellogo")
            elif channel.channel=="personal2":
                thumbnail=config.get_setting("personalchannellogo2")
            elif channel.channel=="personal3":
                thumbnail=config.get_setting("personalchannellogo3")
            elif channel.channel=="personal4":
                thumbnail=config.get_setting("personalchannellogo4")
            elif channel.channel=="personal5":
                thumbnail=config.get_setting("personalchannellogo5")
            else:
                thumbnail=channel.thumbnail
                if thumbnail == "":
                    thumbnail=urlparse.urljoin(get_thumbnail_path(),channel.channel+".png")
            addfolder(channel.title , channel.channel , "mainlist" , channel.channel, thumbnail = thumbnail)

    # Label (top-right)...
    import xbmcplugin
    xbmcplugin.setPluginCategory( handle=int( sys.argv[ 1 ] ), category=category )
    xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_NONE )
    xbmcplugin.endOfDirectory( handle=int( sys.argv[ 1 ] ), succeeded=True )

    if config.get_setting("forceview")=="true":
        # Confluence - Thumbnail
        import xbmc
        xbmc.executebuiltin("Container.SetViewMode(500)")
Пример #14
0
def LIST_MOVIE_TYPES(type=False):
    import movies as moviesDB
    if not type:
        type = common.args.url
    if type=='GENRE':
        mode = 'LIST_MOVIES_GENRE_FILTERED'
        items = moviesDB.getMovieTypes('genres')
    elif type=='STUDIOS':
        mode =  'LIST_MOVIES_STUDIO_FILTERED'
        items = moviesDB.getMovieTypes('studio')
    elif type=='YEARS':
        mode = 'LIST_MOVIES_YEAR_FILTERED'
        items = moviesDB.getMovieTypes('year')
    elif type=='DIRECTORS':
        mode = 'LIST_MOVIES_DIRECTOR_FILTERED'
        items = moviesDB.getMovieTypes('director')
    elif type=='MPAA':
        mode = 'LIST_MOVIES_MPAA_FILTERED'
        items = moviesDB.getMovieTypes('mpaa')
    elif type=='ACTORS':        
        mode = 'LIST_MOVIES_ACTOR_FILTERED'
        items = moviesDB.getMovieTypes('actors')     
    for item in items:
        export_mode=mode+'_EXPORT'
        cm = [('Export to Library', 'XBMC.RunPlugin(plugin://plugin.video.amazon?mode="listmovie"&sitemode="%s"&url="%s")' % ( export_mode, urllib.quote_plus(item) ) ) ]
        common.addDir(item,'listmovie',mode,item,cm=cm)
    xbmcplugin.addSortMethod(pluginhandle, xbmcplugin.SORT_METHOD_LABEL)          
    xbmcplugin.endOfDirectory(pluginhandle,updateListing=False)   
def parsewebcategorias(params,url,category):
    logger.info("[redestv.py] buscacategorias")
    data = scrapertools.cachePage("http://www.redes-tv.com/index.php?option=com_xmap&sitemap=1&Itemid=31")
    #href='http://www.redestv.com/category/arte/' title="ARTE">ARTE</a></li><li><a
    #href="/index.php?option=com_content&amp;view=category&amp;layout=blog&amp;id=1&amp;Itemid=9" title="Biotecnolog\xc3\xada y Salud"
    patronvideos  = "index.php." + url + '(.*?)</ul>'
    #patronvideos=patronvideos.replace("&","\&")
    #patronvideos=patronvideos.replace(";","\;")
    #patronvideos=patronvideos.replace("=","\=")
    #patronvideos=patronvideos.replace("_","\_")
    #logger.info(patronvideos)
    #logger.info("web"+data)
    matches = re.compile(patronvideos,re.DOTALL).findall(data)
    if DEBUG:
        scrapertools.printMatches(matches)
    if len(matches)>0:
        #href="/index.php?option=com_content&amp;view=article&amp;id=65:473-farmacos-para-las-emociones&amp;catid=1:biosalud&amp;Itemid=9" title="473: Fármacos para las emociones"
        patronvideos = 'href="(.+?)" title="(.+?)"'
        matches1 = re.compile(patronvideos).findall(matches[0])
        for i in range(len(matches1)):
            #xbmctools.addnewvideo( CHANNELNAME , "buscavideos" , category, matches1[i][1] , matches1[i][0] , "thumbnail" , "")
            xbmctools.addnewvideo( CHANNELNAME , "buscavideos" , category , "redestv",  matches1[i][1] , matches1[i][0] , "thumbnail" , "")
 
    xbmcplugin.setPluginCategory( handle=int( sys.argv[ 1 ] ), category=category )
    xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_NONE )
    xbmcplugin.endOfDirectory( handle=int( sys.argv[ 1 ] ), succeeded=True )
Пример #16
0
def list_categories():
    """
    Create the list of categories in the Kodi interface.

    Returns:
        None
    """
    categories = get_categories()
    listing = []
    for category in categories:
        # Create a list item with a text label and a thumbnail image.
        list_item = xbmcgui.ListItem(label=FEEDS[category]['name'], thumbnailImage=FEEDS[category]['icon'])
        # set fanart
        my_addon = xbmcaddon.Addon('plugin.audio.dancarlin')
        #list_item.setProperty('fanart_image', my_addon.getAddonInfo('fanart'))
        list_item.setArt({'fanart': my_addon.getAddonInfo('fanart')})
        # Set additional info for the list item.
        list_item.setInfo('video', {'title': category, 'genre': 'news'})
        list_item.setInfo('audio', {'title': category, 'genre': 'news'})
        # Create a URL for the plugin recursive callback.
        # e.g., plugin://plugin.audio.dancarlin/?action=listing&category=common_sense
        url = '{0}?action=listing&category={1}'.format(_url, category)
        # is_folder = True means that this item opens a sub-list of lower level items.
        is_folder = True
        # Add our item to the listing as a 3-element tuple.
        listing.append((url, list_item, is_folder))
    # Add our listing to Kodi.
    xbmcplugin.addDirectoryItems(_handle, listing, len(listing))
    # Add a sort method for the virtual folder items (alphabetically, ignore articles)
    xbmcplugin.addSortMethod(_handle, xbmcplugin.SORT_METHOD_LABEL_IGNORE_THE)
    # Finish creating a virtual folder.
    xbmcplugin.endOfDirectory(_handle)
Пример #17
0
def LIST_MOVIE_AZ():
    common.addDir('#','listmovie','LIST_MOVIES_AZ_FILTERED','')
    alphabet=set(string.ascii_uppercase)
    for letter in alphabet:
        common.addDir(letter,'listmovie','LIST_MOVIES_AZ_FILTERED',letter)
    xbmcplugin.addSortMethod(pluginhandle, xbmcplugin.SORT_METHOD_LABEL)
    xbmcplugin.endOfDirectory(pluginhandle)
Пример #18
0
def seasons(series_name, series_id, thumb):
    xbmcplugin.setContent(plugin_handle, 'seasons')
    seasons = get.seasons_data(series_id)
    for season in seasons:
        add.season(season)
    xbmcplugin.addSortMethod(plugin_handle, xbmcplugin.SORT_METHOD_LABEL)
    xbmcplugin.endOfDirectory(plugin_handle)
Пример #19
0
def listchannels(params, url, category):
    xbmc.output("[channelselector.py] listchannels")

    # Verifica actualizaciones solo en el primer nivel
    if xbmcplugin.getSetting("updatecheck2") == "true":
        xbmc.output("updatecheck2=true")
        import updater

        updater.checkforupdates()
    else:
        xbmc.output("updatecheck2=false")

    CHANNELNAME = "kideoschannel"
    xbmctools.addnewfolder(CHANNELNAME, "ageslist", CHANNELNAME, xbmc.getLocalizedString(30501), "", "", "")
    xbmctools.addnewfolder(CHANNELNAME, "categorylist", CHANNELNAME, xbmc.getLocalizedString(30502), "", "", "")
    xbmctools.addnewfolder(CHANNELNAME, "userlist", CHANNELNAME, xbmc.getLocalizedString(30503), "", "", "")
    xbmctools.addnewfolder("configuracion", "mainlist", "configuracion", xbmc.getLocalizedString(30504), "", "", "")
    xbmctools.addnewfolder("descargados", "mainlist", "descargados", xbmc.getLocalizedString(30505), "", "", "")

    # Label (top-right)...
    xbmcplugin.setPluginCategory(handle=int(sys.argv[1]), category="Canales")

    # Disable sorting...
    xbmcplugin.addSortMethod(handle=int(sys.argv[1]), sortMethod=xbmcplugin.SORT_METHOD_NONE)

    # End of directory...
    xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=True)
Пример #20
0
def build_video_directory(url, page, section):
    if url == "search":
        search = True
        text = common.getUserInput(settings.getLocalizedString(30003), "")
        if text == None:
            return
        url = "channels%2F*%7Cgames%2F*%7Cflip_video_diaries%7Cfiba&text=" + urllib.quote(text)
    else:
        search = False
    save_url = url
    if page == 1 and search != True:
        base = "http://www.nba.com/.element/ssi/auto/2.0/aps/video/playlists/" + section + ".html?section="
    else:
        base = "http://searchapp2.nba.com/nba-search/query.jsp?section="
    url = base + url + "&season=1213&sort=recent&hide=true&type=advvideo&npp=15&start=" + str(1 + (15 * (page - 1)))
    html = getUrl(url)
    textarea = common.parseDOM(html, "textarea", attrs={"id": "jsCode"})[0]
    content = (
        textarea.replace("\\'", "\\\\'")
        .replace('\\\\"', '\\\\\\"')
        .replace("\\n", "")
        .replace("\\t", "")
        .replace("\\x", "")
    )
    query = json.loads(content)
    data = query["results"][0]
    count = query["metaResults"]["advvideo"]
    if len(data) == 0:
        dialog = xbmcgui.Dialog()
        ok = dialog.ok(plugin, settings.getLocalizedString(30004) + "\n" + settings.getLocalizedString(30005))
        return
    for results in data:
        mediaDateUts = time.ctime(float(results["mediaDateUts"]))
        date = datetime.datetime.fromtimestamp(
            time.mktime(time.strptime(mediaDateUts, "%a %b %d %H:%M:%S %Y"))
        ).strftime("%d.%m.%Y")
        title = results["title"].replace("\\", "")
        thumb = results["metadata"]["media"]["thumbnail"]["url"].replace("136x96", "576x324")
        length = results["metadata"]["video"]["length"].split(":")
        duration = int(length[0]) * 60 + int(length[1])
        plot = results["metadata"]["media"]["excerpt"].replace("\\", "")
        url = results["id"].replace("/video/", "").replace("/index.html", "")
        infoLabels = {"Title": title, "Plot": plot, "Aired": date}
        u = {"mode": "3", "name": title, "url": url, "thumb": thumb, "plot": plot}
        addListItem(
            label=title, image=thumb, url=u, isFolder=False, infoLabels=infoLabels, fanart=fanart, duration=duration
        )
    if int(page) * 15 < int(count):
        u = {"mode": "0", "page": str(int(page) + 1), "url": save_url, "section": section}
        addListItem(
            label="[Next Page (" + str(int(page) + 1) + ")]",
            image=next_thumb,
            url=u,
            isFolder=True,
            infoLabels=False,
            fanart=fanart,
        )
    xbmcplugin.addSortMethod(handle=int(sys.argv[1]), sortMethod=xbmcplugin.SORT_METHOD_NONE)
    setViewMode("503")
    xbmcplugin.endOfDirectory(int(sys.argv[1]))
Пример #21
0
def LIST_TVSHOWS_TYPES(type=False):
    import tv as tvDB

    if not type:
        type = common.args.url
    if type == "GENRE":
        mode = "LIST_TVSHOWS_GENRE_FILTERED"
        items = tvDB.getShowTypes("genres")
    elif type == "NETWORKS":
        mode = "LIST_TVSHOWS_NETWORKS_FILTERED"
        items = tvDB.getShowTypes("network")
    elif type == "YEARS":
        mode = "LIST_TVSHOWS_YEARS_FILTERED"
        items = tvDB.getShowTypes("year")
    elif type == "MPAA":
        mode = "LIST_TVSHOWS_MPAA_FILTERED"
        items = tvDB.getShowTypes("mpaa")
    elif type == "CREATORS":
        mode = "LIST_TVSHOWS_CREATORS_FILTERED"
        items = tvDB.getShowTypes("creator")
    for item in items:
        export_mode = mode + "_EXPORT"
        cm = [
            (
                "Export to Library",
                'XBMC.RunPlugin(plugin://plugin.video.amazon?mode="listtv"&sitemode="%s"&url="%s")'
                % (export_mode, urllib.quote_plus(item)),
            )
        ]
        common.addDir(item, "listtv", mode, item, cm=cm)
    xbmcplugin.addSortMethod(pluginhandle, xbmcplugin.SORT_METHOD_LABEL)
    xbmcplugin.endOfDirectory(pluginhandle, updateListing=False)
def detail(params, url, category):
    logger.info("[documentalesatonline.py] detail")

    title = unicode(xbmc.getInfoLabel("ListItem.Title"), "utf-8")
    thumbnail = urllib.unquote_plus(params.get("thumbnail"))
    plot = unicode(xbmc.getInfoLabel("ListItem.Plot"), "utf-8")

    # Descarga la página
    data = scrapertools.cachePage(url)
    # logger.info(data)

    # ------------------------------------------------------------------------------------
    # Busca los enlaces a los videos
    # ------------------------------------------------------------------------------------
    listavideos = servertools.findvideos(data)

    for video in listavideos:
        xbmctools.addvideo(CHANNELNAME, "Megavideo - " + video[0], video[1], category, video[2])
        # ------------------------------------------------------------------------------------

        # Label (top-right)...
    xbmcplugin.setPluginCategory(handle=pluginhandle, category=category)

    # Disable sorting...
    xbmcplugin.addSortMethod(handle=pluginhandle, sortMethod=xbmcplugin.SORT_METHOD_NONE)

    # End of directory...
    xbmcplugin.endOfDirectory(handle=pluginhandle, succeeded=True)
Пример #23
0
def busqueda(params,url,category):
	logger.info("busqueda")
	tecleado = ""
	keyboard = xbmc.Keyboard('')
	keyboard.doModal()
	if (keyboard.isConfirmed()):
		tecleado = keyboard.getText()
		if len(tecleado)<=0:
			return
	
	tecleado = tecleado.replace(" ", "+")
	data=scrapertools.cachePagePost("http://www.divxonline.info/buscador.html",'texto=' + tecleado + '&categoria=0&tipobusqueda=1&Buscador=Buscar')

	#logger.info(data)
	data=data[data.find('Se han encontrado un total de'):]
	
	#<li><a href="/pelicula/306/100-chicas-2000/">100 chicas (2000)</a></li>
	patronvideos  = '<li><a href="(.+?)">(.+?)</a></li>'
	matches = re.compile(patronvideos,re.DOTALL).findall(data)
	if DEBUG: 
		scrapertools.printMatches(matches)
	
	for match in matches:
		xbmctools.addnewfolder( CHANNELNAME , "listmirrors" , category , match[1] , 'http://www.divxonline.info' + match[0] , 'scrapedthumbnail', 'scrapedplot' )
	
	xbmcplugin.setPluginCategory( handle=int( sys.argv[ 1 ] ), category=category )
	xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_NONE )
	xbmcplugin.endOfDirectory( handle=int( sys.argv[ 1 ] ), succeeded=True )
Пример #24
0
def veoh(params,url,category):
	logger.info("[divxonline.py] veoh")

	xbmctools.addnewfolder( CHANNELNAME , "movielist" , CHANNELNAME , "Acción" , "http://www.divxonline.info/peliculas/30/accion-veoh/" , "", "" )
	xbmctools.addnewfolder( CHANNELNAME , "movielist" , CHANNELNAME , "Animación" , "http://www.divxonline.info/peliculas/33/animacion-veoh/" , "", "" )
	xbmctools.addnewfolder( CHANNELNAME , "movielist" , CHANNELNAME , "Anime" , "http://www.divxonline.info/peliculas/41/anime-veoh/" , "", "" )
	xbmctools.addnewfolder( CHANNELNAME , "movielist" , CHANNELNAME , "Aventura" , "http://www.divxonline.info/peliculas/32/aventura-veoh/" , "", "" )
	xbmctools.addnewfolder( CHANNELNAME , "movielist" , CHANNELNAME , "Bélicas" , "http://www.divxonline.info/peliculas/96/belicas-veoh/" , "", "" )
	xbmctools.addnewfolder( CHANNELNAME , "movielist" , CHANNELNAME , "Ciencia Ficción" , "http://www.divxonline.info/peliculas/35/ciencia0-ficcion-veoh/" , "", "" )
	xbmctools.addnewfolder( CHANNELNAME , "movielist" , CHANNELNAME , "Cine Clásico" , "http://www.divxonline.info/peliculas/38/cine-clasico-veoh/" , "", "" )
	xbmctools.addnewfolder( CHANNELNAME , "movielist" , CHANNELNAME , "Cine Español" , "http://www.divxonline.info/peliculas/37/cine-español-veoh/" , "", "" )
	xbmctools.addnewfolder( CHANNELNAME , "movielist" , CHANNELNAME , "Clásicos Disney" , "http://www.divxonline.info/peliculas/39/clasicos-disney-veoh/" , "", "" )
	xbmctools.addnewfolder( CHANNELNAME , "movielist" , CHANNELNAME , "Comedias" , "http://www.divxonline.info/peliculas/40/comedias-veoh/" , "", "" )
	xbmctools.addnewfolder( CHANNELNAME , "movielist" , CHANNELNAME , "Cortometrajes" , "http://www.divxonline.info/peliculas/41/cortometrajes-veoh/" , "", "" )
	xbmctools.addnewfolder( CHANNELNAME , "movielist" , CHANNELNAME , "Documentales" , "http://www.divxonline.info/peliculas/34/documentales-veoh/" , "", "" )
	xbmctools.addnewfolder( CHANNELNAME , "movielist" , CHANNELNAME , "Drama" , "http://www.divxonline.info/peliculas/42/dramas-veoh/" , "", "" )
	xbmctools.addnewfolder( CHANNELNAME , "movielist" , CHANNELNAME , "Infantiles" , "http://www.divxonline.info/peliculas/43/infantiles-veoh/" , "", "" )
	xbmctools.addnewfolder( CHANNELNAME , "movielist" , CHANNELNAME , "Musicales" , "http://www.divxonline.info/peliculas/44/musicales-veoh/" , "", "" )
	xbmctools.addnewfolder( CHANNELNAME , "movielist" , CHANNELNAME , "Suspense" , "http://www.divxonline.info/peliculas/45/suspense-veoh/" , "", "" )
	xbmctools.addnewfolder( CHANNELNAME , "movielist" , CHANNELNAME , "Terror" , "http://www.divxonline.info/peliculas/46/terror-veoh/" , "", "" )
	xbmctools.addnewfolder( CHANNELNAME , "movielist" , CHANNELNAME , "Western" , "http://www.divxonline.info/peliculas/49/western-veoh/" , "", "" )

	# Label (top-right)...
	xbmcplugin.setPluginCategory( handle=pluginhandle, category=category )
	xbmcplugin.addSortMethod( handle=pluginhandle, sortMethod=xbmcplugin.SORT_METHOD_NONE )
	xbmcplugin.endOfDirectory( handle=pluginhandle, succeeded=True )
Пример #25
0
def detail(params,url,category):
	logger.info("[divxonline.py] detail")
	title=''
	thumbnail=''
	plot=''

	try:
		title = urllib.unquote_plus( params.get("title") )
		thumbnail = urllib.unquote_plus( params.get("thumbnail") )
		plot = urllib.unquote_plus( params.get("plot") )
	except:
		pass
	# Descarga la página
	data = scrapertools.cachePage(url)
	#logger.info(data)

	# ------------------------------------------------------------------------------------
	# Busca los enlaces a los videos
	# ------------------------------------------------------------------------------------
	
	data=decryptinks(data);
	listavideos = servertools.findvideos(data)

	for video in listavideos:
		videotitle = video[0]
		url = video[1]
		server = video[2]
		xbmctools.addnewvideo( CHANNELNAME , "play" , category , server , title.strip() + " - " + videotitle , url , thumbnail , plot )
	# ------------------------------------------------------------------------------------

	# Cierra el directorio
	xbmcplugin.setPluginCategory( handle=pluginhandle, category=category )
	xbmcplugin.addSortMethod( handle=pluginhandle, sortMethod=xbmcplugin.SORT_METHOD_NONE )
	xbmcplugin.endOfDirectory( handle=pluginhandle, succeeded=True )
Пример #26
0
def search_list(tvradio):
    # provide a list of saved search terms
    xbmcplugin.addSortMethod(handle=PLUGIN_HANDLE, sortMethod=xbmcplugin.SORT_METHOD_NONE)
    searchimg = get_plugin_thumbnail('search')
    
    # First item allows a new search to be created
    listitem = xbmcgui.ListItem(label='New Search...')
    listitem.setThumbnailImage(searchimg)
    url = make_url(listing='search', tvradio=tvradio)
    ok = xbmcplugin.addDirectoryItem(            
          handle=PLUGIN_HANDLE, 
          url=url,
          listitem=listitem,
          isFolder=True) 
    
    # Now list all the saved searches
    for searchterm in iplayer_search.load_search(SEARCH_FILE, tvradio):
        listitem = xbmcgui.ListItem(label=searchterm)
        listitem.setThumbnailImage(searchimg)
        url = make_url(listing='search', tvradio=tvradio, label=searchterm)
        
        # change the context menu to an entry for deleting the search
        cmd = "XBMC.RunPlugin(%s?deletesearch=%s&tvradio=%s)" % (sys.argv[0], urllib.quote_plus(searchterm), urllib.quote_plus(tvradio))
        listitem.addContextMenuItems( [ ('Delete saved search', cmd) ] )
        
        ok = xbmcplugin.addDirectoryItem(            
            handle=PLUGIN_HANDLE, 
            url=url,
            listitem=listitem,
            isFolder=True,
        )        
         
    xbmcplugin.endOfDirectory(handle=PLUGIN_HANDLE, succeeded=True)
Пример #27
0
def megavideo(params,url,category):
	logger.info("[divxonline.py] megavideo")

	xbmctools.addnewfolder( CHANNELNAME , "movielist" , CHANNELNAME , "Acción" , "http://www.divxonline.info/peliculas/50/accion-megavideo/" , "", "" )
	xbmctools.addnewfolder( CHANNELNAME , "movielist" , CHANNELNAME , "Animación" , "http://www.divxonline.info/peliculas/53/animacion-megavideo/" , "", "" )
	xbmctools.addnewfolder( CHANNELNAME , "movielist" , CHANNELNAME , "Anime" , "http://www.divxonline.info/peliculas/51/anime-megavideo/" , "", "" )
	xbmctools.addnewfolder( CHANNELNAME , "movielist" , CHANNELNAME , "Aventura" , "http://www.divxonline.info/peliculas/52/aventura-megavideo/" , "", "" )
	xbmctools.addnewfolder( CHANNELNAME , "movielist" , CHANNELNAME , "Bélicas" , "http://www.divxonline.info/peliculas/95/belicas-megavideo/" , "", "" )
	xbmctools.addnewfolder( CHANNELNAME , "movielist" , CHANNELNAME , "Ciencia Ficción" , "http://www.divxonline.info/peliculas/55/ciencia-ficcion-megavideo/" , "", "" )
	xbmctools.addnewfolder( CHANNELNAME , "movielist" , CHANNELNAME , "Cine Clásico" , "http://www.divxonline.info/peliculas/58/cine-clasico-megavideo/" , "", "" )
	xbmctools.addnewfolder( CHANNELNAME , "movielist" , CHANNELNAME , "Cine español" , "http://www.divxonline.info/peliculas/57/cine-espa%C3%B1ol-megavideo/" , "", "" )
	xbmctools.addnewfolder( CHANNELNAME , "movielist" , CHANNELNAME , "Clásicos Disney" , "http://www.divxonline.info/peliculas/59/clasicos-disney-megavideo/" , "", "" )
	xbmctools.addnewfolder( CHANNELNAME , "movielist" , CHANNELNAME , "Comedias" , "http://www.divxonline.info/peliculas/60/comedias-megavideo/" , "", "" )
	xbmctools.addnewfolder( CHANNELNAME , "movielist" , CHANNELNAME , "Documentales" , "http://www.divxonline.info/peliculas/54/documentales-megavideo/" , "", "" )
	xbmctools.addnewfolder( CHANNELNAME , "movielist" , CHANNELNAME , "Drama" , "http://www.divxonline.info/peliculas/62/drama-megavideo/" , "", "" )
	xbmctools.addnewfolder( CHANNELNAME , "movielist" , CHANNELNAME , "Infantil" , "http://www.divxonline.info/peliculas/63/infantil-megavideo/" , "", "" )
	xbmctools.addnewfolder( CHANNELNAME , "movielist" , CHANNELNAME , "Musicales" , "http://www.divxonline.info/peliculas/64/musicales-megavideo/" , "", "" )
	xbmctools.addnewfolder( CHANNELNAME , "movielist" , CHANNELNAME , "Suspense" , "http://www.divxonline.info/peliculas/65/suspense-megavideo/" , "", "" )
	xbmctools.addnewfolder( CHANNELNAME , "movielist" , CHANNELNAME , "Terror" , "http://www.divxonline.info/peliculas/66/terror-megavideo/" , "", "" )
	xbmctools.addnewfolder( CHANNELNAME , "movielist" , CHANNELNAME , "Western" , "http://www.divxonline.info/peliculas/67/western-megavideo/" , "", "" )

	# Label (top-right)...
	xbmcplugin.setPluginCategory( handle=pluginhandle, category=category )

	# Disable sorting...
	xbmcplugin.addSortMethod( handle=pluginhandle, sortMethod=xbmcplugin.SORT_METHOD_NONE )

	# End of directory...
	xbmcplugin.endOfDirectory( handle=pluginhandle, succeeded=True )
Пример #28
0
def CATEGORIES():
   

    response=OPEN_URL('http://d3gbuig838qdtm.cloudfront.net/json/tvp/channels.json')
    
    link=json.loads(response)

    data=link['data']
    

    for field in data:
        name= field['channel']['name'].encode("utf-8")
        
        status=field['channel']['status']
        id=field['channel']['id']
        
        if status=='online':
            status='[COLOR green]   (%s)[/COLOR]'%status
        else:
            status='[COLOR red]   (%s)[/COLOR]'%status
        icon='http://static.simplestream.com/tvplayer/logos/150/Inverted/%s.png' % id    
        addDir(name+status,id,200,icon,'')
    if ADDON.getSetting('sort')== 'true':    
        xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_VIDEO_TITLE)             
    setView('movies', 'default') 
Пример #29
0
def list_tvradio():
    """
    Lists five folders - one for TV and one for Radio, plus A-Z, highlights and popular
    """
    xbmcplugin.addSortMethod(handle=PLUGIN_HANDLE, sortMethod=xbmcplugin.SORT_METHOD_TRACKNUM)
        
    folders = []
    folders.append(('TV', 'tv', make_url(tvradio='tv')))
    folders.append(('Radio', 'radio', make_url(tvradio='radio')))
    folders.append(('Settings', 'settings', make_url(tvradio='Settings')))

    for i, (label, tn, url) in enumerate(folders):
        listitem = xbmcgui.ListItem(label=label)
        listitem.setIconImage('defaultFolder.png')
        thumbnail = get_plugin_thumbnail(tn)
        if thumbnail:
            listitem.setThumbnailImage(get_plugin_thumbnail(tn))
        folder=True
        if label == 'Settings':
            # fix for reported bug where loading dialog would overlay settings dialog 
            folder = False
        ok = xbmcplugin.addDirectoryItem(
            handle=PLUGIN_HANDLE, 
            url=url,
            listitem=listitem,
            isFolder=folder,
        )
    
    xbmcplugin.endOfDirectory(handle=PLUGIN_HANDLE, succeeded=True)
def categorias(params, url, category):
    logger.info("[documentalesatonline.py] novedades")

    # Descarga la página
    data = scrapertools.cachePage(url)
    # logger.info(data)

    # Extrae las entradas (carpetas)
    patronvideos = "<a dir='ltr' href='([^']+)'>([^<]+)</a>[^<]+<span dir='ltr'>([^<]+)</span>"
    matches = re.compile(patronvideos, re.DOTALL).findall(data)
    scrapertools.printMatches(matches)

    for match in matches:
        scrapedtitle = match[1] + " " + match[2]
        scrapedurl = urlparse.urljoin(url, match[0])
        scrapedthumbnail = ""
        scrapedplot = ""
        if DEBUG:
            logger.info("title=[" + scrapedtitle + "], url=[" + scrapedurl + "], thumbnail=[" + scrapedthumbnail + "]")

        # Añade al listado de XBMC
        xbmctools.addnewfolder(
            CHANNELNAME, "novedades", category, scrapedtitle, scrapedurl, scrapedthumbnail, scrapedplot
        )

        # Label (top-right)...
    xbmcplugin.setPluginCategory(handle=pluginhandle, category=category)
    xbmcplugin.addSortMethod(handle=pluginhandle, sortMethod=xbmcplugin.SORT_METHOD_NONE)
    xbmcplugin.endOfDirectory(handle=pluginhandle, succeeded=True)
Пример #31
0
    def list_videos_by_channel(self, channel, start, duration):
        # Get the list of videos in the category.
        listEPG = self.user.getEPG(channel, start, duration)

        for channel in listEPG:
            for videoKey in listEPG[channel].keys():
                # Create a list item with a text label and a thumbnail image.
                video = listEPG[channel][videoKey]
                timeStart = modTime.strptime(video['dateCompleteDebut'],
                                             "%Y%m%d%H%M")
                timeEnd = modTime.strptime(video['dateCompleteFin'],
                                           "%Y%m%d%H%M")

                title = "[" + modTime.strftime(
                    "%d/%m/%Y %H:%M",
                    modTime.strptime(video['dateCompleteDebut'],
                                     "%Y%m%d%H%M")) + "] " + video['titre']
                list_item = xbmcgui.ListItem(label=title)

                timeStart = modTime.mktime(timeStart)
                timeEnd = modTime.mktime(timeEnd)

                # Set additional info for the list item.
                list_item.setInfo(
                    'video', {
                        'title':
                        title,
                        'genre':
                        video['categorieDetail'],
                        'dateadded':
                        modTime.strftime(
                            "%Y-%m-%d %H:%M:%s",
                            modTime.strptime(video['dateCompleteDebut'],
                                             "%Y%m%d%H%M")),
                        'mediatype':
                        'movie',
                        'dbid':
                        video['id'],
                        'mpaa':
                        video['classeCSA'],
                        'duration': (timeEnd - timeStart),
                        'plot':
                        video['description'],
                        'plotoutline':
                        video['description']
                    })
                list_item.setProperty('IsPlayable', 'true')

                duration = timeEnd - timeStart
                duration = self.add_margin_video(duration)

                urlVideo = self.user.getURLCatchup(str(video['channel_id']),
                                                   str(int(timeStart)),
                                                   str(duration))
                url = self.get_url(action='play', video=urlVideo)

                list_item.setArt({
                    'thumb': video['vignette'],
                    'icon': video['vignette'],
                    'fanart': video['vignette']
                })
                xbmcplugin.addDirectoryItem(self._handle, url, list_item,
                                            False)

        xbmcplugin.addSortMethod(self._handle,
                                 xbmcplugin.SORT_METHOD_LABEL_IGNORE_THE)
        # Finish creating a virtual folder.
        xbmcplugin.endOfDirectory(self._handle)
Пример #32
0
    def Browse(self, path, forceSort=None):
        """ Display and navigate the menu for PrimeVideo users """

        path = path.decode('utf-8')

        # Add multiuser menu if needed
        if (self._s.multiuser) and ('root' == path) and (1 < len(loadUsers())):
            li = xbmcgui.ListItem(getString(30134).format(loadUser('name')))
            li.addContextMenuItems(self._g.CONTEXTMENU_MULTIUSER)
            xbmcplugin.addDirectoryItem(self._g.pluginhandle, '{0}?mode=PrimeVideo_Browse&path=root-//-SwitchUser'.format(self._g.pluginid), li, isFolder=False)
        if 'root-//-SwitchUser' == path:
            if switchUser():
                self.BuildRoot()
            return

        node = self._catalog
        nodeName = None
        for n in path.split('-//-'):
            nodeName = n
            node = node[n]

        if (nodeName in self._videodata) and ('metadata' in self._videodata[nodeName]) and ('video' in self._videodata[nodeName]['metadata']):
            ''' Start the playback if on a video leaf '''
            PlayVideo(self._videodata[nodeName]['metadata']['video'], self._videodata[nodeName]['metadata']['asin'], '', 0)
            return

        if (None is not node) and ('lazyLoadURL' in node):
            self._LazyLoad(node, nodeName)

        if None is node:
            self._g.dialog.notification('General error', 'Something went terribly wrong…', xbmcgui.NOTIFICATION_ERROR)
            return

        folderType = 0 if 'root' == path else 1
        for key in node:
            if key in ['metadata', 'ref', 'title', 'verb', 'children', 'parent']:
                continue
            url = '{0}?mode='.format(self._g.pluginid)
            entry = node[key] if key not in self._videodata else self._videodata[key]

            # Skip items that are out of catalog
            if ('metadata' in entry) and ('unavailable' in entry['metadata']):
                continue

            if 'verb' not in entry:
                url += 'PrimeVideo_Browse&path={0}-//-{1}'.format(quote_plus(path.encode('utf-8')), quote_plus(key.encode('utf-8')))
                # Squash season number folder when only one season is available
                if ('children' in entry) and (1 == len(entry['children'])):
                    url += '-//-{0}'.format(quote_plus(entry['children'][0].encode('utf-8')))
            else:
                url += entry['verb']
            title = entry['title'] if 'title' in entry else nodeName
            item = xbmcgui.ListItem(title)
            folder = True
            # In case of series find the oldest series and apply its art, also update metadata in case of squashed series
            if ('metadata' not in entry) and ('children' in entry) and (0 < len(entry['children'])):
                if 1 == len(entry['children']):
                    entry['metadata'] = {'artmeta': self._videodata[entry['children'][0]]['metadata']['artmeta'],
                                         'videometa': self._videodata[entry['children'][0]]['metadata']['videometa']}
                else:
                    sn = 90001
                    snid = None
                    for child in entry['children']:
                        if ('season' in self._videodata[child]['metadata']['videometa']) and (sn > self._videodata[child]['metadata']['videometa']['season']):
                            sn = self._videodata[child]['metadata']['videometa']['season']
                            snid = child
                    if None is not snid:
                        entry['metadata'] = {'artmeta': self._videodata[snid]['metadata']['artmeta'], 'videometa': {'mediatype': 'tvshow'}}
            if 'metadata' in entry:
                m = entry['metadata']
                if 'artmeta' in m: item.setArt(m['artmeta'])
                if 'videometa' in m:
                    # https://codedocs.xyz/xbmc/xbmc/group__python__xbmcgui__listitem.html#ga0b71166869bda87ad744942888fb5f14
                    item.setInfo('video', m['videometa'])
                    if 'episode' in m['videometa']:
                        folderType = 4  # Episode
                    elif 'season' in m['videometa']:
                        if 'tvshow' == m['videometa']['mediatype']:
                            folderType = 2  # Series list
                        else:
                            folderType = 3  # Season
                    elif 2 > folderType:  # If it's not been declared series, season or episode yet…
                        folderType = 5  # … it's a Movie
                if 'video' in m:
                    folder = False
                    item.setProperty('IsPlayable', 'true')
                    item.setInfo('video', {'title': title})
                    if 'runtime' in m:
                        item.setInfo('video', {'duration': m['runtime']})
                        item.addStreamInfo('video', {'duration': m['runtime']})
            xbmcplugin.addDirectoryItem(self._g.pluginhandle, url, item, isFolder=folder)
            del item

        # Set sort method and view
        # https://codedocs.xyz/xbmc/xbmc/group__python__xbmcplugin.html#ga85b3bff796fd644fb28f87b136025f40
        xbmcplugin.addSortMethod(self._g.pluginhandle, [
            xbmcplugin.SORT_METHOD_NONE,
            xbmcplugin.SORT_METHOD_LABEL_IGNORE_THE,
            xbmcplugin.SORT_METHOD_LABEL_IGNORE_THE,
            xbmcplugin.SORT_METHOD_LABEL_IGNORE_THE,
            xbmcplugin.SORT_METHOD_EPISODE,
            xbmcplugin.SORT_METHOD_LABEL_IGNORE_THE,
        ][folderType if None is forceSort else forceSort])

        if 'false' == self._g.addon.getSetting("viewenable"):
            # Only vfs and videos to keep Kodi's watched functionalities
            folderType = 0 if 2 > folderType else 1
        else:
            # Actual views, set the main categories as vfs
            folderType = 0 if 2 > folderType else 2

        setContentAndView([None, 'videos', 'series', 'season', 'episode', 'movie'][folderType])
Пример #33
0
def getContent(url, params):
    log.debug("== ENTER: getContent ==")

    media_type = params.get("media_type", None)
    if not media_type:
        xbmcgui.Dialog().ok(i18n('error'), i18n('no_media_type'))

    log.debug("URL: {0}", url)
    log.debug("MediaType: {0}", media_type)
    pluginhandle = int(sys.argv[1])

    settings = xbmcaddon.Addon()
    # determine view type, map it from media type to view type
    view_type = ""
    content_type = ""
    media_type = str(media_type).lower().strip()
    if media_type.startswith("movie"):
        view_type = "Movies"
        content_type = 'movies'
    elif media_type == "musicalbums":
        view_type = "Albums"
        content_type = 'albums'
    elif media_type == "musicartists":
        view_type = "Artists"
        content_type = 'artists'
    elif media_type == "musicartist":
        view_type = "Albums"
        content_type = 'albums'
    elif media_type == "music" or media_type == "audio" or media_type == "musicalbum":
        view_type = "Music"
        content_type = 'songs'
    elif media_type.startswith("boxsets"):
        view_type = "Movies"
        content_type = 'sets'
    elif media_type.startswith("boxset"):
        view_type = "BoxSets"
        content_type = 'movies'
    elif media_type == "tvshows":
        view_type = "Series"
        content_type = 'tvshows'
    elif media_type == "series":
        view_type = "Seasons"
        content_type = 'seasons'
    elif media_type == "season" or media_type == "episodes":
        view_type = "Episodes"
        content_type = 'episodes'

    log.debug("media_type:{0} content_type:{1} view_type:{2} ", media_type,
              content_type, view_type)

    # show a progress indicator if needed
    progress = None
    if (settings.getSetting('showLoadProgress') == "true"):
        progress = xbmcgui.DialogProgress()
        progress.create(i18n('loading_content'))
        progress.update(0, i18n('retrieving_data'))

    # update url for paging
    start_index = 0
    page_limit = int(settings.getSetting('moviePageSize'))
    if page_limit > 0 and media_type.startswith("movie"):
        url_prev = None
        m = re.search('StartIndex=([0-9]{1,4})', url)
        if m and m.group(1):
            log.debug("UPDATING NEXT URL: {0}", url)
            start_index = int(m.group(1))
            log.debug("current_start : {0}", start_index)
            if start_index > 0:
                prev_index = start_index - page_limit
                if prev_index < 0:
                    prev_index = 0
                url_prev = re.sub('StartIndex=([0-9]{1,4})',
                                  'StartIndex=' + str(prev_index), url)
            url_next = re.sub('StartIndex=([0-9]{1,4})',
                              'StartIndex=' + str(start_index + page_limit),
                              url)
            log.debug("UPDATING NEXT URL: {0}", url_next)

        else:
            log.debug("ADDING NEXT URL: {0}", url)
            url_next = url + "&StartIndex=" + str(
                start_index + page_limit) + "&Limit=" + str(page_limit)
            url = url + "&StartIndex=" + str(start_index) + "&Limit=" + str(
                page_limit)
            log.debug("ADDING NEXT URL: {0}", url_next)

    # use the data manager to get the data
    result = dataManager.GetContent(url)

    total_records = 0
    if result is not None and isinstance(result, dict):
        total_records = result.get("TotalRecordCount", 0)

    dir_items, detected_type = processDirectory(result, progress, params)
    if dir_items is None:
        return

    # add paging items
    if page_limit > 0 and media_type.startswith("movie"):
        if url_prev:
            list_item = xbmcgui.ListItem("Prev Page (" +
                                         str(start_index - page_limit + 1) +
                                         "-" + str(start_index) + " of " +
                                         str(total_records) + ")")
            u = sys.argv[0] + "?url=" + urllib.quote(
                url_prev) + "&mode=GET_CONTENT&media_type=movies"
            dir_items.insert(0, (u, list_item, True))

        if start_index + page_limit < total_records:
            upper_count = start_index + (page_limit * 2)
            if upper_count > total_records:
                upper_count = total_records
            list_item = xbmcgui.ListItem("Next Page (" +
                                         str(start_index + page_limit + 1) +
                                         "-" + str(upper_count) + " of " +
                                         str(total_records) + ")")
            u = sys.argv[0] + "?url=" + urllib.quote(
                url_next) + "&mode=GET_CONTENT&media_type=movies"
            dir_items.append((u, list_item, True))

    # set the Kodi content type
    if content_type:
        xbmcplugin.setContent(pluginhandle, content_type)
    elif detected_type is not None:
        # if the media type is not set then try to use the detected type
        log.debug("Detected content type: {0}", detected_type)
        if detected_type == "Movie":
            view_type = "Movies"
            content_type = 'movies'
        if detected_type == "Episode":
            view_type = "Episodes"
            content_type = 'episodes'
        xbmcplugin.setContent(pluginhandle, content_type)

    # set the sort items
    if page_limit > 0 and media_type.startswith("movie"):
        xbmcplugin.addSortMethod(pluginhandle, xbmcplugin.SORT_METHOD_UNSORTED)
    else:
        setSort(pluginhandle, view_type)

    xbmcplugin.addDirectoryItems(pluginhandle, dir_items)
    xbmcplugin.endOfDirectory(pluginhandle, cacheToDisc=False)

    # send display items event
    display_items_notification = {"view_type": view_type}
    send_event_notification("display_items", display_items_notification)

    if (progress != None):
        progress.update(100, i18n('done'))
        progress.close()

    return
Пример #34
0
def setSort(pluginhandle, viewType):
    log.debug("SETTING_SORT for media type: {0}", viewType)
    if viewType == "BoxSets":
        xbmcplugin.addSortMethod(pluginhandle,
                                 xbmcplugin.SORT_METHOD_VIDEO_YEAR)
        xbmcplugin.addSortMethod(
            pluginhandle, xbmcplugin.SORT_METHOD_VIDEO_SORT_TITLE_IGNORE_THE)
    elif viewType == "Episodes":
        xbmcplugin.addSortMethod(pluginhandle, xbmcplugin.SORT_METHOD_EPISODE)
    elif viewType == "Music":
        xbmcplugin.addSortMethod(pluginhandle, xbmcplugin.SORT_METHOD_TRACKNUM)
    else:
        xbmcplugin.addSortMethod(
            pluginhandle, xbmcplugin.SORT_METHOD_VIDEO_SORT_TITLE_IGNORE_THE)
        xbmcplugin.addSortMethod(pluginhandle,
                                 xbmcplugin.SORT_METHOD_VIDEO_YEAR)

    xbmcplugin.addSortMethod(pluginhandle, xbmcplugin.SORT_METHOD_DATEADDED)
    xbmcplugin.addSortMethod(pluginhandle, xbmcplugin.SORT_METHOD_GENRE)
    xbmcplugin.addSortMethod(pluginhandle, xbmcplugin.SORT_METHOD_UNSORTED)
    xbmcplugin.addSortMethod(pluginhandle, xbmcplugin.SORT_METHOD_NONE)
    xbmcplugin.addSortMethod(pluginhandle, xbmcplugin.SORT_METHOD_VIDEO_RATING)
    xbmcplugin.addSortMethod(pluginhandle, xbmcplugin.SORT_METHOD_LABEL)
Пример #35
0
    #PTVL Channel Input
elif mode == 10000:
    InputChannel(int(url), previous)

    #PTVL Pre-Channel Input
elif mode == 10001:
    PreviewChannel(name, url, previous)

    #PTVL Export to PTVL
elif mode == 10002:
    export(name, url, previous)

elif mode == 10003:
    getYoutubePlaylist(url)

elif mode == 10004:
    REAL_SETTINGS.openSettings()
elif mode == 10005:
    PTVL_SETTINGS.openSettings()

elif mode == 12000:
    fillCE(url)

# if mode in [0,1,2,3,4,5,6]: back('Online')                      # Return to Online Menu
# elif mode in [9995,9999]: back('Main')                        # Return to Main Menu

# xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_NONE )
xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_LABEL)
xbmcplugin.setContent(int(sys.argv[1]), 'episodes')
xbmcplugin.endOfDirectory(int(sys.argv[1]), cacheToDisc=False)  # End List
Пример #36
0
def add_sort_methods(sort_type):
    if sort_type == 'sort_nothing':
        xbmcplugin.addSortMethod(g.PLUGIN_HANDLE, xbmcplugin.SORT_METHOD_NONE)
    if sort_type == 'sort_label':
        xbmcplugin.addSortMethod(g.PLUGIN_HANDLE, xbmcplugin.SORT_METHOD_LABEL)
    if sort_type == 'sort_label_ignore_folders':
        xbmcplugin.addSortMethod(g.PLUGIN_HANDLE,
                                 xbmcplugin.SORT_METHOD_LABEL_IGNORE_FOLDERS)
    if sort_type == 'sort_episodes':
        xbmcplugin.addSortMethod(g.PLUGIN_HANDLE,
                                 xbmcplugin.SORT_METHOD_EPISODE)
        xbmcplugin.addSortMethod(g.PLUGIN_HANDLE, xbmcplugin.SORT_METHOD_LABEL)
        xbmcplugin.addSortMethod(g.PLUGIN_HANDLE,
                                 xbmcplugin.SORT_METHOD_VIDEO_TITLE)
Пример #37
0
def setView(content, viewType):

    if content:
        xbmcplugin.setContent(int(sys.argv[1]), content)
    if addon.get_setting('auto-view') == 'true':

        print addon.get_setting(viewType)
        if addon.get_setting(viewType) == 'Info':
            VT = '504'
        elif addon.get_setting(viewType) == 'Info2':
            VT = '503'
        elif addon.get_setting(viewType) == 'Info3':
            VT = '515'
        elif addon.get_setting(viewType) == 'Fanart':
            VT = '508'
        elif addon.get_setting(viewType) == 'Poster Wrap':
            VT = '501'
        elif addon.get_setting(viewType) == 'Big List':
            VT = '51'
        elif viewType == 'default-view':
            VT = addon.get_setting(viewType)

        print viewType
        print VT

        xbmc.executebuiltin("Container.SetViewMode(%s)" % (int(VT)))

    xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                             sortMethod=xbmcplugin.SORT_METHOD_UNSORTED)
    xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                             sortMethod=xbmcplugin.SORT_METHOD_LABEL)
    xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                             sortMethod=xbmcplugin.SORT_METHOD_VIDEO_RATING)
    xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                             sortMethod=xbmcplugin.SORT_METHOD_DATE)
    xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                             sortMethod=xbmcplugin.SORT_METHOD_PROGRAM_COUNT)
    xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                             sortMethod=xbmcplugin.SORT_METHOD_VIDEO_RUNTIME)
    xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                             sortMethod=xbmcplugin.SORT_METHOD_GENRE)
    xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                             sortMethod=xbmcplugin.SORT_METHOD_MPAA_RATING)
Пример #38
0
def detalle(params,url,category):
	logger.info("[italiafilm.py] detalle")

	title = urllib.unquote_plus( params.get("title") )
	thumbnail = urllib.unquote_plus( params.get("thumbnail") )
	plot = urllib.unquote_plus( params.get("plot") )
	title = to_ita(title)
	title = title.title()
	title = title.replace('Serie Tv', '', 1)
	title = title.replace('Streaming', '', 1)
	title = title.replace('Megavideo', '', 1)
	
	# Descarga la página
	data = scrapertools.cachePage(url)
	data_next = ""

	patronvideos  = '<td class="news">.*?<div id=[^>]+>([^<]+)'
	matches = re.compile(patronvideos,re.DOTALL).findall(data)
	scrapertools.printMatches(matches)
	if (matches): 
		plot = matches[0]
		plot = to_ita(plot)

	# ------------------------------------------------------------------------------------
	# looking for seasons
	# ------------------------------------------------------------------------------------
	
	data = to_ita(data)

	sep_season = '<br /><br />'
	patronseason  = '>([^ ]+) ([s|S])tagione([^<]*)' + sep_season
	matches_season = re.compile(patronseason,re.DOTALL).findall(data)
	scrapertools.printMatches(matches_season)

	if (matches_season):
		logger.info("[italiafilm.py] season list match ok")
		
		i = 0 #counter for while
		while i < len(matches_season)-1:
			seasontitle = matches_season[i][0] + " " + matches_season[i][1] + "tagione" + matches_season[i][2]
			seasontitle_next = matches_season[i+1][0] + " " + matches_season[i+1][1] + "tagione" + matches_season[i+1][2]
			seasonlabel = xbmcgui.ListItem(seasontitle)
			seasonlabel.setInfo( type="Video", infoLabels={ "Title": seasontitle } )
			xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url="",listitem=seasonlabel,isFolder=False)
			i_season = data.find(seasontitle+sep_season) + len(seasontitle)+len(sep_season)
			data = data[i_season:]
			f_season = data.find(seasontitle_next+sep_season)
			data_next = data[f_season:]
			data = data[:f_season]
			
			loadvideo(params,data,category,title,thumbnail,plot)

			data = data_next
			data_next = ""
			i = i + 1
			#end while
		
		if (matches_season[i]):
			seasontitle = matches_season[i][0] + " " + matches_season[i][1] + "tagione" + matches_season[i][2]
			seasonlabel = xbmcgui.ListItem(seasontitle)
			seasonlabel.setInfo( type="Video", infoLabels={ "Title": seasontitle } )
			xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url="",listitem=seasonlabel,isFolder=False)
			i_season = data.find(seasontitle+sep_season) + len(seasontitle)+len(sep_season)
			data = data[i_season:]
			
	#end if matches_season
	# ------------------------------------------------------------------------------------
		
	loadvideo(params,data,category,title,thumbnail,plot)
		
	# Cierra el directorio
	xbmcplugin.setPluginCategory( handle=pluginhandle, category=category )
	xbmcplugin.addSortMethod( handle=pluginhandle, sortMethod=xbmcplugin.SORT_METHOD_NONE )
	xbmcplugin.endOfDirectory( handle=pluginhandle, succeeded=True )
Пример #39
0
 xbmcplugin.setPluginCategory(int(sys.argv[1]), name)
 if load_DB(name) == "": create_DB(url, name)
 else:
     data = load_DB(name)
     for film in data:
         if film["type"] == "film":
             if __settings__.getSetting("date_sortie") == "true":
                 ajout_sortie = "[CR]" + film.get("sortie", "")
             else:
                 ajout_sortie = ""
             addDir(film["name"] + ajout_sortie,
                    "%s##%s" % (film["poster"], film["id_allo"]),
                    2,
                    film["poster"],
                    sortie=film.get("sortie", ""))
             xbmcplugin.addSortMethod(int(sys.argv[1]),
                                      xbmcplugin.SORT_METHOD_TITLE)
             xbmcplugin.addSortMethod(int(sys.argv[1]),
                                      xbmcplugin.SORT_METHOD_DATE)
             #xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_NONE)
         else:
             #print "image:%s " % film["poster"]
             c_items = []
             local_trailer = os.path.join(
                 trailer_dir, "%s.flv" % translate_string(film["name"]))
             script = DOWNLOADER
             args = "%s&%s&%s" % (urllib.quote_plus(
                 "cmedia=%s" % film["id_media"]),
                                  urllib.quote_plus(local_trailer), quality)
             if not os.path.exists(local_trailer):
                 c_items += [("Télécharger",
                              "XBMC.RunScript(%s,%s)" % (script, args))]
Пример #40
0
def render_items(itemlist, parent_item):
    """
    Función encargada de mostrar el itemlist en kodi, se pasa como parametros el itemlist y el item del que procede
    @type itemlist: list
    @param itemlist: lista de elementos a mostrar

    @type parent_item: item
    @param parent_item: elemento padre
    """
    # Si el itemlist no es un list salimos
    if not type(itemlist) == list:
        return

    if parent_item.start:
        menu_icon = get_thumb('menu.png')
        menu = Item(channel="channelselector",
                    action="getmainlist",
                    viewmode="movie",
                    thumbnail=menu_icon,
                    title='Menu')
        itemlist.insert(0, menu)

    # Si no hay ningun item, mostramos un aviso
    if not len(itemlist):
        itemlist.append(Item(title="No hay elementos que mostrar"))

    genre = False
    if 'nero' in parent_item.title:
        genre = True
        anime = False
        if 'anime' in channeltools.get_channel_parameters(
                parent_item.channel)['categories']:
            anime = True

    # Recorremos el itemlist

    for item in itemlist:
        try:
            channel_parameters = channeltools.get_channel_parameters(
                item.channel)
        except:
            pass
        #logger.debug(item)
        # Si el item no contiene categoria, le ponemos la del item padre
        if item.category == "":
            item.category = parent_item.category

        # Si el item no contiene fanart, le ponemos el del item padre
        if item.fanart == "":
            item.fanart = parent_item.fanart

        if genre:

            valid_genre = True
            thumb = get_thumb(item.title, auto=True)
            if thumb != '':
                item.thumbnail = thumb
                valid_genre = True
            elif anime:
                valid_genre = True

        unify_enabled = config.get_setting('unify')

        #logger.debug('unify_enabled: %s' % unify_enabled)

        if unify_enabled and not channel_parameters[
                'adult'] and 'skip_unify' not in channel_parameters:
            # Formatear titulo con unify
            item = unify.title_format(item)
        else:
            #Formatear titulo metodo old school
            if item.text_color:
                item.title = '[COLOR %s]%s[/COLOR]' % (item.text_color,
                                                       item.title)
            if item.text_bold:
                item.title = '[B]%s[/B]' % item.title
            if item.text_italic:
                item.title = '[I]%s[/I]' % item.title

        # Añade headers a las imagenes si estan en un servidor con cloudflare
        from core import httptools

        if item.action == 'play':
            item.thumbnail = unify.thumbnail_type(item)
        else:
            item.thumbnail = httptools.get_url_headers(item.thumbnail)
        item.fanart = httptools.get_url_headers(item.fanart)
        # IconImage para folder y video
        if item.folder:
            icon_image = "DefaultFolder.png"
        else:
            icon_image = "DefaultVideo.png"

        #if not genre or (genre and valid_genre):
        # Creamos el listitem
        #listitem = xbmcgui.ListItem(item.title, iconImage=icon_image, thumbnailImage=unify.thumbnail_type(item))
        listitem = xbmcgui.ListItem(item.title,
                                    iconImage=icon_image,
                                    thumbnailImage=item.thumbnail)
        # Ponemos el fanart
        if item.fanart:
            fanart = item.fanart
        else:
            fanart = os.path.join(config.get_runtime_path(), "fanart.jpg")

        # Creamos el listitem
        #listitem = xbmcgui.ListItem(item.title)

        # values icon, thumb or poster are skin dependent.. so we set all to avoid problems
        # if not exists thumb it's used icon value
        if config.get_platform(True)['num_version'] >= 16.0:
            listitem.setArt({
                'icon': icon_image,
                'thumb': item.thumbnail,
                'poster': item.thumbnail,
                'fanart': fanart
            })
        else:
            listitem.setIconImage(icon_image)
            listitem.setThumbnailImage(item.thumbnail)
            listitem.setProperty('fanart_image', fanart)

        # No need it, use fanart instead
        # xbmcplugin.setPluginFanart(int(sys.argv[1]), os.path.join(config.get_runtime_path(), "fanart.jpg"))

        # Esta opcion es para poder utilizar el xbmcplugin.setResolvedUrl()
        # if item.isPlayable == True or (config.get_setting("player_mode") == 1 and item.action == "play"):
        if config.get_setting("player_mode") == 1 and item.action == "play":
            if item.folder:
                item.folder = False
            listitem.setProperty('IsPlayable', 'true')

        # Añadimos los infoLabels
        set_infolabels(listitem, item)

        # Montamos el menu contextual
        context_commands = set_context_commands(item, parent_item)

        # Añadimos el item
        if config.get_platform(True)['num_version'] >= 17.0:
            listitem.addContextMenuItems(context_commands)
        else:
            listitem.addContextMenuItems(context_commands, replaceItems=True)

        if not item.totalItems:
            item.totalItems = 0
        xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),
                                    url='%s?%s' % (sys.argv[0], item.tourl()),
                                    listitem=listitem,
                                    isFolder=item.folder,
                                    totalItems=item.totalItems)

    # Fijar los tipos de vistas...
    if config.get_setting("forceview"):
        # ...forzamos segun el viewcontent
        xbmcplugin.setContent(int(sys.argv[1]), parent_item.viewcontent)
    elif parent_item.channel not in ["channelselector", ""]:
        # ... o segun el canal
        xbmcplugin.setContent(int(sys.argv[1]), "movies")

    # Fijamos el "breadcrumb"
    xbmcplugin.setPluginCategory(handle=int(sys.argv[1]),
                                 category=parent_item.category.capitalize())

    # No ordenar items
    xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                             sortMethod=xbmcplugin.SORT_METHOD_NONE)

    # Cerramos el directorio
    xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=True)

    # Fijar la vista
    if config.get_setting("forceview"):
        viewmode_id = get_viewmode_id(parent_item)
        xbmc.executebuiltin("Container.SetViewMode(%s)" % viewmode_id)
    if parent_item.mode in ['silent', 'get_cached', 'set_cache', 'finish']:
        xbmc.executebuiltin("Container.SetViewMode(500)")
Пример #41
0
def show_listing(list_items,
                 category=None,
                 sort='unsorted',
                 ascending=True,
                 content=None,
                 cache=None,
                 selected=None):
    """Show a virtual directory in Kodi"""
    from xbmcgui import ListItem
    from addon import plugin

    set_property('container.url', 'plugin://' + addon_id() + plugin.path)
    xbmcplugin.setPluginFanart(handle=plugin.handle,
                               image=from_unicode(addon_fanart()))

    usemenucaching = get_setting_bool('usemenucaching', default=True)
    if cache is None:
        cache = usemenucaching
    elif usemenucaching is False:
        cache = False

    if content:
        # content is one of: files, songs, artists, albums, movies, tvshows, episodes, musicvideos
        xbmcplugin.setContent(plugin.handle, content=content)

    # Jump through hoops to get a stable breadcrumbs implementation
    category_label = ''
    if category:
        if not content:
            category_label = 'VRT NU / '
        if plugin.path.startswith(('/favorites/', '/resumepoints/')):
            category_label += localize(30428) + ' / '  # My
        if isinstance(category, int):
            category_label += localize(category)
        else:
            category_label += category
    elif not content:
        category_label = 'VRT NU'
    xbmcplugin.setPluginCategory(handle=plugin.handle, category=category_label)

    # FIXME: Since there is no way to influence descending order, we force it here
    if not ascending:
        sort = 'unsorted'

    # NOTE: When showing tvshow listings and 'showoneoff' was set, force 'unsorted'
    if get_setting_bool(
            'showoneoff',
            default=True) and sort == 'label' and content == 'tvshows':
        sort = 'unsorted'

    # Add all sort methods to GUI (start with preferred)
    xbmcplugin.addSortMethod(handle=plugin.handle,
                             sortMethod=SORT_METHODS[sort])
    for key in sorted(SORT_METHODS):
        if key != sort:
            xbmcplugin.addSortMethod(handle=plugin.handle,
                                     sortMethod=SORT_METHODS[key])

    # FIXME: This does not appear to be working, we have to order it ourselves
#    xbmcplugin.setProperty(handle=plugin.handle, key='sort.ascending', value='true' if ascending else 'false')
#    if ascending:
#        xbmcplugin.setProperty(handle=plugin.handle, key='sort.order', value=str(SORT_METHODS[sort]))
#    else:
#        # NOTE: When descending, use unsorted
#        xbmcplugin.setProperty(handle=plugin.handle, key='sort.order', value=str(SORT_METHODS['unsorted']))

    listing = []
    showfanart = get_setting_bool('showfanart', default=True)
    for title_item in list_items:
        # Three options:
        #  - item is a virtual directory/folder (not playable, path)
        #  - item is a playable file (playable, path)
        #  - item is non-actionable item (not playable, no path)
        is_folder = bool(not title_item.is_playable and title_item.path)
        is_playable = bool(title_item.is_playable and title_item.path)

        list_item = ListItem(label=title_item.label)

        prop_dict = dict(
            IsInternetStream='true' if is_playable else 'false',
            IsPlayable='true' if is_playable else 'false',
            IsFolder='false' if is_folder else 'true',
        )
        if title_item.prop_dict:
            title_item.prop_dict.update(prop_dict)
        else:
            title_item.prop_dict = prop_dict
        # NOTE: The setProperties method is new in Kodi18
        try:
            list_item.setProperties(title_item.prop_dict)
        except AttributeError:
            for key, value in list(title_item.prop_dict.items()):
                list_item.setProperty(key=key, value=str(value))

        # FIXME: The setIsFolder method is new in Kodi18, so we cannot use it just yet
        # list_item.setIsFolder(is_folder)

        if showfanart:
            # Add add-on fanart when fanart is missing
            if not title_item.art_dict:
                title_item.art_dict = dict(fanart=addon_fanart())
            elif not title_item.art_dict.get('fanart'):
                title_item.art_dict.update(fanart=addon_fanart())
            list_item.setArt(title_item.art_dict)

        if title_item.info_dict:
            # type is one of: video, music, pictures, game
            list_item.setInfo(type='video', infoLabels=title_item.info_dict)

        if title_item.stream_dict:
            # type is one of: video, audio, subtitle
            list_item.addStreamInfo('video', title_item.stream_dict)

        if title_item.context_menu:
            list_item.addContextMenuItems(title_item.context_menu)

        url = None
        if title_item.path:
            url = title_item.path

        listing.append((url, list_item, is_folder))

    # Jump to specific item
    if selected is not None:
        pass


#        from xbmcgui import getCurrentWindowId, Window
#        wnd = Window(getCurrentWindowId())
#        wnd.getControl(wnd.getFocusId()).selectItem(selected)

    succeeded = xbmcplugin.addDirectoryItems(plugin.handle, listing,
                                             len(listing))
    xbmcplugin.endOfDirectory(plugin.handle,
                              succeeded,
                              updateListing=False,
                              cacheToDisc=cache)
Пример #42
0
def get_film_list(url, database=False):
    catalogue = []
    page_data = get_html_source(url)
    count = 0
    pager = 1
    try:
        nbpage = int(
            re.findall('<span class="navcurrpage">.*</span>(.*?)</li>',
                       page_data)[0].strip(" / "))
    except:
        nbpage = 10
        print "impossible de trouver le nb de page"
        print_exc()
    print "nb pages: %s" % nbpage
    try:
        total_item = int(
            re.findall('<p class="extrazone">.* sur (.*?) r.*sultats</p>',
                       page_data)[0].strip(" / "))
    except:
        total_item = "error"
        print "impossible de trouver le nb d'item"
        print_exc()
    print "nb d'items: %s" % total_item

    #progress bar:
    #dp = xbmcgui.DialogProgress()
    #dp.create("Update Database")

    while pager <= nbpage and nbpage != "error" and pager <= [
            5, 10, 20, 30, 999
    ][int(__settings__.getSetting("page_limit"))]:
        if not pager == 1:
            current_url = "%s?page=%s" % (url, pager)
            print "page %s: %s" % (pager, current_url)
            page_data = get_html_source(current_url)

        try:
            #print page_data
            match = re.search(
                '<a href="/video/emissions/(.*?)/episode/\?cmedia=(.*?)">\s+<img src="(.*?)" alt="" />\s+</a>\s+</div>\s+<div style="float:left; position:relative; width:320px; height:220px; padding:95px 0 0 35px; overflow:hidden;">\s+<h2 class="fs18" style="color:#FFFFFF;">(.*?)</h2>',
                page_data)

            if match:
                film = {}
                count = count + 1
                film["type"] = match.group(1)
                film["poster"] = match.group(3)
                film["name"] = match.group(4)
                film["id_allo"] = match.group(2)
                film["id_media"] = match.group(2)
                if __settings__.getSetting("hdimage") == "true":
                    film["poster"] = film["poster"].replace(
                        "c_120_160/b_1_x/o_play.png_5_se", "r_760_x").replace(
                            "cx_120_96/b_1_x/o_play.png_5_se",
                            "r_760_x").replace(
                                "c_120_120/b_1_x/o_play.png_5_se", "r_760_x")
                    film["poster"] = film["poster"].replace(
                        "cx_120_113/o_overlayEmissions-P2C-120.png_1_c",
                        "r_760_x"
                    ).replace(
                        "cx_120_113/o_overlayEmissions-MerciQui-120.png_1_c",
                        "r_760_x"
                    ).replace(
                        "cx_120_113/o_overlayEmissions-LaMinute-120.png_1_c",
                        "r_760_x").replace(
                            "cx_120_113/o_overlayEmissions-D2DVD-120.png_1_c",
                            "r_760_x"
                        ).replace(
                            "cx_120_113/o_overlayEmissions-TES-120.png_1_c",
                            "r_760_x"
                        ).replace(
                            "cx_120_113/o_overlayEmissions-FauxR-120.png_1_c",
                            "r_760_x")
                catalogue.append(film)
                try:
                    c_items = []
                    local_trailer = os.path.join(
                        trailer_dir, "%s.flv" % translate_string(film["name"]))
                    script = DOWNLOADER
                    args = "%s&%s&%s" % (
                        urllib.quote_plus("cmedia=%s" % film["id_media"]),
                        urllib.quote_plus(local_trailer), quality)
                    if not os.path.exists(local_trailer):
                        c_items += [("Télécharger",
                                     "XBMC.RunScript(%s,%s)" % (script, args))]
                    else:
                        c_items += [("jouer en local",
                                     "xbmc.PlayMedia(%s)" % local_trailer)]
                    addDir(film["name"], film["id_media"], 5, film["poster"],
                           c_items)
                except:
                    print_exc()
                print "#######trouvé########trouvé############trouvé##########trouvé###########"
            MEDIA = re.compile(
                '<div class="mainzone">(.*?)<div class="spacer">',
                re.DOTALL).findall(page_data)
            #save_data(page_data)
            for i in MEDIA:
                if database: film = get_film_info(id_allo)
                else: film = {}
                #print i
                film["type"] = url.split("/")[4]
                if film["type"] == "bandes-annonces": film["type"] = "film"
                elif film["type"] == "series": film["type"] = "serie"

                print "###################type#############################"
                print film["type"]
                count = count + 1
                try:
                    ratio = int(100 * float(count) / float(total_item))
                except:
                    ratio = 0

                match = re.search("<a href=\'/video/emissions.*?>", i)
                if match: film["type"] = "emission"

                if film["type"] == "serie":
                    match = re.search("<strong>(.*?)</strong>(.*?)\s+</a>", i)
                elif film["type"] == "interviews":
                    match = re.search(
                        "<span class=\'bold\'>\s+(.*?)\s+</span>\s+(.*?)<br />",
                        i)
                elif film["type"] == "emission":
                    match = re.search(
                        "<span class=\'bold\'><strong>(.*?)</strong>(.*?)</span></a><br/>",
                        i)
                else:
                    match = re.search("<strong>(.*?)</strong>", i)
                save_data(i)

                film["name"] = ""
                if match:
                    if film["type"] == "serie":
                        film["name"] = match.group(1) + " " + match.group(
                            2)  #match.group(1).replace("</span>"," ")
                    elif film["type"] == "interviews":
                        film["name"] = match.group(1) + match.group(2)
                    elif film["type"] == "emission":
                        film["name"] = match.group(1) + match.group(2)
                    else:
                        film["name"] = match.group(1)

                print "récupération info %s (%s/%s): %s" % (
                    film["type"], count, total_item, film["name"])
                #dp.update(ratio , "récupération info %s (%s/%s)" % ( film["type"], count , total_item ), film["name"])
                #                 if dp.iscanceled() :
                #                     dp.close()
                #                     break
                match = re.search(
                    "<a href='/video/player_gen_cmedia=(.*?)&c%s=(.*?).html'" %
                    film["type"], i)
                if match:
                    film["id_allo"] = match.group(2)
                    film["id_media"] = match.group(1)
                    #print "############TEST###############" + "test id:%s %s" % (match.group(1) , match.group(2))
                else:
                    match = re.search("cmedia=(.*?)'", i)
                    if match:
                        film["id_allo"] = film["id_media"] = match.group(1)
                    else:
                        film["id_allo"] = film["id_media"] = ""

                match = re.search("<p>Date de sortie :\s+(.*?)</p>", i)
                if match:
                    print "sortie: %s " % match.group(1).replace("/", ".")
                    film["sortie"] = match.group(1).replace("/", ".")
                try:
                    film["poster"] = re.findall("<img src='(.*?)'", i)[0]
                except:
                    film["poster"] = ""
                print "hd image: %s" % __settings__.getSetting("hdimage")
                if __settings__.getSetting("hdimage") == "true":
                    film["poster"] = film["poster"].replace(
                        "c_120_160/b_1_x/o_play.png_5_se", "r_760_x").replace(
                            "cx_120_96/b_1_x/o_play.png_5_se",
                            "r_760_x").replace(
                                "c_120_120/b_1_x/o_play.png_5_se", "r_760_x")
                    film["poster"] = film["poster"].replace(
                        "cx_120_113/o_overlayEmissions-P2C-120.png_1_c",
                        "r_760_x"
                    ).replace(
                        "cx_120_113/o_overlayEmissions-MerciQui-120.png_1_c",
                        "r_760_x"
                    ).replace(
                        "cx_120_113/o_overlayEmissions-LaMinute-120.png_1_c",
                        "r_760_x").replace(
                            "cx_120_113/o_overlayEmissions-D2DVD-120.png_1_c",
                            "r_760_x"
                        ).replace(
                            "cx_120_113/o_overlayEmissions-TES-120.png_1_c",
                            "r_760_x"
                        ).replace(
                            "cx_120_113/o_overlayEmissions-FauxR-120.png_1_c",
                            "r_760_x")
                catalogue.append(film)
                if film["type"] == "film":
                    if __settings__.getSetting("date_sortie") == "true":
                        ajout_sortie = "[CR]" + film.get("sortie", "")
                    else:
                        ajout_sortie = ""
                    addDir(film["name"] + ajout_sortie,
                           "%s##%s" % (film["poster"], film["id_allo"]),
                           2,
                           film["poster"],
                           sortie=film.get("sortie", ""))
                    xbmcplugin.addSortMethod(int(sys.argv[1]),
                                             xbmcplugin.SORT_METHOD_TITLE)
                    xbmcplugin.addSortMethod(int(sys.argv[1]),
                                             xbmcplugin.SORT_METHOD_DATE)
                    #xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_NONE)
                else:
                    #print "image:%s " % film["poster"]
                    c_items = []
                    local_trailer = os.path.join(
                        trailer_dir, "%s.flv" % translate_string(film["name"]))
                    script = DOWNLOADER
                    args = "%s&%s&%s" % (
                        urllib.quote_plus("cmedia=%s" % film["id_media"]),
                        urllib.quote_plus(local_trailer), quality)
                    if not os.path.exists(local_trailer):
                        c_items += [("Télécharger",
                                     "XBMC.RunScript(%s,%s)" % (script, args))]
                    else:
                        c_items += [("jouer en local",
                                     "xbmc.PlayMedia(%s)" % local_trailer)]
                    addDir(film["name"], film["id_media"], 5, film["poster"],
                           c_items)

        except:
            print "probleme de récupération de la liste de film"
            print_exc()

        pager = pager + 1
    #dp.close()
    print "total movies = %s" % count
    return catalogue
Пример #43
0
 def add_sort_method(self, *sort_methods):
     for sort_method in sort_methods:
         xbmcplugin.addSortMethod(self._plugin_handle, sort_method)
Пример #44
0
    def list(self, page):
        if Debug: self.LOG('DEBUG: list()')
        _json = simplejson.loads(self._get(page))
        if page.startswith('/baroque') or \
           page.startswith('/classicism') or \
           page.startswith('/romantism') or \
           page.startswith('/piano') or \
           page.startswith('/singer') or \
           page.startswith('/violin') or \
           page.startswith('/instrument-cello') or \
           page.startswith('/conducting'):
            _soup = BS(_json['data'],
                       parseOnlyThese=SoupStrainer('div', 'list-small'))
            totalitems = len(_soup('div', 'block_media small spc-t'))
            soup = _soup('div', 'block_media small spc-t')
        elif page.startswith('/live/previous/'):
            _soup = BS(_json['data'],
                       parseOnlyThese=SoupStrainer('table', 'tbl_live bck-1'))
            #remove unneded lines.
            comments = _soup.findAll('a', 'button3 flt-r')
            [comment.extract() for comment in comments]
            totalitems = len(_soup('td', 'info'))
            soup = _soup('td', 'info')
        else:
            _soup = BS(_json['data'],
                       parseOnlyThese=SoupStrainer('div', 'list-medium'))
            totalitems = len(_soup('div', 'block_media spc-t'))
            soup = _soup('div', 'block_media spc-t')
        try:
            next_page = BS(_json['data']).find('div',
                                               'next').a['href'].split('#!')[1]
            pagination = True
        except:
            pagination = False
        for i in soup:
            if i.a:
                folders = i('a')[0]['href'].split('#!')[1]
                try:
                    if Debug: self.LOG('DEBUG: Trying to read from cache!')
                    s = shelve.open(
                        xbmc.translatePath(__cachedir__) + '/medici.db')
                    try:
                        entry = s[str(folders)]
                    finally:
                        s.close()
                except:
                    if Debug: self.LOG('DEBUG: Not cached! Get from website!')
                    entry = self._details(folders)
                title = entry['title']
                desc = entry['description']
                fanart = entry['fanart']
                quality = __get_settings__('quality')
                if quality == '0':
                    video = entry['video_low']
                if quality == '1':
                    video = entry['video_mid']
                if quality == '2':
                    if entry['video_high'] == '':
                        video = entry['video_mid']
                        if Debug:
                            self.LOG(
                                'DEBUG: high video quality is not found. Revert to mid quality!'
                            )
                    else:
                        video = entry['video_high']
                try:
                    mode = entry['mode']
                except:
                    mode = ''

                if Debug:                    self.LOG('DEBUG:\n\tfolder: %s\n\ttitle: %s\n\tdescription: %s\n\tvideo: %s\n\tfanart: %s\n\tmode: %s\n' % \
                             (folders, title, desc, video, fanart, mode))
                listitem = xbmcgui.ListItem(title,
                                            iconImage="DefaultFolder.png",
                                            thumbnailImage=fanart)
                listitem.setProperty('fanart_image', fanart)
                # set list information
                listitem.setInfo(
                    'video', {
                        'title': title,
                        'label': title,
                        'plot': desc,
                        'PlotOutline': desc,
                    })
                if mode == '' or video == '':
                    parameters = '%s' % (sys.argv[0])
                else:
                    parameters = '%s?action=play&url=%s&mode=%s' % (
                        sys.argv[0], urllib.quote_plus(video), mode)
                xbmcplugin.addDirectoryItems(int(sys.argv[1]),
                                             [(parameters, listitem, False)],
                                             totalitems)
            else:
                pass
        if pagination:
            listitem = xbmcgui.ListItem('Next Page >>',
                                        iconImage='DefaultVideo.png',
                                        thumbnailImage=__icon__)
            parameters = '%s?action=list&next_page=%s' % (sys.argv[0],
                                                          next_page)
            xbmcplugin.addDirectoryItem(int(sys.argv[1]), parameters, listitem,
                                        True)
        xbmcplugin.setContent(int(sys.argv[1]), 'musicvideos')
        xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_NONE)
        xbmcplugin.endOfDirectory(int(sys.argv[1]), True)
Пример #45
0
 def setEndOfDirectory(self):
     iHandler = cPluginHandler().getPluginHandle()
     xbmcplugin.setPluginCategory(iHandler, "")
     xbmcplugin.setContent(iHandler, cGui.CONTENT)
     xbmcplugin.addSortMethod(iHandler, xbmcplugin.SORT_METHOD_NONE)
     xbmcplugin.endOfDirectory(iHandler, True)
Пример #46
0
    def getVideoListXML(self):
        findVideo = False
        paginationUrl = ''
        if self.page > 0:
            paginationUrl = "&start_rec=" + str(self.page * PAGE_MOVIES)
        try:
            elems = ET.parse(urllib.urlopen(self.url +
                                            paginationUrl)).getroot()
            epgItems = elems.findall("epg_item")
            if not epgItems:
                epgItems = elems.findall("directory_stats/video")
            if not epgItems:
                epgItems = elems.findall("directory_standard/video")
            if not epgItems:
                epgItems = elems.findall("video")
            if not epgItems:
                epgItems = elems.findall("directory_video/video")

            pub = elems.findall("publication_status")
            if pub[0].attrib['publication_status_id'] == '4':
                d = xbmcgui.Dialog()
                d.ok('Brak video', pub[0].attrib['name'].encode('utf-8'))

            #print "test[6]: " + str(len(epgItems))

            listsize = len(epgItems)
            xbmcplugin.setContent(HANDLE, 'episodes')
            xbmcplugin.addSortMethod(
                handle=HANDLE, sortMethod=xbmcplugin.SORT_METHOD_UNSORTED)
            xbmcplugin.addSortMethod(handle=HANDLE,
                                     sortMethod=xbmcplugin.SORT_METHOD_LABEL)

            for epgItem in epgItems:
                prop = {
                    'title': epgItem.find("title").text.encode('utf-8'),
                    'TVShowTitle': self.name
                }
                if epgItem.attrib['hptitle'] <> '':
                    prop['title'] = epgItem.attrib['hptitle'].encode('utf-8')
                if epgItem.attrib['release_date']:
                    prop['aired'] = epgItem.attrib['release_date']
                if epgItem.get('episode_number'):
                    prop['episode'] = epgItem.attrib['episode_number']
                prop['description'] = ''
                textNode = epgItem.find('text_paragraph_standard/text')
                #print "test[8]:" + textNode.text.encode('utf-8')
                if ET.iselement(textNode):
                    prop['description'] = textNode.text.encode('utf-8')
                    prop['description'] = prop['description'].replace(
                        "<BR/>", "")

                iconUrl = ''
                videoUrl = ''
                iconFileNode = epgItem.find('video/image')
                if not iconFileNode:
                    iconFileNode = epgItem.find('image')

                if iconFileNode:
                    iconFileName = iconFileNode.attrib['file_name']
                    iconFileName = iconFileName.split('.')
                    iconUrl = 'http://s.v3.tvp.pl/images/6/2/4/uid_%s_width_700.jpg' % iconFileName[
                        0]
                    iconTitle = iconFileNode.find('title').text.encode('utf-8')
                    if len(iconTitle) > 4 and iconTitle <> prop['title']:
                        if iconTitle <> 'zdjecie domyślne' and iconTitle <> 'image' and iconTitle <> 'obrazek':
                            iconTitle = iconTitle.split(',')[0]
                            prop['title'] = iconTitle + " - " + prop['title']
                    #print "test[4]: " + iconUrl

                videMainNode = epgItem.find('video')
                if ET.iselement(videMainNode):
                    #print "test[7]: " + str(ET.dump(videMainNode))
                    # 2400 00:41:28  2488
                    # 2100 00:35:50  2150
                    if videMainNode.attrib['release_date']:
                        prop['aired'] = videMainNode.attrib['release_date']
                    if videMainNode.attrib['episode_number']:
                        prop['episode'] = videMainNode.attrib['episode_number']

                    videoText = videMainNode.find('text_paragraph_lead/text')
                    if ET.iselement(videoText):
                        if len(prop['description']) < videoText.text.encode(
                                'utf-8'):
                            prop['description'] = videoText.text.encode(
                                'utf-8')

                    prop['time'] = int(videMainNode.attrib['duration'])
                    iconTitle = videMainNode.find('title').text.encode('utf-8')
                    if len(iconTitle) > 4 and iconTitle <> prop['title']:
                        if iconTitle <> 'zdjecie domyślne' and iconTitle <> 'image' and iconTitle <> 'obrazek':
                            iconTitle = iconTitle.split(',')[0]
                            prop['title'] = prop['title'] + " - " + iconTitle

                videoNode = epgItem.find('video/video_format')
                if not videoNode:
                    videoNode = epgItem.find('video_format')

                if videoNode:
                    videoUrl = videoNode.attrib['temp_sdt_url']

                if videoUrl != '':
                    #if self.watched(videoUrl):
                    #    prop['overlay'] = 7

                    self.addVideoLink(prop, videoUrl, iconUrl, listsize)
                    #print "test[4]: " + prop['title'] + ", " + iconUrl + ", " + videoUrl
                    findVideo = True
        except urllib2.HTTPError, e:
            err = str(e)
            msg = e.read()
            xbmc.executebuiltin('XBMC.Notification("%s", "%s", %s)' %
                                (err, msg, 5))
Пример #47
0
# -*- coding: utf-8 -*-
import sys
import requests
import xbmcplugin
from xbmcgui import ListItem
from xbmcaddon import Addon

addon_handle = int(sys.argv[1])
my_addon = Addon('plugin.audio.radiorecord')
xbmcplugin.setContent(addon_handle, 'albums')

if __name__ == "__main__":
    station_list = requests.get(
        'https://radiorecord.ru/api/stations/').json().get('result')
    for station in station_list.get('stations'):
        item = ListItem(station.get('title'))
        item.setArt({
            'thumb': station.get('icon_fill_white'),
            'icon': station.get('icon_fill_white'),
            'fanart': my_addon.getAddonInfo('fanart')
        })
        item.setInfo(type="music", infoLabels={"title": station.get('title')})
        item.setProperty('isPlayable', 'true')
        xbmcplugin.addDirectoryItem(addon_handle, station['stream_320'], item,
                                    False)
    xbmcplugin.addSortMethod(addon_handle, 1)
    xbmcplugin.endOfDirectory(addon_handle)
Пример #48
0
def setView(content, viewType):
    ''' Why recode whats allready written and works well,
    Thanks go to Eldrado for it '''
    if content:
        xbmcplugin.setContent(int(sys.argv[1]), content)
    if addon.get_setting('auto-view') == 'true':

        print addon.get_setting(viewType)
        if addon.get_setting(viewType) == 'Info':
            VT = '504'
        elif addon.get_setting(viewType) == 'Info2':
            VT = '503'
        elif addon.get_setting(viewType) == 'Info3':
            VT = '515'
        elif addon.get_setting(viewType) == 'Fanart':
            VT = '508'
        elif addon.get_setting(viewType) == 'Poster Wrap':
            VT = '501'
        elif addon.get_setting(viewType) == 'Big List':
            VT = '51'
        elif addon.get_setting(viewType) == 'Low List':
            VT = '724'
        elif addon.get_setting(viewType) == 'Thumbnail':
            VT = '500'
        elif addon.get_setting(viewType) == 'Default View':
            VT = addon.get_setting('default-view')
        #elif viewType == 'default-view':
        #VT = addon.get_setting(viewType)

        print viewType
        print VT

        xbmc.executebuiltin("Container.SetViewMode(%s)" % (int(VT)))

    xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                             sortMethod=xbmcplugin.SORT_METHOD_UNSORTED)
    xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                             sortMethod=xbmcplugin.SORT_METHOD_LABEL)
    xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                             sortMethod=xbmcplugin.SORT_METHOD_VIDEO_RATING)
    xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                             sortMethod=xbmcplugin.SORT_METHOD_DATE)
    xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                             sortMethod=xbmcplugin.SORT_METHOD_PROGRAM_COUNT)
    xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                             sortMethod=xbmcplugin.SORT_METHOD_VIDEO_RUNTIME)
    xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                             sortMethod=xbmcplugin.SORT_METHOD_GENRE)
    xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                             sortMethod=xbmcplugin.SORT_METHOD_MPAA_RATING)
def renderItems(itemlist, parentitem, isPlayable='false'):
    logger.info("streamondemand.platformcode.xbmctools renderItems")

    viewmode = "list"

    if itemlist <> None:
        for item in itemlist:
            logger.info("item=" + item.tostring())
            item.totalItems = len(itemlist)
            item.isPlayable = isPlayable

            if item.category == "":
                item.category = parentitem.category

            if item.fulltitle == "":
                item.fulltitle = item.title

            if item.fanart == "":
                channel_fanart = os.path.join(config.get_runtime_path(),
                                              'resources', 'images', 'fanart',
                                              item.channel + '.jpg')

                if os.path.exists(channel_fanart):
                    item.fanart = channel_fanart
                else:
                    item.fanart = os.path.join(config.get_runtime_path(),
                                               "fanart.jpg")

            # Formatear titulo
            if 'text_color' in item and item.text_color:
                item.title = '[COLOR %s]%s[/COLOR]' % (item.text_color,
                                                       item.title)
            if 'text_blod' in item and item.text_blod:
                item.title = '[B]%s[/B]' % (item.title)
            if 'text_italic' in item and item.text_italic:
                item.title = '[I]%s[/I]' % (item.title)

            if item.folder:
                add_new_folder(item, totalItems=len(itemlist))
            else:
                if config.get_setting(
                        "player_mode"
                ) == "1":  # SetResolvedUrl debe ser siempre "isPlayable = true"
                    item.isPlayable = 'true'

                add_new_video(item,
                              IsPlayable=item.isPlayable,
                              totalItems=len(itemlist))

            if item.viewmode != "list":
                viewmode = item.viewmode
        viewmode = parentitem.viewmode
        # Cierra el directorio
        # if not parentitem.channel in ["channelselector",""]:
        # xbmcplugin.setContent(pluginhandle,"Movies")
        xbmcplugin.setPluginCategory(handle=pluginhandle,
                                     category=parentitem.category)
        xbmcplugin.addSortMethod(handle=pluginhandle,
                                 sortMethod=xbmcplugin.SORT_METHOD_NONE)

        # Modos biblioteca
        # MediaInfo3 - 503
        #
        # Modos fichero
        # WideIconView - 505
        # ThumbnailView - 500

        if config.get_setting("forceview") == "true":
            if viewmode == "list":
                xbmc.executebuiltin("Container.SetViewMode(50)")
            elif viewmode == "movie_with_plot":
                xbmc.executebuiltin("Container.SetViewMode(503)")
            elif viewmode == "movie":
                xbmc.executebuiltin("Container.SetViewMode(500)")

    xbmcplugin.endOfDirectory(handle=pluginhandle, succeeded=True)
Пример #50
0
params = get_params()
url = None
name = None
mode = None

try:
    url = urllib.unquote_plus(params["url"])
except:
    pass
try:
    name = urllib.unquote_plus(params["name"])
except:
    pass
try:
    mode = int(params["mode"])
except:
    pass

if mode == None:
    print ""
    getCategories()

elif mode == 1:
    print "" + url
    getChannels(url)

xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                         sortMethod=xbmcplugin.SORT_METHOD_LABEL)
xbmcplugin.endOfDirectory(int(sys.argv[1]))
Пример #51
0
def ListListenList(logged_in):
    if (CheckLogin(logged_in) == False):
        CreateBaseDirectory('audio')
        return
    """Scrapes all episodes of the favourites page."""
    html = OpenURL('http://www.bbc.co.uk/radio/favourites/episodesandclips')

    programmes = html.split('<div class="favourites box-link favourite ')
    for programme in programmes:

        if not programme.startswith('media'):
            continue

        data_available_match = re.search(r'data-is-available="(.*?)"',
                                         programme)
        if ((not data_available_match)
                or (data_available_match.group(1) == '')):
            continue

        series_id = ''
        series_name = ''
        series_id_match = re.search(
            r'<a href="http://www.bbc.co.uk/programmes/(.*?)" class="media__meta-row size-f clr-light-grey text--single-line">\s*(.*?)\s*</a>',
            programme)
        if series_id_match:
            series_name = series_id_match.group(2)
            series_id = series_id_match.group(1)

        episode_name = ''
        episode_id = ''
        episode_id_match = re.search(
            r'<a aria-label="(.*?) Duration: (.*?)" class="favourites__brand-link(.*?)" href="http://www.bbc.co.uk/programmes/(.*?)#play">',
            programme)
        if episode_id_match:
            episode_name = episode_id_match.group(1)
            episode_id = episode_id_match.group(4)

        episode_image = ''
        episode_image_match = re.search(
            r'<img alt="" class="favourites__brand-image media__image " src="(.*?)"',
            programme)
        if episode_image_match:
            episode_image = "http:%s" % episode_image_match.group(1)

        series_image = ''
        series_image_match = re.search(
            r'<img class="media__image avatar-image--small" src="(.*?)">',
            programme)
        if series_image_match:
            series_image = "http:%s" % series_image_match.group(1)
            series_image = re.sub(r'96x96', '640x360', series_image)

        station = ''
        station_match = re.search(
            r'<span class="favourites__network-name.*?<a href="(.*?)" class="clr-light-grey">\s+?(.*?)\s+?<',
            programme,
            flags=(re.DOTALL | re.MULTILINE))
        if station_match:
            station = station_match.group(2).strip()

        description = ''
        description_match = re.search(
            r'<p class="favourites__description media__meta-row size-f clr-white.*?">\s+?(.*?)\s+?</p>',
            programme,
            flags=(re.DOTALL | re.MULTILINE))
        if description_match:
            description = description_match.group(1).strip()

        if series_id:
            series_title = "[B]%s - %s[/B]" % (station, series_name)
            AddMenuEntry(series_title, series_id, 131, series_image,
                         description, '')

        if episode_id:
            if series_name:
                episode_title = "[B]%s[/B] - %s - %s" % (station, series_name,
                                                         episode_name)
            else:
                episode_title = "[B]%s[/B] - %s" % (station, episode_name)
            episode_url = "http://www.bbc.co.uk/programmes/%s" % episode_id
            # xbmc.log(episode_url)
            CheckAutoplay(episode_title, episode_url, episode_image, ' ', '')

    xbmcplugin.addSortMethod(int(sys.argv[1]),
                             xbmcplugin.SORT_METHOD_VIDEO_TITLE)
    xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_UNSORTED)
Пример #52
0
def list(params,url,category):
	logger.info("[newcineonline.py] list")

	# Descarga la página
	data = scrapertools.cachePage(url)
	#logger.info(data)

	# Extrae las entradas (carpetas)
	patronvideos  = '<div id="post-info-mid">[^<]+<div class="post-title"><a href="([^"]+)">([^<]+)</a></div>'
	patronvideos += '.*?<td class="post-story">.*?<tbody>.*?<img src="([^"]+)"[^>]+>(.*?)</tbody>'
	matches = re.compile(patronvideos,re.DOTALL).findall(data)
	scrapertools.printMatches(matches)

	for match in matches:
		# Titulo
		scrapedtitle = match[1]

		# URL
		scrapedurl = urlparse.urljoin(url,match[0])
		
		# Thumbnail
		scrapedthumbnail = urlparse.urljoin(url,match[2])
		
		# procesa el resto
		scrapeddescription = match[3]
		scrapeddescription = scrapertools.htmlclean(scrapeddescription)
		scrapeddescription = scrapeddescription.replace("<!--colorstart:#589BB9-->","")
		scrapeddescription = scrapeddescription.replace("<!--colorend-->","")
		scrapeddescription = scrapeddescription.replace("<!--/colorend-->","")
		scrapeddescription = scrapeddescription.replace("<!--/colorstart-->","")
		scrapeddescription = scrapeddescription.strip()

		# Depuracion
		if (DEBUG):
			logger.info("scrapedtitle="+scrapedtitle)
			logger.info("scrapedurl="+scrapedurl)
			logger.info("scrapedthumbnail="+scrapedthumbnail)

		# Añade al listado de XBMC
		#addfolder( scrapedtitle , scrapedurl , "detail" )
		xbmctools.addnewfolder( CHANNELNAME , "detail" , CHANNELNAME , scrapedtitle , scrapedurl , scrapedthumbnail , scrapeddescription )

	# ------------------------------------------------------------------------------------
	# Busca los enlaces a los mirrors, o a los capítulos de las series...
	# ------------------------------------------------------------------------------------
	logger.info("Busca el enlace de página siguiente...")
	try:
		# La siguiente página
		patronvideos  = '<a href\="([^"]+)"><span class\="navigation"[^>]+>Sigu'
		matches = re.compile(patronvideos,re.DOTALL).findall(data)
		
		url = matches[0]
		addfolder("!Siguiente",url,"list")
	except:
		logger.info("No encuentro la pagina...")

	# Label (top-right)...
	xbmcplugin.setPluginCategory( handle=int( sys.argv[ 1 ] ), category=category )

	# Disable sorting...
	xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_NONE )

	# End of directory...
	xbmcplugin.endOfDirectory( handle=int( sys.argv[ 1 ] ), succeeded=True )
Пример #53
0
 def set_view(self, view, content=None, viewid=None):
     if self.ENABLE_DEFAULT_VIEWS:
         if content:
             xbmcplugin.setContent(int(sys.argv[1]), content)
         if viewid == 0:
             pass
         elif not viewid:
             viewid = view
         xbmc.executebuiltin("Container.SetViewMode(%s)" % viewid)
         xbmcplugin.addSortMethod(
             handle=int(sys.argv[1]),
             sortMethod=xbmcplugin.SORT_METHOD_UNSORTED)
         xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                                  sortMethod=xbmcplugin.SORT_METHOD_LABEL)
         xbmcplugin.addSortMethod(
             handle=int(sys.argv[1]),
             sortMethod=xbmcplugin.SORT_METHOD_VIDEO_RATING)
         xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                                  sortMethod=xbmcplugin.SORT_METHOD_DATE)
         xbmcplugin.addSortMethod(
             handle=int(sys.argv[1]),
             sortMethod=xbmcplugin.SORT_METHOD_PROGRAM_COUNT)
         xbmcplugin.addSortMethod(
             handle=int(sys.argv[1]),
             sortMethod=xbmcplugin.SORT_METHOD_VIDEO_RUNTIME)
         xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                                  sortMethod=xbmcplugin.SORT_METHOD_GENRE)
Пример #54
0
def ListFollowing(logged_in):
    if (CheckLogin(logged_in) == False):
        CreateBaseDirectory('audio')
        return
    """Scrapes all episodes of the favourites page."""
    html = OpenURL('https://www.bbc.co.uk/radio/favourites/programmes')

    programmes = html.split('<div class="favourites follow ')
    for programme in programmes:

        if not programme.startswith('media'):
            continue

        series_id = ''
        series_name = ''
        series_id_match = re.search(
            r'<a aria-label="(.*?)" class="follows__image-link" href="http://www.bbc.co.uk/programmes/(.*?)">',
            programme)
        if series_id_match:
            series_name = series_id_match.group(1)
            series_id = series_id_match.group(2)

        episode_name = ''
        episode_id = ''
        episode_id_match = re.search(
            r'<a aria-label="(.*?)" class="size-e clr-white" href="http://www.bbc.co.uk/programmes/(.*?)#play"',
            programme)
        if episode_id_match:
            episode_name = episode_id_match.group(1)
            episode_id = episode_id_match.group(2)

        episode_image = ''
        series_image = ''
        series_image_match = re.search(
            r'<img class="media__image" src="(.*?)"', programme)
        if series_image_match:
            series_image = "https:%s" % series_image_match.group(1)
            episode_image = series_image

        station = ''
        station_match = re.search(
            r'<a href="(.*?)" class="clr-light-grey">\s*(.*?)\s*</a>',
            programme,
            flags=(re.DOTALL | re.MULTILINE))
        if station_match:
            station = station_match.group(2).strip()

        description = ''

        if series_id:
            series_title = "[B]%s - %s[/B]" % (station, series_name)
            AddMenuEntry(series_title, series_id, 131, series_image,
                         description, '')

        if episode_id:
            if series_name:
                episode_title = "[B]%s[/B] - %s - %s" % (station, series_name,
                                                         episode_name)
            else:
                episode_title = "[B]%s[/B] - %s" % (station, episode_name)
            episode_url = "http://www.bbc.co.uk/programmes/%s" % episode_id
            # xbmc.log(episode_url)
            CheckAutoplay(episode_title, episode_url, episode_image, ' ', '')

    xbmcplugin.addSortMethod(int(sys.argv[1]),
                             xbmcplugin.SORT_METHOD_VIDEO_TITLE)
    xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_UNSORTED)
Пример #55
0
def detail(params, url, category):
    logger.info("[discoverymx.py] detail")

    title = urllib.unquote_plus(params.get("title"))
    thumbnail = urllib.unquote_plus(params.get("thumbnail"))
    plot = urllib.unquote_plus(params.get("plot"))

    # Descarga la página
    data = scrapertools.cachePage(url)
    #logger.info(data)

    # ------------------------------------------------------------------------------------
    # Busca los enlaces a videos no megavideo (youtube)
    # ------------------------------------------------------------------------------------
    patronyoutube = '<a href="http\:\/\/www.youtube.com/watch\?v=[^=]+=PlayList\&amp\;p=(.+?)&[^"]+"'
    matchyoutube = re.compile(patronyoutube, re.DOTALL).findall(data)
    if len(matchyoutube) > 0:
        for match in matchyoutube:
            listyoutubeurl = 'http://www.youtube.com/view_play_list?p=' + match
            data1 = scrapertools.cachePage(listyoutubeurl)
            newpatronyoutube = '<a href="(.*?)".*?<img src="(.*?)".*?alt="([^"]+)"'
            matchnewyoutube = re.compile(newpatronyoutube,
                                         re.DOTALL).findall(data1)
            if len(matchnewyoutube) > 0:
                for match2 in matchnewyoutube:
                    scrapedthumbnail = match2[1]
                    scrapedtitle = match2[2]
                    scrapedurl = match2[0]
                    if (DEBUG):
                        logger.info("title=[" + scrapedtitle + "], url=[" +
                                    scrapedurl + "], thumbnail=[" +
                                    scrapedthumbnail + "]")
                    xbmctools.addnewvideo(CHANNELNAME, "youtubeplay", category,
                                          "Directo",
                                          scrapedtitle + " - " + "(youtube) ",
                                          scrapedurl, scrapedthumbnail, plot)
                logger.info(" lista de links encontrados U " +
                            str(len(matchnewyoutube)))


#-------------------------------------------------------------------------------
#<a href="http://www.youtube.com/watch?v=je-692ngMY0" target="_blank">parte 1</a>
    patronyoutube = '<a href="(http://www.youtube.com/watch\?v\=[^"]+)".*?>(.*?)</a>'
    matchyoutube = re.compile(patronyoutube, re.DOTALL).findall(data)
    if len(matchyoutube) > 0:
        for match in matchyoutube:
            if "PlayList" not in match[0]:
                scrapedtitle = match[1]
                scrapedtitle = re.sub("<[^>]+>", " ", scrapedtitle)
                scrapedurl = match[0]
                if (DEBUG):
                    logger.info("title=[" + scrapedtitle + "], url=[" +
                                scrapedurl + "], thumbnail=[" +
                                scrapedthumbnail + "]")
                xbmctools.addnewvideo(CHANNELNAME, "youtubeplay", category,
                                      "Directo",
                                      scrapedtitle + " - " + "(youtube) ",
                                      scrapedurl, thumbnail, plot)
    else:
        patronyoutube = "<param name='movie' value='(http://www.youtube.com/v/[^']+)'"
        matchyoutube = re.compile(patronyoutube, re.DOTALL).findall(data)
        parte = 0
        for match in matchyoutube:
            parte = parte + 1
            scrapedurl = match
            scrapedtitle = title
            scrapedthumbnail = thumbnail
            re.compile(patronyoutube, re.DOTALL).findall(data)
            xbmctools.addnewvideo(
                CHANNELNAME, "youtubeplay", category, "Directo",
                scrapedtitle + " - " + str(parte) + " (youtube) ", scrapedurl,
                scrapedthumbnail, plot)
    # ------------------------------------------------------------------------------------
    # Busca los enlaces a los videos
    # ------------------------------------------------------------------------------------
    listavideos = servertools.findvideos(data)

    for video in listavideos:
        videotitle = video[0]
        url = video[1]
        server = video[2]
        xbmctools.addnewvideo(CHANNELNAME, "play", category, server,
                              title.strip() + " - " + videotitle, url,
                              thumbnail, plot)
    # ------------------------------------------------------------------------------------
    '''
	patronvideos = '(http://www.zshare.net/download/[^"]+)"'
	matches = re.compile(patronvideos,re.DOTALL).findall(data)
	for match in matches:
		import zshare
		scrapedurl = zshare.geturl(match).replace(" ","%20")
		scrapedtitle = title
		re.compile(patronyoutube,re.DOTALL).findall(data)
		xbmctools.addnewvideo( CHANNELNAME , "play" , category , "Directo" , scrapedtitle +" - "+"(Zshare) ", scrapedurl , thumbnail , plot )
	'''
    # Label (top-right)...
    xbmcplugin.setPluginCategory(handle=pluginhandle, category=category)

    # Disable sorting...
    xbmcplugin.addSortMethod(handle=pluginhandle,
                             sortMethod=xbmcplugin.SORT_METHOD_NONE)

    # End of directory...
    xbmcplugin.endOfDirectory(handle=pluginhandle, succeeded=True)
Пример #56
0
def GetPage(page_url, just_episodes=False):
    """   Generic Radio page scraper.   """

    pDialog = xbmcgui.DialogProgressBG()
    pDialog.create(translation(30319))

    html = OpenURL(page_url)

    total_pages = 1
    current_page = 1
    page_range = range(1)
    paginate = re.search(r'<ol.+?class="pagination.*?</ol>', html)
    next_page = 1
    if paginate:
        if int(ADDON.getSetting('radio_paginate_episodes')) == 0:
            current_page_match = re.search(r'page=(\d*)', page_url)
            if current_page_match:
                current_page = int(current_page_match.group(1))
            page_range = range(current_page, current_page + 1)
            next_page_match = re.search(
                r'<li class="pagination__next"><a href="(.*?page=)(.*?)">',
                paginate.group(0))
            if next_page_match:
                page_base_url = next_page_match.group(1)
                next_page = int(next_page_match.group(2))
            else:
                next_page = current_page
            page_range = range(current_page, current_page + 1)
        else:
            pages = re.findall(r'<li.+?class="pagination__page.*?</li>',
                               paginate.group(0))
            if pages:
                last = pages[-1]
                last_page = re.search(r'<a.+?href="(.*?=)(.*?)"', last)
                page_base_url = last_page.group(1)
                total_pages = int(last_page.group(2))
            page_range = range(1, total_pages + 1)

    for page in page_range:

        if page > current_page:
            page_url = 'http://www.bbc.co.uk' + page_base_url + str(page)
            html = OpenURL(page_url)

        masthead_title = ''
        masthead_title_match = re.search(
            r'<div.+?id="programmes-main-content".*?<span property="name">(.+?)</span>',
            html)
        if masthead_title_match:
            masthead_title = masthead_title_match.group(1)

        list_item_num = 1

        programmes = html.split('<div class="programme ')
        for programme in programmes:

            if not programme.startswith("programme--radio"):
                continue

            if "available" not in programme:  #TODO find a more robust test
                continue

            series_id = ''
            series_id_match = re.search(
                r'<a class="iplayer-text js-lazylink__link" href="/programmes/(.+?)/episodes/player"',
                programme)
            if series_id_match:
                series_id = series_id_match.group(1)

            programme_id = ''
            programme_id_match = re.search(r'data-pid="(.+?)"', programme)
            if programme_id_match:
                programme_id = programme_id_match.group(1)

            name = ''
            name_match = re.search(r'<span property="name">(.+?)</span>',
                                   programme)
            if name_match:
                name = name_match.group(1)

            subtitle = ''
            subtitle_match = re.search(
                r'<span class="programme__subtitle.+?property="name">(.*?)</span>(.*?property="name">(.*?)</span>)?',
                programme)
            if subtitle_match:
                series = subtitle_match.group(1)
                episode = subtitle_match.group(3)
                if episode:
                    subtitle = "(%s, %s)" % (series, episode)
                else:
                    if series.strip():
                        subtitle = "(%s)" % series

            image = ''
            image_match = re.search(
                r'<meta property="image" content="(.+?)" />', programme)
            if image_match:
                image = image_match.group(1)

            synopsis = ''
            synopsis_match = re.search(
                r'<span property="description">(.+?)</span>', programme)
            if synopsis_match:
                synopsis = synopsis_match.group(1)

            station = ''
            station_match = re.search(
                r'<p class="programme__service.+?<strong>(.+?)</strong>.*?</p>',
                programme)
            if station_match:
                station = station_match.group(1).strip()

            series_title = "[B]%s - %s[/B]" % (station, name)
            if just_episodes:
                title = "[B]%s[/B] - %s" % (masthead_title, name)
            else:
                title = "[B]%s[/B] - %s %s" % (station, name, subtitle)

            if series_id:
                AddMenuEntry(series_title, series_id, 131, image, synopsis, '')
            elif programme_id:  #TODO maybe they are not always mutually exclusive

                url = "http://www.bbc.co.uk/programmes/%s" % programme_id
                CheckAutoplay(title, url, image, ' ', '')

            percent = int(100 * (page + list_item_num / len(programmes)) /
                          total_pages)
            pDialog.update(percent, translation(30319), name)

            list_item_num += 1

        percent = int(100 * page / total_pages)
        pDialog.update(percent, translation(30319))

    if int(ADDON.getSetting('radio_paginate_episodes')) == 0:
        if current_page < next_page:
            page_url = 'http://www.bbc.co.uk' + page_base_url + str(next_page)
            AddMenuEntry(" [COLOR ffffa500]%s >>[/COLOR]" % translation(30320),
                         page_url, 136, '', '', '')

    #BUG: this should sort by original order but it doesn't (see http://trac.kodi.tv/ticket/10252)
    xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_UNSORTED)
    xbmcplugin.addSortMethod(int(sys.argv[1]),
                             xbmcplugin.SORT_METHOD_VIDEO_TITLE)

    pDialog.close()
Пример #57
0
def listar_busquedas(params, url="", category=""):
    import xbmc
    import xbmcgui
    import xbmcplugin

    from platformcode.xbmc import xbmctools
    #print "category :" +category
    if url == "" and category == "":
        channel_preset = params.channel
        accion = params.action
        category = "Buscador_Generico"
    else:
        channel_preset = params.get("channel")
        accion = params.get("action")
        category = "Buscador_Normal"
    #print "listar_busquedas()"
    channel2 = ""
    itemlist = []
    # Despliega las busquedas anteriormente guardadas
    try:
        presets = config.get_setting("presets_buscados")

        if channel_preset != CHANNELNAME:
            channel2 = channel_preset
        logger.info("channel_preset :%s" % channel_preset)

        matches = ""
        if "|" in presets:
            matches = presets.split("|")
            itemlist.append(
                Item(channel="buscador",
                     action="por_teclado",
                     title=config.get_localized_string(30103) + "...",
                     url=matches[0],
                     thumbnail="",
                     plot=channel2,
                     category=category,
                     context=1))
            #addfolder( "buscador"   , config.get_localized_string(30103)+"..." , matches[0] , "por_teclado", channel2 ) # Buscar
        else:
            itemlist.append(
                Item(channel="buscador",
                     action="por_teclado",
                     title=config.get_localized_string(30103) + "...",
                     url="",
                     thumbnail="",
                     plot=channel2,
                     category=category,
                     context=0))
            #addfolder( "buscador"   , config.get_localized_string(30103)+"..." , "" , "por_teclado", channel2 )
        if len(matches) > 0:
            for match in matches:

                title = scrapedurl = match
                itemlist.append(
                    Item(channel=channel_preset,
                         action="searchresults",
                         title=title,
                         url=scrapedurl,
                         thumbnail="",
                         plot="",
                         category=category,
                         context=1))
                #addfolder( channel_preset , title , scrapedurl , "searchresults" )
        elif presets != "":

            title = scrapedurl = presets
            itemlist.append(
                Item(channel=channel_preset,
                     action="searchresults",
                     title=title,
                     url=scrapedurl,
                     thumbnail="",
                     plot="",
                     category=category,
                     context=1))
            #addfolder( channel_preset , title , scrapedurl , "searchresults" )
    except:
        itemlist.append(
            Item(channel="buscador",
                 action="por_teclado",
                 title=config.get_localized_string(30103) + "...",
                 url="",
                 thumbnail="",
                 plot=channel2,
                 category=category,
                 context=0))
    #addfolder( "buscador"   , config.get_localized_string(30103)+"..." , "" , "por_teclado" , channel2 )

    if url == "" and category == "Buscador_Generico":

        return itemlist
    else:
        for item in itemlist:
            channel = item.channel
            action = item.action
            category = category
            scrapedtitle = item.title
            scrapedurl = item.url
            scrapedthumbnail = item.thumbnail
            scrapedplot = item.plot
            extra = item.extra
            context = item.context
            xbmctools.addnewfolderextra(channel,
                                        action,
                                        category,
                                        scrapedtitle,
                                        scrapedurl,
                                        scrapedthumbnail,
                                        scrapedplot,
                                        extradata=extra,
                                        context=context)

        # Cierra el directorio
        xbmcplugin.setPluginCategory(handle=int(sys.argv[1]),
                                     category=category)
        xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                                 sortMethod=xbmcplugin.SORT_METHOD_NONE)
        xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=True)
Пример #58
0
def render_items(itemlist, parent_item):
    """
    Función encargada de mostrar el itemlist en kodi, se pasa como parametros el itemlist y el item del que procede
    @type itemlist: list
    @param itemlist: lista de elementos a mostrar

    @type parent_item: item
    @param parent_item: elemento padre
    """
    # Si el itemlist no es un list salimos
    if not type(itemlist) == list:
        if config.get_platform() == "boxee":
            xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=True)
        return

    # Si no hay ningun item, mostramos un aviso
    if not len(itemlist):
        itemlist.append(Item(title="Non ci sono elementi da visualizzare"))

    # Recorremos el itemlist
    for item in itemlist:
        # logger.debug(item)
        # Si el item no contiene categoria, le ponemos la del item padre
        if item.category == "":
            item.category = parent_item.category

        # Si el item no contiene fanart, le ponemos el del item padre
        if item.fanart == "":
            item.fanart = parent_item.fanart

        # Formatear titulo
        if item.text_color:
            item.title = '[COLOR %s]%s[/COLOR]' % (item.text_color, item.title)
        if item.text_blod:
            item.title = '[B]%s[/B]' % item.title
        if item.text_italic:
            item.title = '[I]%s[/I]' % item.title

        # Añade headers a las imagenes si estan en un servidor con cloudflare
        from core import httptools
        item.thumbnail = httptools.get_url_headers(item.thumbnail)
        item.fanart = httptools.get_url_headers(item.fanart)

        # IconImage para folder y video
        if item.folder:
            icon_image = "DefaultFolder.png"
        else:
            icon_image = "DefaultVideo.png"

        # Creamos el listitem
        listitem = xbmcgui.ListItem(item.title,
                                    iconImage=icon_image,
                                    thumbnailImage=item.thumbnail)

        # Ponemos el fanart
        if item.fanart:
            listitem.setProperty('fanart_image', item.fanart)
        else:
            listitem.setProperty(
                'fanart_image',
                os.path.join(config.get_runtime_path(), "fanart.jpg"))

        # TODO: ¿Se puede eliminar esta linea? yo no he visto que haga ningun efecto.
        xbmcplugin.setPluginFanart(
            int(sys.argv[1]),
            os.path.join(config.get_runtime_path(), "fanart.jpg"))

        # Añadimos los infoLabels
        set_infolabels(listitem, item)

        # Montamos el menu contextual
        context_commands = set_context_commands(item, parent_item)

        # Añadimos el item
        if config.get_platform() == "boxee":
            xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),
                                        url='%s?%s' %
                                        (sys.argv[0], item.tourl()),
                                        listitem=listitem,
                                        isFolder=item.folder)
        else:
            listitem.addContextMenuItems(context_commands, replaceItems=True)

            if not item.totalItems:
                item.totalItems = 0
            xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),
                                        url='%s?%s' %
                                        (sys.argv[0], item.tourl()),
                                        listitem=listitem,
                                        isFolder=item.folder,
                                        totalItems=item.totalItems)

    # Fijar los tipos de vistas...
    if config.get_setting("forceview") == True:
        # ...forzamos segun el viewcontent
        xbmcplugin.setContent(int(sys.argv[1]), parent_item.viewcontent)
        # logger.debug(parent_item)
    elif parent_item.channel not in ["channelselector", ""]:
        # ... o segun el canal
        xbmcplugin.setContent(int(sys.argv[1]), "movies")

    # Fijamos el "breadcrumb"
    xbmcplugin.setPluginCategory(handle=int(sys.argv[1]),
                                 category=parent_item.category.capitalize())

    # No ordenar items
    xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                             sortMethod=xbmcplugin.SORT_METHOD_NONE)

    # Cerramos el directorio
    xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=True)

    # Fijar la vista
    if config.get_setting("forceview") == True:
        viewmode_id = get_viewmode_id(parent_item)
        xbmc.executebuiltin("Container.SetViewMode(%s)" % viewmode_id)
Пример #59
0
def run(url_suffix=""):
    if not os.path.exists(os.path.join(ADDON_PATH, ".firstrun")):
        notify(getLocalizedString(30101))
        system_information()
        return

    donatePath = os.path.join(ADDON_PATH, ".donate")
    if not os.path.exists(donatePath):
        with open(donatePath, "w"):
            os.utime(donatePath, None)
        dialog = xbmcgui.Dialog()
        dialog.ok("Quasar", getLocalizedString(30141))

    socket.setdefaulttimeout(int(ADDON.getSetting("buffer_timeout")))
    urllib2.install_opener(urllib2.build_opener(NoRedirectHandler()))

    # Pause currently playing Quasar file to avoid doubling requests
    if xbmc.Player().isPlaying() and ADDON_ID in xbmc.Player().getPlayingFile(
    ):
        xbmc.Player().pause()

    url = sys.argv[0].replace("plugin://%s" % ADDON_ID,
                              QUASARD_HOST + url_suffix) + sys.argv[2]
    log.debug("Requesting %s from %s" % (url, repr(sys.argv)))

    try:
        data = _json(url)
    except urllib2.URLError as e:
        if 'Connection refused' in e.reason:
            notify(getLocalizedString(30116), time=7000)
        else:
            import traceback
            map(log.error, traceback.format_exc().split("\n"))
            notify(e.reason, time=7000)
        return
    except Exception as e:
        import traceback
        map(log.error, traceback.format_exc().split("\n"))
        try:
            msg = unicode(e)
        except:
            try:
                msg = str(e)
            except:
                msg = repr(e)
        notify(getLocalizedLabel(msg), time=7000)
        return

    if not data:
        return

    if data["content_type"]:
        content_type = data["content_type"]
        if data["content_type"].startswith("menus"):
            content_type = data["content_type"].split("_")[1]

        xbmcplugin.addSortMethod(HANDLE, xbmcplugin.SORT_METHOD_UNSORTED)
        if content_type != "tvshows":
            xbmcplugin.addSortMethod(HANDLE,
                                     xbmcplugin.SORT_METHOD_LABEL_IGNORE_THE)
        xbmcplugin.addSortMethod(HANDLE, xbmcplugin.SORT_METHOD_DATE)
        xbmcplugin.addSortMethod(HANDLE, xbmcplugin.SORT_METHOD_GENRE)
        xbmcplugin.setContent(HANDLE, content_type)

    listitems = range(len(data["items"]))
    for i, item in enumerate(data["items"]):
        # Translate labels
        if item["label"][0:8] == "LOCALIZE":
            item["label"] = unicode(getLocalizedLabel(item["label"]), 'utf-8')
        if item["label2"][0:8] == "LOCALIZE":
            item["label2"] = getLocalizedLabel(item["label2"])

        listItem = xbmcgui.ListItem(label=item["label"],
                                    label2=item["label2"],
                                    iconImage=item["icon"],
                                    thumbnailImage=item["thumbnail"])
        if item.get("info"):
            listItem.setInfo("video", item["info"])
        if item.get("stream_info"):
            for type_, values in item["stream_info"].items():
                listItem.addStreamInfo(type_, values)
        if item.get("art"):
            listItem.setArt(item["art"])
        elif ADDON.getSetting(
                'default_fanart') == 'true' and item["label"] != unicode(
                    getLocalizedString(30218), 'utf-8'):
            fanart = os.path.join(ADDON_PATH, "fanart.jpg")
            listItem.setArt({'fanart': fanart})
        if item.get("context_menu"):
            # Translate context menus
            for m, menu in enumerate(item["context_menu"]):
                if menu[0][0:8] == "LOCALIZE":
                    menu[0] = getLocalizedLabel(menu[0])
            listItem.addContextMenuItems(item["context_menu"])
        listItem.setProperty("isPlayable", item["is_playable"] and "true"
                             or "false")
        if item.get("properties"):
            for k, v in item["properties"].items():
                listItem.setProperty(k, v)
        listitems[i] = (item["path"], listItem, not item["is_playable"])

    xbmcplugin.addDirectoryItems(HANDLE, listitems, totalItems=len(listitems))

    # Set ViewMode
    if data["content_type"]:
        viewMode = ADDON.getSetting("viewmode_%s" % data["content_type"])
        if viewMode:
            try:
                xbmc.executebuiltin('Container.SetViewMode(%s)' % viewMode)
            except Exception as e:
                log.warning("Unable to SetViewMode(%s): %s" %
                            (viewMode, repr(e)))

    xbmcplugin.endOfDirectory(HANDLE,
                              succeeded=True,
                              updateListing=False,
                              cacheToDisc=True)
Пример #60
0
def listvideos(params, url, category):
    logger.info("[discoverymx.py] listvideos")

    scrapedthumbnail = ""
    scrapedplot = ""
    # Descarga la página
    data = scrapertools.cachePage(url)
    #logger.info(data)

    # Extrae las entradas (carpetas)
    patronvideos = '<h3 class="entry-title"><a href="([^"]+)"[^>]+>([^<]+)</a></h3>.*?'
    patronvideos += '<div class="entry-content">(.*?)</div> <!-- #post-ID -->'

    matches = re.compile(patronvideos, re.DOTALL).findall(data)
    scrapertools.printMatches(matches)

    for match in matches:
        scrapedtitle = match[1]
        scrapedtitle = re.sub("<[^>]+>", " ", scrapedtitle)
        scrapedtitle = scrapedtitle.replace("&#8211;", "-")
        scrapedtitle = scrapedtitle.replace("&nbsp;", " ")
        scrapedtitle = scrapedtitle.replace("&amp;;", "&")
        scrapedurl = match[0]
        regexp = re.compile(r'src="([^"]+)"')
        matchthumb = regexp.search(match[2])
        if matchthumb is not None:
            scrapedthumbnail = matchthumb.group(1)
        scrapedplot = match[2]
        scrapedplot = re.sub("<[^>]+>", " ", scrapedplot)
        scrapedplot = scrapedplot.replace("&#215;", "*")
        scrapedplot = scrapedplot.replace("&amp;", "&")
        scrapedplot = scrapedplot.replace("&#8211;", "-")
        scrapedplot = scrapedplot.replace("\n", "")
        scrapedplot = scrapedplot.replace("\t", "")
        scrapedplot = scrapedplot.replace("\:\:", "")
        scrapedplot = scrapedplot.replace("…", "")
        scrapedplot = scrapedplot.replace("Uploading", "")
        scrapedplot = scrapedplot.replace("DepositFiles", "")
        scrapedplot = scrapedplot.replace("HotFile", "")
        #scrapedplot = scrapedplot.replace("…","")
        if (DEBUG):
            logger.info("title=[" + scrapedtitle + "], url=[" + scrapedurl +
                        "], thumbnail=[" + scrapedthumbnail + "]")

        # Añade al listado de XBMC
        xbmctools.addnewfolder(CHANNELNAME, "detail", category, scrapedtitle,
                               scrapedurl, scrapedthumbnail, scrapedplot)

    # Extrae la marca de siguiente página
    patronvideos = '<div class="left"><a href="([^"]+)" ><span>&laquo;</span> Entradas Anteriores</a></div>'
    matches = re.compile(patronvideos, re.DOTALL).findall(data)
    scrapertools.printMatches(matches)

    if len(matches) > 0:
        scrapedtitle = "Página siguiente"
        scrapedurl = urlparse.urljoin(url, matches[0])
        scrapedthumbnail = ""
        scrapedplot = ""
        xbmctools.addnewfolder(CHANNELNAME, "listvideos", category,
                               scrapedtitle, scrapedurl, scrapedthumbnail,
                               scrapedplot)

    # Propiedades
    xbmcplugin.setPluginCategory(handle=int(sys.argv[1]), category=category)
    xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                             sortMethod=xbmcplugin.SORT_METHOD_NONE)
    xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=True)