Advertisement
Guest User

Fixed buscador WiiMC

a guest
Aug 13th, 2012
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 21.57 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. #------------------------------------------------------------
  3. # pelisalacarta
  4. # Launcher
  5. # http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
  6. #------------------------------------------------------------
  7. import urllib
  8. import base64
  9. import os
  10. import binascii
  11. import md5
  12.  
  13. from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
  14.  
  15. from core import config
  16. from core import wiideoteca
  17. from core.item import Item
  18.  
  19. import logging.config
  20. import logging
  21. logging_conf = os.path.join( os.path.dirname(__file__) , ".." , ".." , "logging.conf")
  22. print "logging_conf=",logging_conf
  23. logging.config.fileConfig( logging_conf )
  24. logger=logging.getLogger("wiimc")
  25.  
  26. #TODO: Pasar esto a ¿config?
  27. VERSIONTAG = "3.2.18"
  28.  
  29. #from lib import cerealizer
  30. #cerealizer.register(Item)
  31.  
  32. def get_content_type():
  33.     return "text/plain"
  34.  
  35. def controller(plugin_name,port,host,path,headers):
  36.  
  37.     respuesta = ""
  38.  
  39.     respuesta += "version=7\n"
  40.     respuesta += "logo=http://pelisalacarta.mimediacenter.info/icon.png\n"
  41.     respuesta += "title="+plugin_name+" "+VERSIONTAG+" (WiiMC)\n"
  42.     respuesta += "\n"
  43.  
  44.     if path == "/wiimc/" or path=="/wiimc":
  45.         import channelselector
  46.         channelslist = channelselector.getmainlist()
  47.  
  48.         # Actualización automática de canales, actualiza la lista
  49.         if config.get_setting("updatechannels")=="true":
  50.             logger.info("Verificando actualización del channelselector")
  51.             try:
  52.                 from core import updater
  53.                 actualizado = updater.updatechannel("channelselector")
  54.  
  55.                 if actualizado:
  56.                     respuesta += "type=playlist\n"
  57.                     respuesta += "name=¡Lista de canales actualizada!\n"
  58.                     respuesta += "thumb=\n"
  59.                     respuesta += "URL=http://"+host+"/wiimc/\n"
  60.                     respuesta += "\n"
  61.             except:
  62.                 import sys
  63.                 for line in sys.exc_info():
  64.                     logger.error( "%s" % line )
  65.  
  66.         for channel in channelslist:
  67.  
  68.             # Quita el canal de ayuda y el de configuración, no sirven en WiiMC
  69.             if channel.channel!="configuracion" and channel.channel!="ayuda":
  70.                
  71.                 if channel.channel!="buscador":
  72.                     respuesta += "type=playlist\n"
  73.                 else:
  74.                     respuesta += "type=search\n"
  75.                 respuesta += "name="+channel.title+"\n"
  76.                 respuesta += "thumb=http://"+plugin_name+".mimediacenter.info/wiimc/"+channel.channel+".png\n"
  77.                 respuesta += "URL=http://"+host+"/wiimc/"+base64.b64encode(channel.serialize()).replace("/","%2F")+"/playlist.plx\n"
  78.                 respuesta += "\n"
  79.     else:
  80.        
  81.         item = extract_item_from_url(path)
  82.    
  83.         if item.channel=="channelselector" and item.action=="channeltypes":
  84.            
  85.             import channelselector
  86.             channelslist = channelselector.getchanneltypes()
  87.            
  88.             for channel in channelslist:
  89.                 respuesta += "type=playlist\n"
  90.                 respuesta += "name="+channel.title+"\n"
  91.                 respuesta += "thumb=http://"+plugin_name+".mimediacenter.info/wiimc/"+channel.channel+".png\n"
  92.                 respuesta += "URL=http://"+host+"/wiimc/"+base64.b64encode(channel.serialize()).replace("/","%2F")+"/playlist.plx\n"
  93.                 respuesta += "\n"
  94.        
  95.         elif item.channel=="channelselector" and item.action=="listchannels":
  96.            
  97.             import channelselector
  98.             channelslist = channelselector.filterchannels(item.category)
  99.            
  100.             for channel in channelslist:
  101.                 if channel.type=="generic" or channel.type=="wiimc":
  102.                     channel.action="mainlist"
  103.                     respuesta += "type=playlist\n"
  104.                     respuesta += "name="+channel.title+"\n"
  105.                     respuesta += "thumb=http://"+plugin_name+".mimediacenter.info/wiimc/"+channel.channel+".png\n"
  106.                     respuesta += "URL=http://"+host+"/wiimc/"+base64.b64encode(channel.serialize()).replace("/","%2F")+"/playlist.plx\n"
  107.                     respuesta += "\n"
  108.    
  109.         else:
  110.             itemlist,channel = getitems(item,path)
  111.            
  112.             # Las listas vacías son problemáticas, añade un elemento dummy
  113.             if len(itemlist)==0:
  114.                 itemlist.append( Item(title="(No hay elementos)") )
  115.            
  116.             for item in itemlist:
  117.                 if item.action=="search":
  118.                     if item.server=="": item.server="none"
  119.                     if item.url=="": item.url="none"
  120.                     url = "http://%s/%s/playlist.plx" % ( host+"/wiimc" , base64.b64encode( item.serialize() ).replace("/","%2F") )
  121.                     respuesta += "type=search\n"
  122.                     respuesta += "name=%s\n" % item.title
  123.                     if item.thumbnail != "":
  124.                         respuesta += "thumb=%s\n" % item.thumbnail
  125.                     respuesta += "URL=%s\n" % url
  126.                     respuesta += "\n"
  127.                     logger.info("  Buscador "+url)
  128.      
  129.                 elif item.folder or item.action=="play" or item.action=="downloadall":
  130.                     if item.server=="": item.server="none"
  131.                     if item.url=="": item.url="none"
  132.                     if item.title=="": item.title="Ver el video-"
  133.  
  134.                     url = "http://%s/%s/playlist.plx" % ( host+"/wiimc" , base64.b64encode( item.serialize() ).replace("/","%2F") )
  135.                     respuesta += "type=playlist\n"
  136.                     respuesta += "name=%s\n" % item.title
  137.                     if item.thumbnail != "":
  138.                         respuesta += "thumb=%s\n" % item.thumbnail
  139.                     respuesta += "URL=%s\n" % url
  140.                     respuesta += "\n"
  141.                     logger.info("  Nivel intermedio "+url)
  142.                 else:
  143.                     respuesta += "type=video\n"
  144.                     respuesta += "name=%s\n" % item.title
  145.                     respuesta += "URL=%s\n" % item.url
  146.                     respuesta += "\n"
  147.                     logger.info("  Video "+item.url)
  148.  
  149.     return respuesta
  150.  
  151. def extract_item_from_url(requestpath):
  152.     logger.info("extract_item_from_url()")
  153.     # La ruta empleada en la petición
  154.     ruta = requestpath.split("?")[0]
  155.     logger.info("ruta="+ruta)
  156.  
  157.     # El item serializado está codificado en base64
  158.     itemserializado = ruta.split("/")[2]
  159.     itemserializado = itemserializado.replace("%2F","/")
  160.     itemserializado = itemserializado.replace("%2f","/")
  161.     logger.info("item base64="+itemserializado)
  162.     import base64
  163.     item = Item()
  164.     item.deserialize(base64.b64decode(itemserializado))
  165.     logger.info("item: channel="+item.channel+", action="+item.action+", title="+item.title+", url="+item.url+", server="+item.server+", category="+item.category)
  166.  
  167.     return item
  168.  
  169. def getitems(item,requestpath):
  170.     logger.info("getitems")
  171.     itemlist = []
  172.    
  173.     # Extrae los parámetros
  174.     channel = item.channel
  175.     accion = item.action
  176.     url = item.url
  177.     if url!="none":
  178.         if not "filenium" in url:
  179.             url = urllib.unquote_plus(url)
  180.     server = item.server
  181.     title = item.title
  182.     extra = item.extra
  183.     category = item.category
  184.     fulltitle = item.fulltitle
  185.  
  186.     try:
  187.         if accion=="mainlist" and config.get_setting("updatechannels")=="true":
  188.             try:
  189.                 logger.info("Verificando actualización del canal")
  190.                 from core import updater
  191.                 actualizado = updater.updatechannel(channel)
  192.        
  193.                 if actualizado:
  194.                     itemlist.append( Item(title="¡Canal descargado y actualizado!") )
  195.             except:
  196.                 import sys
  197.                 for line in sys.exc_info():
  198.                     logger.error( "%s" % line )
  199.    
  200.         '''
  201.        # Obtiene un nombre válido para la cache
  202.        hashed_url = binascii.hexlify(md5.new(requestpath).digest())
  203.        cached_file = os.path.join( config.get_data_path() , "tmp" , "cache" , hashed_url )
  204.        logger.info( "Cache file must be "+cached_file )
  205.        
  206.        # Si el fichero está en cache
  207.        if os.path.exists(cached_file):
  208.            logger.info( "Reading from cache" )
  209.            fichero = open( cached_file ,"rb")
  210.            itemlist = cerealizer.load(fichero)
  211.            fichero.close()
  212.            
  213.        # Si no está en cache
  214.        else:
  215.        '''
  216.         logger.info( "Not cached" )
  217.    
  218.         # El item que invocó es importante para obtener el siguiente
  219.         senderitem = Item( title=title , channel=channel, action=accion, url=url , server=server, extra=extra, category=category, fulltitle=fulltitle )
  220.         if "|" in url:
  221.             partes = urllib.unquote_plus(senderitem.url).split("|")
  222.             refered_item = Item(title=partes[0],url=partes[2],thumbnail="",server=partes[1],plot="",extra=partes[3])
  223.             logger.info( "refered_item title="+refered_item.title+", url="+refered_item.url+", server="+refered_item.server+", extra="+refered_item.extra)
  224.    
  225.         else:
  226.             refered_item = Item()
  227.    
  228.         # Importa el canal y ejecuta la función
  229.         try:
  230.             exec "from pelisalacarta.channels import "+channel+" as channelmodule"
  231.         except:
  232.             import sys
  233.             for line in sys.exc_info():
  234.                 logger.error( "%s" % line )
  235.             try:
  236.                 exec "from pelisalacarta import "+channel+" as channelmodule"
  237.             except:
  238.                 import sys
  239.                 for line in sys.exc_info():
  240.                     logger.error( "%s" % line )
  241.                 try:
  242.                     exec "from core import "+channel+" as channelmodule"
  243.                 except:
  244.                     pass
  245.    
  246.         # play - es el menú de reproducción de un vídeo
  247.         if accion=="play":
  248.             logger.info("ACCION PLAY")
  249.             if hasattr(channelmodule, 'play'):
  250.                 logger.info("[launcher.py] executing channel 'play' method")
  251.                 logger.info(channelmodule.__file__)
  252.                 itemlist = channelmodule.play(senderitem)
  253.                 logger.info("itemlist"+str(itemlist))
  254.                 senderitem = itemlist[0]
  255.                 senderitem.folder=False
  256.             else:
  257.                 logger.info("[launcher.py] no channel 'play' method, executing core method")
  258.             itemlist = menu_video(senderitem)
  259.    
  260.         # play_video - genera una playlist con una sola entrada para que wiimc la reproduzca
  261.         elif accion=="play_video":
  262.             logger.info("ACCION PLAY_VIDEO")
  263.             logger.info("url="+senderitem.url)
  264.             senderitem.folder=False
  265.             itemlist.append( senderitem )
  266.    
  267.         # search - es el buscador
  268.         elif channel=="buscador" and accion=="mainlist":
  269.             logger.info("ACCION SEARCH (buscador)")
  270.             texto = requestpath.split("plx")[1]
  271.             exec "itemlist = buscador.do_search_results(texto)"
  272.            
  273.         elif accion=="search":
  274.             logger.info("ACCION SEARCH")
  275.             texto = requestpath.split("plx")[1]
  276.             exec "itemlist = channelmodule."+accion+"(senderitem,texto)"
  277.    
  278.         # findvideos - debe encontrar videos reproducibles
  279.         elif accion=="findvideos":
  280.             logger.info("ACCION FINDVIDEOS")
  281.             try:
  282.                 exec "itemlist = channelmodule."+accion+"(senderitem)"
  283.             except:
  284.                 import sys
  285.                 for line in sys.exc_info():
  286.                     logger.error( "%s" % line )
  287.                 itemlist = findvideos(senderitem,channel)
  288.        
  289.         elif accion=="descargar":
  290.             itemlist = download_item(senderitem,refered_item)
  291.         elif accion=="download_all":
  292.             itemlist = download_all(senderitem,refered_item)
  293.         elif accion=="add_to_favorites":
  294.             itemlist = add_to_favorites(senderitem,refered_item)
  295.         elif accion=="remove_from_favorites":
  296.             itemlist = remove_from_favorites(senderitem,refered_item)
  297.         elif accion=="add_to_downloads":
  298.             itemlist = add_to_downloads(senderitem,refered_item)
  299.         elif accion=="remove_from_downloads":
  300.             itemlist = remove_from_downloads(senderitem,refered_item)
  301.    
  302.         elif accion=="remove_from_error_downloads":
  303.             itemlist = remove_from_error_downloads(senderitem,refered_item)
  304.         elif accion=="add_again_to_downloads":
  305.             itemlist = add_again_to_downloads(senderitem,refered_item)
  306.         elif accion=="send_to_jdownloader":
  307.             itemlist = send_to_jdownloader(senderitem,refered_item)
  308.         elif accion=="search_trailer":
  309.             itemlist = search_trailer(senderitem,refered_item)
  310.         elif accion=="add_serie_to_wiideoteca":
  311.             itemlist = wiideoteca.AgregarSerie(senderitem)
  312.         elif accion=="UltimoVisto":
  313.             itemlist = wiideoteca.UltimoVisto(senderitem)
  314.    
  315.         else:
  316.             if senderitem.url=="none":
  317.                 senderitem.url=""
  318.             exec "itemlist.extend( channelmodule."+accion+"(senderitem) )"
  319.        
  320.         '''
  321.        # Lo almacena en cache
  322.        fichero = open( cached_file ,"wb")
  323.        cerealizer.dump(itemlist,fichero)
  324.        fichero.close()
  325.        '''
  326.    
  327.         logger.info("Items devueltos ")
  328.         for item in itemlist:
  329.             logger.info( " " + item.title + " | " + item.url + " | " + item.action)
  330.     except:
  331.         import traceback,sys
  332.         from pprint import pprint
  333.         exc_type, exc_value, exc_tb = sys.exc_info()
  334.         lines = traceback.format_exception(exc_type, exc_value, exc_tb)
  335.         for line in lines:
  336.             line_splits = line.split("\n")
  337.             for line_split in line_splits:
  338.                 logger.error(line_split)
  339.  
  340.     return itemlist,channel
  341.  
  342. def download_item(senderitem,refered_item):
  343.     itemlist = []
  344.  
  345.     # Extrae todos los enlaces posibles
  346.     exec "from servers import "+refered_item.server+" as server_connector"
  347.     video_urls = server_connector.get_video_url( page_url=refered_item.url , premium=(config.get_setting("megavideopremium")=="true") , user=config.get_setting("megavideouser") , password=config.get_setting("megavideopassword") )
  348.  
  349.     if len(video_urls)>0:
  350.         from core import downloadtools
  351.         titulo = senderitem.fulltitle
  352.         if titulo=="": titulo=refered_item.title
  353.         downloadtools.downloadtitle(video_urls[len(video_urls)-1][1],titulo)
  354.         itemlist.append( Item( title="Descarga finalizada" ) )
  355.     else:
  356.         itemlist.append( Item( title="El video ya no está disponible" ) )
  357.    
  358.     return itemlist
  359.  
  360. def send_to_jdownloader(senderitem,refered_item):
  361.     itemlist = []
  362.     itemlist.append( Item( title="Opcion no disponible" ) )
  363.  
  364.     return itemlist
  365.  
  366. def search_trailer(senderitem,refered_item):
  367.     itemlist = []
  368.     itemlist.append( Item( title="Opcion no disponible" ) )
  369.  
  370.     return itemlist
  371.  
  372. def add_to_favorites(senderitem,refered_item):
  373.     from core import favoritos
  374.     favoritos.savebookmark(titulo=refered_item.title,url=refered_item.url,thumbnail="",server=refered_item.server,fulltitle=senderitem.fulltitle,plot="")
  375.  
  376.     itemlist = []
  377.     itemlist.append( Item( title="El video %s" % senderitem.fulltitle ) )
  378.     itemlist.append( Item( title="ha sido añadido a favoritos" ) )
  379.    
  380.     return itemlist
  381.  
  382. def remove_from_favorites(senderitem,refered_item):
  383.     from core import favoritos
  384.     favoritos.deletebookmark(refered_item.extra)
  385.    
  386.     itemlist = []
  387.     itemlist.append( Item( title="El video %s" % refered_item.title ) )
  388.     itemlist.append( Item( title="ha sido eliminado de favoritos" ) )
  389.    
  390.     return itemlist
  391.  
  392. def download_all(senderitem,refered_item):
  393.     from core import descargas
  394.     descargas.downloadall(senderitem)
  395.    
  396.     itemlist = []
  397.     itemlist.append( Item( title="Fin de todas las descargas pendientes" ) )
  398.    
  399.     return itemlist
  400.  
  401. def add_to_downloads(senderitem,refered_item):
  402.     from core import descargas
  403.     descargas.savebookmark(titulo=refered_item.title,url=refered_item.url,thumbnail="",server=refered_item.server,plot="")
  404.    
  405.     itemlist = []
  406.     itemlist.append( Item( title="El video %s" % refered_item.title ) )
  407.     itemlist.append( Item( title="ha sido añadido a la lista" ) )
  408.     itemlist.append( Item( title="de descargas" ) )
  409.    
  410.     return itemlist
  411.  
  412. def remove_from_downloads(senderitem,refered_item):
  413.     from core import descargas
  414.     descargas.deletebookmark(refered_item.extra)
  415.    
  416.     itemlist = []
  417.     itemlist.append( Item( title="El video %s" % refered_item.title ) )
  418.     itemlist.append( Item( title="ha sido eliminado de la lista" ) )
  419.     itemlist.append( Item( title="de descargas" ) )
  420.    
  421.     return itemlist
  422.  
  423. def remove_from_error_downloads(senderitem,refered_item):
  424.     from core import descargas
  425.     descargas.delete_error_bookmark(refered_item.extra)
  426.    
  427.     itemlist = []
  428.     itemlist.append( Item( title="El video %s" % refered_item.title ) )
  429.     itemlist.append( Item( title="ha sido eliminado definitivamente" ) )
  430.    
  431.     return itemlist
  432.  
  433. def add_again_to_downloads(senderitem,refered_item):
  434.     from core import descargas
  435.     descargas.mover_descarga_error_a_pendiente(refered_item.extra)
  436.    
  437.     itemlist = []
  438.     itemlist.append( Item( title="El video %s" % refered_item.title ) )
  439.     itemlist.append( Item( title="ha sido movido a la lista" ) )
  440.     itemlist.append( Item( title="de descargas de nuevo" ) )
  441.    
  442.     return itemlist
  443.  
  444. def menu_video(item):
  445.     itemlist = []
  446.     logger.info("menu_video item=[url="+item.url+", server="+item.server+", fulltitle="+item.fulltitle+"]")
  447.  
  448.     from servers import servertools
  449.     video_urls,puede,motivo = servertools.resolve_video_urls_for_playing( item.server , item.url , video_password="" , muestra_dialogo=False)
  450.  
  451.     if puede:
  452.         for video_url in video_urls:
  453.             itemlist.append( Item(channel=item.channel, title="Ver "+video_url[0], url=video_url[1], action="play_video") )
  454.        
  455.         refered_item_encoded = urllib.quote(item.title.replace("|","-"))+"|"+urllib.quote(item.server)+"|"+urllib.quote(item.url)+"|"+urllib.quote(item.extra)
  456.        
  457.         itemlist.append( Item(channel=item.channel, title="Descargar",action="descargar",url=refered_item_encoded,fulltitle=urllib.quote(item.fulltitle) ) )
  458.        
  459.         if item.channel!="favoritos":
  460.             itemlist.append( Item(channel=item.channel, title="Añadir a favoritos",action="add_to_favorites",url=refered_item_encoded,fulltitle=urllib.quote(item.fulltitle) ) )
  461.         else:
  462.             itemlist.append( Item(channel=item.channel, title="Quitar de favoritos",action="remove_from_favorites",url=refered_item_encoded,fulltitle=urllib.quote(item.fulltitle) ) )
  463.        
  464.         if item.channel!="descargas":
  465.             itemlist.append( Item(channel=item.channel, title="Añadir a la lista de descargas",action="add_to_downloads",url=refered_item_encoded,fulltitle=urllib.quote(item.fulltitle) ) )
  466.         else:
  467.             if item.category=="errores":
  468.                 itemlist.append( Item(channel=item.channel, title="Quitar definitivamente de la lista de descargas",action="remove_from_error_downloads",url=refered_item_encoded ) )
  469.                 itemlist.append( Item(channel=item.channel, title="Pasar de nuevo a la lista de descargas",action="add_again_to_downloads",url=refered_item_encoded ) )
  470.             else:
  471.                 itemlist.append( Item(channel=item.channel, title="Quitar de la lista de descargas",action="remove_from_downloads",url=refered_item_encoded ) )
  472.    
  473.         itemlist.append( Item(channel=item.channel, title="Enviar a jdownloader",action="send_to_jdownloader",url=refered_item_encoded ) )
  474.         itemlist.append( Item(channel=item.channel, title="Buscar trailer",action="search_trailer",url=refered_item_encoded ) )
  475.         if item.category=="wiideoteca":
  476.             itemlist.append( Item(channel=item.channel, title="Marcar como Ultimo Episodio Visto",action="UltimoVisto",url=item.extra,fulltitle=item.fulltitle ) )
  477.  
  478.     # Si no puedes ver el vídeo te informa
  479.     else:
  480.         itemlist.append( Item(title="No puedes ver ese vídeo porque...") )
  481.         if item.server!="":
  482.             if "<br/>" in motivo:
  483.                 itemlist.append( Item(title=motivo.split("<br/>")[0]) )
  484.                 itemlist.append( Item(title=motivo.split("<br/>")[1]) )
  485.                 itemlist.append( Item(title=item.url) )
  486.             else:
  487.                 itemlist.append( Item(title=motivo) )
  488.                 itemlist.append( Item(title=item.url) )
  489.         else:
  490.             itemlist.append( Item(title="El servidor donde está alojado no está") )
  491.             itemlist.append( Item(title="soportado en pelisalacarta todavía") )
  492.             itemlist.append( Item(title=item.url) )
  493.  
  494.     return itemlist
  495.  
  496. def findvideos(item,channel):
  497.     logger.info("findvideos")
  498.  
  499.     url = item.url
  500.     title = item.title
  501.     thumbnail = item.thumbnail
  502.     plot = item.plot
  503.     fulltitle = item.fulltitle
  504.     # Descarga la pagina
  505.     from core import scrapertools
  506.     data = scrapertools.cachePage(url)
  507.    
  508.     from servers import servertools
  509.     listavideos = servertools.findvideos(data)
  510.    
  511.     itemlist = []
  512.     for video in listavideos:
  513.         scrapedtitle = video[0]
  514.         scrapedurl = video[1]
  515.         server = video[2]
  516.  
  517.         itemlist.append( Item(channel=channel, action="play" , title=scrapedtitle , url=scrapedurl, thumbnail=item.thumbnail, plot=item.plot, server=server, fulltitle=fulltitle, folder=False))
  518.  
  519.     return itemlist
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement