Example #1
0
def listchannel(item):

    if not "|Next Page >>" in item.title:
        try:
            lang = config.get_setting("justin_lang")
            if len(lang) == 0:
                lang = 'all'
        except:
            lang = "all"
        item.title = item.url
        if lang == 'all':
            lang = ''
        else:
            lang = '&language=' + lang
        if 'all' in item.url:
            item.url = "http://api.justin.tv/api/stream/list.json?category=%s%s&offset=0&limit=%d" % (
                item.category, lang, limit)
        else:
            item.url = "http://api.justin.tv/api/stream/list.json?subcategory=%s%s&offset=0&limit=%d" % (
                item.title, lang, limit)
    itemlist = getlistchannel(item)
    if config.get_setting('streamlive') == 'true':
        xbmctools.renderItems(itemlist, [], '', 'Movies', isPlayable='true')
        return
    else:
        return itemlist
def getplayByID(item):
    logger.info("[justintv.py] plyByID")
    tecleado = ""
    default = ""
    itemlist = []
    tecleado = teclado(heading=config.get_localized_string(30405))
    if len(tecleado)>0:
        item.url = 'http://api.justin.tv/api/stream/list.json?channel='+tecleado
        itemlist = getlistchannel(item)
        if len(itemlist)>0:
            if config.get_setting('streamlive') == 'true':
                xbmctools.renderItems(itemlist, [], '', 'Movies',isPlayable='true')
            else:
                return itemlist
        elif config.get_setting('streamlive') != 'true':
            xbmc.executebuiltin("XBMC.Notification(Justin tv,Streaming no encontrado... verificando archivos"+",5000,"+jtv_icon+")")
            item.url = tecleado
            item.action = 'getplayByID'
            itemlist = listarchives(item)
            if itemlist is not None and len(itemlist)>0:
                return itemlist
            else:
                channelANDarchivesEmpty()
        else:
            channelEmpty()
    return
def search(params, url, category):
    logger.info("[programastv.py] search")

    keyboard = xbmc.Keyboard('')
    keyboard.doModal()
    if (keyboard.isConfirmed()):
        tecleado = keyboard.getText()
        if len(tecleado) > 0:
            #convert to HTML
            tecleado = tecleado.replace(" ", "+")
            searchUrl = "http://programastvonline.blogspot.com/search?q=" + tecleado
            itemlist = []
            itemlist.append(
                Item(channel=CHANNELNAME,
                     title=tecleado,
                     action="parsear",
                     url="http://programastvonline.blogspot.com/search?q=" +
                     tecleado,
                     folder=True))

            #searchresults(params,searchUrl,category)
    xbmctools.renderItems(itemlist, params, url, category)
    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)
Example #4
0
def getplayByID(item):
    logger.info("[justintv.py] plyByID")
    tecleado = ""
    default = ""
    itemlist = []
    tecleado = teclado(heading=config.get_localized_string(30405))
    if len(tecleado) > 0:
        item.url = 'http://api.justin.tv/api/stream/list.json?channel=' + tecleado
        itemlist = getlistchannel(item)
        if len(itemlist) > 0:
            if config.get_setting('streamlive') == 'true':
                xbmctools.renderItems(itemlist, [],
                                      '',
                                      'Movies',
                                      isPlayable='true')
            else:
                return itemlist
        elif config.get_setting('streamlive') != 'true':
            xbmc.executebuiltin(
                "XBMC.Notification(Justin tv,Streaming no encontrado... verificando archivos"
                + ",5000," + jtv_icon + ")")
            item.url = tecleado
            item.action = 'getplayByID'
            itemlist = listarchives(item)
            if itemlist is not None and len(itemlist) > 0:
                return itemlist
            else:
                channelANDarchivesEmpty()
        else:
            channelEmpty()
    return
Example #5
0
def add_file_cine_library(item):
    from platformcode.xbmc import library, xbmctools
    library.savelibrary( titulo=item.show , url=item.url , thumbnail=item.thumbnail , server=item.server , plot=item.plot , canal=item.channel , category="Cine" , Serie="" , verbose=False, accion="play_from_library", pedirnombre=False, subtitle=item.subtitle )
    itemlist = []
    itemlist.append(Item(title='El vídeo '+item.show+' se ha añadido a la biblioteca'))
    xbmctools.renderItems(itemlist, "", "", "")

    return
Example #6
0
def add_file_cine_library(item):
    from platformcode.xbmc import library, xbmctools
    library.savelibrary( titulo=item.show , url=item.url , thumbnail=item.thumbnail , server=item.server , plot=item.plot , canal=item.channel , category="Cine" , Serie="" , verbose=False, accion="play_from_library", pedirnombre=False, subtitle=item.subtitle )

    itemlist = []
    itemlist.append(Item(title='El vídeo '+item.show+' se ha añadido a la biblioteca'))
    xbmctools.renderItems(itemlist, "", "", "")

    return
def search(item,texto):
    
    texto = texto.replace(' ','+')
    item.title = 'search'
    item.url = url =  'http://api.justin.tv/api/stream/search/'+texto+'.json?offset=0&limit='+str(limit)
    itemlist = getlistchannel(item)
    if config.get_setting('streamlive')=='true':
        xbmctools.renderItems(itemlist, [], '', 'Movies',isPlayable='true')
    else:
        return itemlist
Example #8
0
def search(item, texto):

    texto = texto.replace(' ', '+')
    item.title = 'search'
    item.url = url = 'http://api.justin.tv/api/stream/search/' + texto + '.json?offset=0&limit=' + str(
        limit)
    itemlist = getlistchannel(item)
    if config.get_setting('streamlive') == 'true':
        xbmctools.renderItems(itemlist, [], '', 'Movies', isPlayable='true')
    else:
        return itemlist
def favorites(item):
    if item.url == '':
        username = config.get_setting("justin_login")
    else:
        username = item.url
    if username == "":
        LoginEmpty()
        config.open_settings()
        item.url = config.get_setting("justin_login")
        if item.url == '':return
        favorites(item)
        return 
    item.title = "favorites"
    if config.get_setting('streamlive')=='true':
        livetrue='&live=true'
    else:
        livetrue = ''
    item.url = 'http://api.justin.tv/api/user/favorites/'+str(username)+'.json?offset=0&limit='+str(limit)+livetrue
    itemlist = getlistchannel(item)
    if not livetrue:
        return itemlist
    xbmctools.renderItems(itemlist, [], '', 'Movies',isPlayable='true')
    return 
Example #10
0
def search(params,url,category):
    logger.info("[programastv.py] search")
 
    keyboard = xbmc.Keyboard('')
    keyboard.doModal()
    if (keyboard.isConfirmed()):
        tecleado = keyboard.getText()
        if len(tecleado)>0:
            #convert to HTML
            tecleado = tecleado.replace(" ", "+")
            searchUrl = "http://programastvonline.blogspot.com/search?q="+tecleado
            itemlist=[]
            itemlist.append( Item(channel=CHANNELNAME, title=tecleado      , action="parsear", url="http://programastvonline.blogspot.com/search?q="+tecleado, folder=True) )
 
            #searchresults(params,searchUrl,category)
    xbmctools.renderItems(itemlist, params, url, category)
    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 )
Example #11
0
def favorites(item):
    if item.url == '':
        username = config.get_setting("justin_login")
    else:
        username = item.url
    if username == "":
        LoginEmpty()
        config.open_settings()
        item.url = config.get_setting("justin_login")
        if item.url == '': return
        favorites(item)
        return
    item.title = "favorites"
    if config.get_setting('streamlive') == 'true':
        livetrue = '&live=true'
    else:
        livetrue = ''
    item.url = 'http://api.justin.tv/api/user/favorites/' + str(
        username) + '.json?offset=0&limit=' + str(limit) + livetrue
    itemlist = getlistchannel(item)
    if not livetrue:
        return itemlist
    xbmctools.renderItems(itemlist, [], '', 'Movies', isPlayable='true')
    return
def listchannel(item):
    
    if not "|Next Page >>" in item.title:
        try:
            lang = config.get_setting("justin_lang")
            if len(lang) == 0:
                lang = 'all'
        except:
            lang = "all"
        item.title = item.url
        if lang == 'all':
            lang = ''
        else:
            lang = '&language='+lang
        if 'all' in item.url:
            item.url = "http://api.justin.tv/api/stream/list.json?category=%s%s&offset=0&limit=%d" %(item.category,lang,limit)
        else:
            item.url = "http://api.justin.tv/api/stream/list.json?subcategory=%s%s&offset=0&limit=%d" %(item.title,lang,limit)
    itemlist = getlistchannel(item)
    if config.get_setting('streamlive')=='true':
        xbmctools.renderItems(itemlist, [], '', 'Movies',isPlayable='true')
        return 
    else:
        return itemlist
def mainlist(params, url, category):
    logger.info("[programastv.py] mainlist")

    itemlist = getmainlist(params, url, category)
    xbmctools.renderItems(itemlist, params, url, category)
def searchvideos(params, url, category):
    logger.info("[programastv.py] parse")

    # ------------------------------------------------------
    # Descarga la página
    # ------------------------------------------------------
    data = scrapertools.cachePage(url)
    #logger.info(data)
    # ------------------------------------------------------
    # Extrae las entradas
    # ------------------------------------------------------
    #quitamos a partir de los comentarios
    data = data[0:data.index('class=\'post-footer\'>')]
    videos = servertools.findvideos(data)

    #xbmc.output( videos[0][2] + " es 02")
    #xbmc.output( videos[1][2] + " es 12")
    #TODO extract plot y thumbnail
    if len(videos) > 0:
        if (videos[0][2] == "Megavideo") and (videos[1][2] == "Megaupload"):
            xbmc.output("asumimos que solo hay un video con dos mirrors")
            patronvideos = 'class=\'post-title entry-title\'>.+?<a href=\'.+?\'>(.+?)</a>'
            matches = re.compile(patronvideos, re.DOTALL).findall(data)
            xbmc.output(matches[0])
            xbmctools.addnewvideo(CHANNELNAME, "play", category, "Megavideo",
                                  matches[0], videos[0][1], "", "")
            xbmctools.addnewvideo(CHANNELNAME, "play", category, "Megaupload",
                                  matches[0], videos[1][1], "", "")
        elif len(videos) == 1:
            if re.search('&amp;xtp=(.+?)_VIDEO', videos[0][1]):
                patronvideos = '&amp;xtp=(.+?)_VIDEO'
                matches = re.compile(patronvideos, re.DOTALL).findall(data)
                videos[0][1] = matches[0]
            xbmc.output("aqui estamos")
            patronvideos = 'class=\'post-title entry-title\'>.+?<a href=\'.+?\'>(.+?)</a>'
            matches = re.compile(patronvideos, re.DOTALL).findall(data)
            xbmctools.addnewvideo(CHANNELNAME, "play", category, videos[0][2],
                                  matches[0], videos[0][1], "", "")
        else:
            xbmc.output("hay mas de 1 video")
            for video in videos:
                if video[2].find("youtube") != -1:
                    continue
                #xbmc.output(video[2] + video[1] + " 2 + 1")
                indexvideo = data.index(video[1])
                #xbmc.output(str(indexvideo))
                #if (video[2]=="Megaupload"):
                #    #xbmc.output(str(indexvideo))
                #    indexvideo=data.rindex(">-",0,indexvideo)
                #    #xbmc.output(str(indexvideo))
                indexvideo1 = data.rindex(">-", 0, indexvideo)
                #xbmc.output(str(indexvideo1))
                indexvideo2 = data.rindex(">-", 0, indexvideo1)
                #xbmc.output(str(indexvideo2))
                #xbmc.output(data[indexvideo2+1:indexvideo1])
                nombre = re.sub('<.+?>', '',
                                data[indexvideo2 + 3:indexvideo1 - 5])
                while re.search('egaupl', nombre) or re.search(
                        'egavid', nombre):
                    indexvideo3 = data.rindex(">-", 0, indexvideo2)
                    nombre = re.sub('<.+?>', '',
                                    data[indexvideo3 + 3:indexvideo2 - 5])
                    indexvideo2 = indexvideo3
                xbmctools.addnewvideo(CHANNELNAME, "play", category, video[2],
                                      nombre + " " + video[2], video[1], "",
                                      "")
    else:
        xbmc.output("es un listado")
        #xbmc.output(data)
        data = data[data.index('class=\'post-header-line-1\'') + 33:]
        #xbmc.output(data)
        xbmc.output("aqui llego")

        p = MyParser()
        p.feed(data)
        p.close()
        itemlist = []
        for k, v in p.anchors.items():
            print k, "=>", v

            if re.search('programastvonline.blogspot.com', v[0]):
                itemlist.append(
                    Item(channel=CHANNELNAME,
                         title=k,
                         action="parsear",
                         url=v[0],
                         folder=True))
        xbmctools.renderItems(itemlist, params, url, category)

        #'egaupl', nombre)

        #myparser=MyParser(data)
        #myparser.parse(data)
        #links = myparser.get_hyperlinks()   # get the hyperlinks list
        #xbmc.output(str(len(links)))   # print all the links
        #descriptions = myparser.get_descriptions()   # get the hyperlinks list
        #xbmc.output("b",descriptions)   # print all the links
        #xbmc.output("aqui llego 1")
        #post-header-line-1
        #format = formatter.NullFormatter()           # create default formatter
        #htmlparser = LinksExtractor(format)        # create new parser object


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

# ------------------------------------------------------------------------------------
# Busca los enlaces a los videos
# ------------------------------------------------------------------------------------

# ------------------------------------------------------------------------------------

# 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 parsear(params, url, category):
    logger.info("[programastv.py] parsear")

    itemlist = parse(params, url, category)
    xbmctools.renderItems(itemlist, params, url, category)
def secciones(params, url, category):
    logger.info("[programastv.py] seccions")

    itemlist = getsecciones(params, url, category)
    xbmctools.renderItems(itemlist, params, url, category)
Example #17
0
def searchvideos(params, url, category):
    logger.info("[programastv.py] parse")
 
    # ------------------------------------------------------
    # Descarga la página
    # ------------------------------------------------------
    data = scrapertools.cachePage(url)
    #logger.info(data)
    # ------------------------------------------------------
    # Extrae las entradas
    # ------------------------------------------------------
    #quitamos a partir de los comentarios
    data=data[0:data.index('class=\'post-footer\'>')]
    videos=servertools.findvideos(data)
 
    #xbmc.output( videos[0][2] + " es 02")
    #xbmc.output( videos[1][2] + " es 12")
    #TODO extract plot y thumbnail
    if len(videos)>0:
        if (videos[0][2] == "Megavideo") and (videos[1][2] == "Megaupload"):
            xbmc.output("asumimos que solo hay un video con dos mirrors")
            patronvideos  = 'class=\'post-title entry-title\'>.+?<a href=\'.+?\'>(.+?)</a>'
            matches = re.compile(patronvideos,re.DOTALL).findall(data)
            xbmc.output(matches[0])
            xbmctools.addnewvideo( CHANNELNAME , "play" , category , "Megavideo" , matches[0] , videos[0][1] , "" , "" )
            xbmctools.addnewvideo( CHANNELNAME , "play" , category , "Megaupload" , matches[0] , videos[1][1] , "" , "" )
        elif len(videos)==1:
            if re.search('&amp;xtp=(.+?)_VIDEO',videos[0][1]):
                patronvideos  = '&amp;xtp=(.+?)_VIDEO'
                matches = re.compile(patronvideos,re.DOTALL).findall(data)
                videos[0][1]=matches[0]
            xbmc.output("aqui estamos")
            patronvideos  = 'class=\'post-title entry-title\'>.+?<a href=\'.+?\'>(.+?)</a>'
            matches = re.compile(patronvideos,re.DOTALL).findall(data)    
            xbmctools.addnewvideo( CHANNELNAME , "play" , category , videos[0][2] , matches[0] , videos[0][1] , "" , "" )
        else:
            xbmc.output("hay mas de 1 video")
            for video in videos:
                if video[2].find("youtube")!=-1:
                    continue   
                #xbmc.output(video[2] + video[1] + " 2 + 1")
                indexvideo=data.index(video[1])
                #xbmc.output(str(indexvideo))
                #if (video[2]=="Megaupload"):
                #    #xbmc.output(str(indexvideo))
                #    indexvideo=data.rindex(">-",0,indexvideo)
                #    #xbmc.output(str(indexvideo))
                indexvideo1=data.rindex(">-",0,indexvideo)
                #xbmc.output(str(indexvideo1))
                indexvideo2=data.rindex(">-",0,indexvideo1)
                #xbmc.output(str(indexvideo2))
                #xbmc.output(data[indexvideo2+1:indexvideo1])
                nombre=re.sub('<.+?>','',data[indexvideo2+3:indexvideo1-5])
                while re.search('egaupl', nombre) or re.search('egavid', nombre):
                     indexvideo3=data.rindex(">-",0,    indexvideo2)
                     nombre=re.sub('<.+?>','',data[indexvideo3+3:indexvideo2-5])
                     indexvideo2=indexvideo3
                xbmctools.addnewvideo( CHANNELNAME , "play" , category , video[2] , nombre + " " + video[2] , video[1] , "" , "" )    
    else:
        xbmc.output("es un listado")
        #xbmc.output(data)
        data=data[data.index('class=\'post-header-line-1\'')+33:]
        #xbmc.output(data)
        xbmc.output("aqui llego")
 
        p = MyParser()
        p.feed(data)
        p.close()
        itemlist = []
        for k, v in p.anchors.items():
            print k, "=>", v
 
            if re.search('programastvonline.blogspot.com',v[0]):
                itemlist.append( Item(channel=CHANNELNAME, title=k , action="parsear", url=v[0], folder=True) )
        xbmctools.renderItems(itemlist, params, url, category)
 
 
 
            #'egaupl', nombre)
 
        #myparser=MyParser(data)
        #myparser.parse(data)
        #links = myparser.get_hyperlinks()   # get the hyperlinks list
        #xbmc.output(str(len(links)))   # print all the links
        #descriptions = myparser.get_descriptions()   # get the hyperlinks list
        #xbmc.output("b",descriptions)   # print all the links        
        #xbmc.output("aqui llego 1")
        #post-header-line-1
        #format = formatter.NullFormatter()           # create default formatter
        #htmlparser = LinksExtractor(format)        # create new parser object
 
 
#        for video in listavideos:
#            videotitle = video[0]
#            scrapedurl = video[1]
#            server = video[2]
#            xbmctools.addnewvideo( CHANNELNAME , "play" , category , server , title.strip()+" "+match[1]+" "+match[2]+" "+videotitle , scrapedurl , thumbnail , plot )
 
    # ------------------------------------------------------------------------------------
    # Busca los enlaces a los videos
    # ------------------------------------------------------------------------------------
 
    # ------------------------------------------------------------------------------------
 
    # 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 )
Example #18
0
def mainlist(params,url,category):
    logger.info("[programastv.py] mainlist")
 
    itemlist = getmainlist(params,url,category)
    xbmctools.renderItems(itemlist, params, url, category)
Example #19
0
def parsear(params,url,category):
    logger.info("[programastv.py] parsear")
 
    itemlist = parse(params,url,category)
    xbmctools.renderItems(itemlist, params, url, category)
Example #20
0
def run():
    logger.info("[launcher.py] run")
    
    # Test if all the required directories are created
    config.verify_directories_created()
    
    # Extract parameters from sys.argv
    params, channel_name, title, fulltitle, url, thumbnail, plot, action, server, extra, subtitle, category, show, password = extract_parameters()
    logger.info("[launcher.py] channel_name=%s, title=%s, fulltitle=%s, url=%s, thumbnail=%s, plot=%s, action=%s, server=%s, extra=%s, subtitle=%s, category=%s, show=%s, password=%s" % (channel_name, title, fulltitle, url, thumbnail, plot, action, server, extra, subtitle, category, show, password))

    try:
        # Accion por defecto - elegir canal
        if ( action=="selectchannel" ):
            # Borra el fichero de las cookies para evitar problemas con MV
            #ficherocookies = os.path.join( config.get_data_path(), 'cookies.lwp' )
            #if os.path.exists(ficherocookies):
            #    os.remove(ficherocookies)
            
            if config.get_setting("updatechannels")=="true":
                try:
                    from core import updater
                    actualizado = updater.updatechannel("channelselector")

                    if actualizado:
                        import xbmcgui
                        advertencia = xbmcgui.Dialog()
                        advertencia.ok("tvalacarta",config.get_localized_string(30064))
                except:
                    pass

            import channelselector as plugin
            plugin.mainlist(params, url, category)

        # Actualizar version
        elif ( action=="update" ):
            try:
                from core import updater
                updater.update(params)
            except ImportError:
                logger.info("[launcher.py] Actualizacion automática desactivada")

            import channelselector as plugin
            plugin.listchannels(params, url, category)

        elif (action=="channeltypes"):
            import channelselector as plugin
            plugin.channeltypes(params,url,category)

        elif (action=="listchannels"):
            import channelselector as plugin
            plugin.listchannels(params,url,category)

        # El resto de acciones vienen en el parámetro "action", y el canal en el parámetro "channel"
        else:
            if action=="mainlist" and config.get_setting("updatechannels")=="true":
                try:
                    from core import updater
                    actualizado = updater.updatechannel(channel_name)

                    if actualizado:
                        import xbmcgui
                        advertencia = xbmcgui.Dialog()
                        advertencia.ok("plugin",channel_name,config.get_localized_string(30063))
                except:
                    pass

            # La acción puede estar en el core, o ser un canal regular. El buscador es un canal especial que está en pelisalacarta
            regular_channel_path = os.path.join( config.get_runtime_path(), PLUGIN_NAME , 'channels' , channel_name+".py" )
            core_channel_path = os.path.join( config.get_runtime_path(), 'core' , channel_name+".py" )
            logger.info("[launcher.py] regular_channel_path=%s" % regular_channel_path)
            logger.info("[launcher.py] core_channel_path=%s" % core_channel_path)

            if channel_name=="buscador":
                import pelisalacarta.buscador as channel
            elif os.path.exists( regular_channel_path ):
                exec "import "+PLUGIN_NAME+".channels."+channel_name+" as channel"
            elif os.path.exists( core_channel_path ):
                exec "from core import "+channel_name+" as channel"

            logger.info("[launcher.py] running channel %s %s" % (channel.__name__ , channel.__file__))

            generico = False
            # Esto lo he puesto asi porque el buscador puede ser generico o normal, esto estará asi hasta que todos los canales sean genericos 
            if category == "Buscador_Generico":
                generico = True
            else:
                try:
                    generico = channel.isGeneric()
                except:
                    generico = False

            if not generico:
                logger.info("[launcher.py] xbmc native channel")
                if (action=="strm"):
                    from platformcode.xbmc import xbmctools
                    xbmctools.playstrm(params, url, category)
                else:
                    exec "channel."+action+"(params, url, category)"
            else:            
                logger.info("[launcher.py] multiplatform channel")
                from core.item import Item
                item = Item(channel=channel_name, title=title , fulltitle=fulltitle, url=url, thumbnail=thumbnail , plot=plot , server=server, category=category, extra=extra, subtitle=subtitle, show=show, password=password)
                
                '''
                if item.subtitle!="":
                    logger.info("[launcher.py] Downloading subtitle file "+item.subtitle)
                    from core import downloadtools
                    
                    ficherosubtitulo = os.path.join( config.get_data_path() , "subtitulo.srt" )
                    if os.path.exists(ficherosubtitulo):
                        os.remove(ficherosubtitulo)

                    downloadtools.downloadfile(item.subtitle, ficherosubtitulo )
                    config.set_setting("subtitulo","true")
                else:
                    logger.info("[launcher.py] No subtitle")
                '''
                from platformcode.xbmc import xbmctools

                if action=="play":
                    logger.info("[launcher.py] play")
                    # Si el canal tiene una acción "play" tiene prioridad
                    if hasattr(channel, 'play'):
                        logger.info("[launcher.py] executing channel 'play' method")
                        itemlist = channel.play(item)
                        if len(itemlist)>0:
                            item = itemlist[0]
                            xbmctools.play_video(channel=channel_name, server=item.server, url=item.url, category=item.category, title=item.title, thumbnail=item.thumbnail, plot=item.plot, extra=item.extra, subtitle=item.subtitle, video_password = item.password, fulltitle=item.fulltitle)
                        else:
                            import xbmcgui
                            ventana_error = xbmcgui.Dialog()
                            ok = ventana_error.ok ("plugin", "No hay nada para reproducir")
                    else:
                        logger.info("[launcher.py] no channel 'play' method, executing core method")
                        xbmctools.play_video(channel=channel_name, server=item.server, url=item.url, category=item.category, title=item.title, thumbnail=item.thumbnail, plot=item.plot, extra=item.extra, subtitle=item.subtitle, video_password = item.password, fulltitle=item.fulltitle)

                elif action=="strm_detail" or action=="play_from_library":
                    logger.info("[launcher.py] play_from_library")

                    fulltitle = item.show + " " + item.title
                    elegido = Item(url="")                    

                    logger.info("item.server=#"+item.server+"#")
                    # Ejecuta find_videos, del canal o común
                    try:
                        itemlist = channel.findvideos(item)
                    except:
                        from servers import servertools
                        itemlist = servertools.find_video_items(item)

                    if len(itemlist)>0:
                        #for item2 in itemlist:
                        #    logger.info(item2.title+" "+item2.subtitle)
    
                        # El usuario elige el mirror
                        opciones = []
                        for item in itemlist:
                            opciones.append(item.title)
                    
                        import xbmcgui
                        dia = xbmcgui.Dialog()
                        seleccion = dia.select(config.get_localized_string(30163), opciones)
                        elegido = itemlist[seleccion]
    
                        if seleccion==-1:
                            return
                    else:
                        elegido = item
                
                    # Ejecuta el método play del canal, si lo hay
                    try:
                        itemlist = channel.play(elegido)
                        item = itemlist[0]
                    except:
                        item = elegido
                    logger.info("Elegido %s (sub %s)" % (item.title,item.subtitle))
                    
                    from platformcode.xbmc import xbmctools
                    logger.info("subtitle="+item.subtitle)
                    xbmctools.play_video(strmfile=True, channel=item.channel, server=item.server, url=item.url, category=item.category, title=item.title, thumbnail=item.thumbnail, plot=item.plot, extra=item.extra, subtitle=item.subtitle, video_password = item.password, fulltitle=fulltitle)

                elif action=="add_pelicula_to_library":
                    logger.info("[launcher.py] add_pelicula_to_library")
                    from platformcode.xbmc import library
                    # Obtiene el listado desde el que se llamó
                    library.savelibrary( titulo=item.fulltitle , url=item.url , thumbnail=item.thumbnail , server=item.server , plot=item.plot , canal=item.channel , category="Cine" , Serie=item.show.strip() , verbose=False, accion="play_from_library", pedirnombre=False, subtitle=item.subtitle )

                elif action=="add_serie_to_library":
                    logger.info("[launcher.py] add_serie_to_library")
                    from platformcode.xbmc import library
                    import xbmcgui
                
                    # Obtiene el listado desde el que se llamó
                    action = item.extra
                    exec "itemlist = channel."+action+"(item)"

                    # Progreso
                    pDialog = xbmcgui.DialogProgress()
                    ret = pDialog.create('pelisalacarta', 'Añadiendo episodios...')
                    pDialog.update(0, 'Añadiendo episodio...')
                    totalepisodes = len(itemlist)
                    logger.info ("[launcher.py] Total Episodios:"+str(totalepisodes))
                    i = 0
                    errores = 0
                    nuevos = 0
                    for item in itemlist:
                        i = i + 1
                        pDialog.update(i*100/totalepisodes, 'Añadiendo episodio...',item.title)
                        if (pDialog.iscanceled()):
                            return
                
                        try:
                            #(titulo="",url="",thumbnail="",server="",plot="",canal="",category="Cine",Serie="",verbose=True,accion="strm",pedirnombre=True):
                            # Añade todos menos el último (el que dice "Añadir esta serie...")
                            if i<len(itemlist):
                                nuevos = nuevos + library.savelibrary( titulo=item.title , url=item.url , thumbnail=item.thumbnail , server=item.server , plot=item.plot , canal=item.channel , category="Series" , Serie=item.show.strip() , verbose=False, accion="play_from_library", pedirnombre=False, subtitle=item.subtitle )
                        except IOError:
                            import sys
                            for line in sys.exc_info():
                                logger.error( "%s" % line )
                            logger.info("[launcher.py]Error al grabar el archivo "+item.title)
                            errores = errores + 1
                        
                    pDialog.close()
                    
                    # Actualizacion de la biblioteca
                    itemlist=[]
                    if errores > 0:
                        itemlist.append(Item(title="ERROR, la serie NO se ha añadido a la biblioteca o lo ha hecho incompleta"))
                        logger.info ("[launcher.py] No se pudo añadir "+str(errores)+" episodios")
                    else:
                        itemlist.append(Item(title="La serie se ha añadido a la biblioteca"))
                        logger.info ("[launcher.py] Ningún error al añadir "+str(errores)+" episodios")
                    
                    # FIXME:jesus Comentado porque no funciona bien en todas las versiones de XBMC
                    #library.update(totalepisodes,errores,nuevos)
                    xbmctools.renderItems(itemlist, params, url, category)
                    
                    #Lista con series para actualizar
                    nombre_fichero_config_canal = os.path.join( config.get_data_path() , "series.xml" )
                    logger.info("nombre_fichero_config_canal="+nombre_fichero_config_canal)
                    if not os.path.exists(nombre_fichero_config_canal):
                        f = open( nombre_fichero_config_canal , "w" )
                    else:
                        f = open( nombre_fichero_config_canal , "r" )
                        contenido = f.read()
                        f.close()
                        f = open( nombre_fichero_config_canal , "w" )
                        f.write(contenido)
                    f.write(item.show+","+item.url+","+item.channel+"\n")
                    f.close();

                elif action=="download_all_episodes":
                    download_all_episodes(item,channel)

                elif action=="search":
                    logger.info("[launcher.py] search")
                    import xbmc
                    keyboard = xbmc.Keyboard("")
                    keyboard.doModal()
                    if (keyboard.isConfirmed()):
                        tecleado = keyboard.getText()
                        tecleado = tecleado.replace(" ", "+")
                        itemlist = channel.search(item,tecleado)
                    else:
                        itemlist = []
                    xbmctools.renderItems(itemlist, params, url, category)

                else:
                    logger.info("[launcher.py] executing channel '"+action+"' method")
                    if action!="findvideos":
                        exec "itemlist = channel."+action+"(item)"
                    else:
                        # Intenta ejecutar una posible funcion "findvideos" del canal
                        try:
                            exec "itemlist = channel."+action+"(item)"
                        # Si no funciona, lanza el método genérico para detectar vídeos
                        except:
                            logger.info("[launcher.py] no channel 'findvideos' method, executing core method")
                            from servers import servertools
                            itemlist = servertools.find_video_items(item)
                        from core import subtitletools
                        subtitletools.saveSubtitleName(item)

                    # Activa el modo biblioteca para todos los canales genéricos, para que se vea el argumento
                    import xbmcplugin
                    import sys
                    handle = sys.argv[1]
                    xbmcplugin.setContent(int( handle ),"movies")
                    
                    # Añade los items a la lista de XBMC
                    xbmctools.renderItems(itemlist, params, url, category)

    except urllib2.URLError,e:
        import traceback
        import sys
        from pprint import pprint
        exc_type, exc_value, exc_tb = sys.exc_info()
        lines = traceback.format_exception(exc_type, exc_value, exc_tb)
        for line in lines:
            line_splits = line.split("\n")
            for line_split in line_splits:
                logger.error(line_split)
        import xbmcgui
        ventana_error = xbmcgui.Dialog()
        # Agarra los errores surgidos localmente enviados por las librerias internas
        if hasattr(e, 'reason'):
            logger.info("Razon del error, codigo: %d , Razon: %s" %(e.reason[0],e.reason[1]))
            texto = config.get_localized_string(30050) # "No se puede conectar con el sitio web"
            ok = ventana_error.ok ("plugin", texto)
        # Agarra los errores con codigo de respuesta del servidor externo solicitado     
        elif hasattr(e,'code'):
            logger.info("codigo de error HTTP : %d" %e.code)
            texto = (config.get_localized_string(30051) % e.code) # "El sitio web no funciona correctamente (error http %d)"
            ok = ventana_error.ok ("plugin", texto)    
Example #21
0
def run():
    logger.info("[launcher.py] run")

    # Test if all the required directories are created
    config.verify_directories_created()

    # Extract parameters from sys.argv
    params, fanart, channel_name, title, fulltitle, url, thumbnail, plot, action, server, extra, subtitle, viewmode, category, show, password = extract_parameters(
    )
    logger.info(
        "[launcher.py] fanart=%s, channel_name=%s, title=%s, fulltitle=%s, url=%s, thumbnail=%s, plot=%s, action=%s, server=%s, extra=%s, subtitle=%s, category=%s, show=%s, password=%s"
        % (fanart, channel_name, title, fulltitle, url, thumbnail, plot,
           action, server, extra, subtitle, category, show, password))

    try:
        # Accion por defecto - elegir canal
        if (action == "selectchannel"):
            # Borra el fichero de las cookies para evitar problemas con MV
            #ficherocookies = os.path.join( config.get_data_path(), 'cookies.lwp' )
            #if os.path.exists(ficherocookies):
            #    os.remove(ficherocookies)

            if config.get_setting("updatechannels") == "true":
                try:
                    from core import updater
                    actualizado = updater.updatechannel("channelselector")

                    if actualizado:
                        import xbmcgui
                        advertencia = xbmcgui.Dialog()
                        advertencia.ok("tvalacarta",
                                       config.get_localized_string(30064))
                except:
                    pass

            import channelselector as plugin
            plugin.mainlist()

        # Actualizar version
        elif (action == "update"):
            try:
                from core import updater
                updater.update(params)
            except ImportError:
                logger.info(
                    "[launcher.py] Actualizacion automática desactivada")

            #import channelselector as plugin
            #plugin.listchannels(params, url, category)
            if config.get_system_platform() != "xbox":
                import xbmc
                xbmc.executebuiltin("Container.Refresh")

        # El resto de acciones vienen en el parámetro "action", y el canal en el parámetro "channel"
        else:
            if action == "mainlist" and config.get_setting(
                    "updatechannels") == "true":
                try:
                    from core import updater
                    actualizado = updater.updatechannel(channel_name)

                    if actualizado:
                        import xbmcgui
                        advertencia = xbmcgui.Dialog()
                        advertencia.ok("plugin", channel_name,
                                       config.get_localized_string(30063))
                except:
                    pass

            # La acción puede estar en el core, o ser un canal regular. El buscador es un canal especial que está en pelisalacarta
            regular_channel_path = os.path.join(config.get_runtime_path(),
                                                PLUGIN_NAME, 'channels',
                                                channel_name + ".py")
            core_channel_path = os.path.join(config.get_runtime_path(), 'core',
                                             channel_name + ".py")
            logger.info("[launcher.py] regular_channel_path=%s" %
                        regular_channel_path)
            logger.info("[launcher.py] core_channel_path=%s" %
                        core_channel_path)

            if channel_name == "buscador":
                import pelisalacarta.buscador as channel
            elif os.path.exists(regular_channel_path):
                exec "import mywebtv.channels." + channel_name + " as channel"
            elif os.path.exists(regular_channel_path):
                exec "import tvalacarta.channels." + channel_name + " as channel"
            elif os.path.exists(core_channel_path):
                exec "from core import " + channel_name + " as channel"

            logger.info("[launcher.py] running channel %s %s" %
                        (channel.__name__, channel.__file__))

            generico = False
            # Esto lo he puesto asi porque el buscador puede ser generico o normal, esto estará asi hasta que todos los canales sean genericos
            if category == "Buscador_Generico":
                generico = True
            else:
                try:
                    generico = channel.isGeneric()
                except:
                    generico = False

            if not generico:
                logger.info("[launcher.py] xbmc native channel")
                if (action == "strm"):
                    from platformcode.xbmc import xbmctools
                    xbmctools.playstrm(params, url, category)
                else:
                    exec "channel." + action + "(params, url, category)"
            else:
                logger.info("[launcher.py] multiplatform channel")
                from core.item import Item
                item = Item(channel=channel_name,
                            title=title,
                            fulltitle=fulltitle,
                            url=url,
                            thumbnail=thumbnail,
                            plot=plot,
                            server=server,
                            category=category,
                            extra=extra,
                            subtitle=subtitle,
                            viewmode=viewmode,
                            show=show,
                            password=password,
                            fanart=fanart)
                '''
                if item.subtitle!="":
                    logger.info("[launcher.py] Downloading subtitle file "+item.subtitle)
                    from core import downloadtools
                    
                    ficherosubtitulo = os.path.join( config.get_data_path() , "subtitulo.srt" )
                    if os.path.exists(ficherosubtitulo):
                        os.remove(ficherosubtitulo)

                    downloadtools.downloadfile(item.subtitle, ficherosubtitulo )
                    config.set_setting("subtitulo","true")
                else:
                    logger.info("[launcher.py] No subtitle")
                '''
                from platformcode.xbmc import xbmctools

                if action == "play":
                    logger.info("[launcher.py] play")
                    # Si el canal tiene una acción "play" tiene prioridad
                    if hasattr(channel, 'play'):
                        logger.info(
                            "[launcher.py] executing channel 'play' method")
                        itemlist = channel.play(item)
                        if len(itemlist) > 0:
                            item = itemlist[0]
                            xbmctools.play_video(channel=channel_name,
                                                 server=item.server,
                                                 url=item.url,
                                                 category=item.category,
                                                 title=item.title,
                                                 thumbnail=item.thumbnail,
                                                 plot=item.plot,
                                                 extra=item.extra,
                                                 subtitle=item.subtitle,
                                                 video_password=item.password,
                                                 fulltitle=item.fulltitle,
                                                 Serie=item.show)
                        else:
                            import xbmcgui
                            ventana_error = xbmcgui.Dialog()
                            ok = ventana_error.ok(
                                "plugin", "No hay nada para reproducir")
                    else:
                        logger.info(
                            "[launcher.py] no channel 'play' method, executing core method"
                        )
                        xbmctools.play_video(channel=channel_name,
                                             server=item.server,
                                             url=item.url,
                                             category=item.category,
                                             title=item.title,
                                             thumbnail=item.thumbnail,
                                             plot=item.plot,
                                             extra=item.extra,
                                             subtitle=item.subtitle,
                                             video_password=item.password,
                                             fulltitle=item.fulltitle,
                                             Serie=item.show)

                elif action == "strm_detail" or action == "play_from_library":
                    logger.info("[launcher.py] play_from_library")

                    fulltitle = item.show + " " + item.title
                    elegido = Item(url="")

                    logger.info("item.server=#" + item.server + "#")
                    # Ejecuta find_videos, del canal o común
                    try:
                        itemlist = channel.findvideos(item)
                    except:
                        from servers import servertools
                        itemlist = servertools.find_video_items(item)

                    if len(itemlist) > 0:
                        #for item2 in itemlist:
                        #    logger.info(item2.title+" "+item2.subtitle)

                        # El usuario elige el mirror
                        opciones = []
                        for item in itemlist:
                            opciones.append(item.title)

                        import xbmcgui
                        dia = xbmcgui.Dialog()
                        seleccion = dia.select(
                            config.get_localized_string(30163), opciones)
                        elegido = itemlist[seleccion]

                        if seleccion == -1:
                            return
                    else:
                        elegido = item

                    # Ejecuta el método play del canal, si lo hay
                    try:
                        itemlist = channel.play(elegido)
                        item = itemlist[0]
                    except:
                        item = elegido
                    logger.info("Elegido %s (sub %s)" %
                                (item.title, item.subtitle))

                    from platformcode.xbmc import xbmctools
                    logger.info("subtitle=" + item.subtitle)
                    xbmctools.play_video(strmfile=True,
                                         channel=item.channel,
                                         server=item.server,
                                         url=item.url,
                                         category=item.category,
                                         title=item.title,
                                         thumbnail=item.thumbnail,
                                         plot=item.plot,
                                         extra=item.extra,
                                         subtitle=item.subtitle,
                                         video_password=item.password,
                                         fulltitle=fulltitle)

                elif action == "add_pelicula_to_library":
                    logger.info("[launcher.py] add_pelicula_to_library")
                    from platformcode.xbmc import library
                    # Obtiene el listado desde el que se llamó
                    library.savelibrary(titulo=item.fulltitle,
                                        url=item.url,
                                        thumbnail=item.thumbnail,
                                        server=item.server,
                                        plot=item.plot,
                                        canal=item.channel,
                                        category="Cine",
                                        Serie=item.show.strip(),
                                        verbose=False,
                                        accion="play_from_library",
                                        pedirnombre=False,
                                        subtitle=item.subtitle)

                elif action == "add_serie_to_library":
                    logger.info("[launcher.py] add_serie_to_library, show=" +
                                item.show)
                    from platformcode.xbmc import library
                    import xbmcgui

                    # Obtiene el listado desde el que se llamó
                    action = item.extra

                    # Esta marca es porque el item tiene algo más aparte en el atributo "extra"
                    if "###" in item.extra:
                        action = item.extra.split("###")[0]
                        item.extra = item.extra.split("###")[1]

                    exec "itemlist = channel." + action + "(item)"

                    # Progreso
                    pDialog = xbmcgui.DialogProgress()
                    ret = pDialog.create('mywebtv', 'Añadiendo episodios...')
                    pDialog.update(0, 'Añadiendo episodio...')
                    totalepisodes = len(itemlist)
                    logger.info("[launcher.py] Total Episodios:" +
                                str(totalepisodes))
                    i = 0
                    errores = 0
                    nuevos = 0
                    for item in itemlist:
                        i = i + 1
                        pDialog.update(i * 100 / totalepisodes,
                                       'Añadiendo episodio...', item.title)
                        if (pDialog.iscanceled()):
                            return

                        try:
                            #(titulo="",url="",thumbnail="",server="",plot="",canal="",category="Cine",Serie="",verbose=True,accion="strm",pedirnombre=True):
                            # Añade todos menos el último (el que dice "Añadir esta serie...")
                            if i < len(itemlist):
                                nuevos = nuevos + library.savelibrary(
                                    titulo=item.title,
                                    url=item.url,
                                    thumbnail=item.thumbnail,
                                    server=item.server,
                                    plot=item.plot,
                                    canal=item.channel,
                                    category="Series",
                                    Serie=item.show.strip(),
                                    verbose=False,
                                    accion="play_from_library",
                                    pedirnombre=False,
                                    subtitle=item.subtitle,
                                    extra=item.extra)
                        except IOError:
                            import sys
                            for line in sys.exc_info():
                                logger.error("%s" % line)
                            logger.info(
                                "[launcher.py]Error al grabar el archivo " +
                                item.title)
                            errores = errores + 1

                    pDialog.close()

                    # Actualizacion de la biblioteca
                    itemlist = []
                    if errores > 0:
                        itemlist.append(
                            Item(
                                title=
                                "ERROR, la serie NO se ha añadido a la biblioteca o lo ha hecho incompleta"
                            ))
                        logger.info("[launcher.py] No se pudo añadir " +
                                    str(errores) + " episodios")
                    else:
                        itemlist.append(
                            Item(title="La serie se ha añadido a la biblioteca"
                                 ))
                        logger.info("[launcher.py] Ningún error al añadir " +
                                    str(errores) + " episodios")

                    # FIXME:jesus Comentado porque no funciona bien en todas las versiones de XBMC
                    #library.update(totalepisodes,errores,nuevos)
                    xbmctools.renderItems(itemlist, params, url, category)

                    #Lista con series para actualizar
                    nombre_fichero_config_canal = os.path.join(
                        config.get_data_path(), "series.xml")
                    logger.info("nombre_fichero_config_canal=" +
                                nombre_fichero_config_canal)
                    if not os.path.exists(nombre_fichero_config_canal):
                        f = open(nombre_fichero_config_canal, "w")
                    else:
                        f = open(nombre_fichero_config_canal, "r")
                        contenido = f.read()
                        f.close()
                        f = open(nombre_fichero_config_canal, "w")
                        f.write(contenido)
                    f.write(item.show + "," + item.url + "," + item.channel +
                            "\n")
                    f.close()

                elif action == "download_all_episodes":
                    download_all_episodes(item, channel)

                elif action == "search":
                    logger.info("[launcher.py] search")
                    import xbmc
                    keyboard = xbmc.Keyboard("")
                    keyboard.doModal()
                    if (keyboard.isConfirmed()):
                        tecleado = keyboard.getText()
                        tecleado = tecleado.replace(" ", "+")
                        itemlist = channel.search(item, tecleado)
                    else:
                        itemlist = []
                    xbmctools.renderItems(itemlist, params, url, category)

                else:
                    logger.info("[launcher.py] executing channel '" + action +
                                "' method")
                    if action != "findvideos":
                        exec "itemlist = channel." + action + "(item)"

                        #for item in itemlist:
                        #    logger.info("viemode="+item.viewmode)
                    else:

                        # Intenta ejecutar una posible funcion "findvideos" del canal
                        if hasattr(channel, 'findvideos'):
                            exec "itemlist = channel." + action + "(item)"
                        # Si no funciona, lanza el método genérico para detectar vídeos
                        else:
                            logger.info(
                                "[launcher.py] no channel 'findvideos' method, executing core method"
                            )
                            from servers import servertools
                            itemlist = servertools.find_video_items(item)

                        from core import subtitletools
                        subtitletools.saveSubtitleName(item)

                    # Activa el modo biblioteca para todos los canales genéricos, para que se vea el argumento
                    import xbmcplugin
                    import sys
                    handle = sys.argv[1]
                    xbmcplugin.setContent(int(handle), "movies")

                    # Añade los items a la lista de XBMC
                    xbmctools.renderItems(itemlist, params, url, category)

    except urllib2.URLError, e:
        import traceback, sys
        from pprint import pprint
        exc_type, exc_value, exc_tb = sys.exc_info()
        lines = traceback.format_exception(exc_type, exc_value, exc_tb)
        for line in lines:
            line_splits = line.split("\n")
            for line_split in line_splits:
                logger.error(line_split)

        import xbmcgui
        ventana_error = xbmcgui.Dialog()
        # Agarra los errores surgidos localmente enviados por las librerias internas
        if hasattr(e, 'reason'):
            logger.info("Razon del error, codigo: %d , Razon: %s" %
                        (e.reason[0], e.reason[1]))
            texto = config.get_localized_string(
                30050)  # "No se puede conectar con el sitio web"
            ok = ventana_error.ok("plugin", texto)
        # Agarra los errores con codigo de respuesta del servidor externo solicitado
        elif hasattr(e, 'code'):
            logger.info("codigo de error HTTP : %d" % e.code)
            texto = (
                config.get_localized_string(30051) % e.code
            )  # "El sitio web no funciona correctamente (error http %d)"
            ok = ventana_error.ok("plugin", texto)
Example #22
0
def secciones(params,url,category):
    logger.info("[programastv.py] seccions")
 
    itemlist = getsecciones(params,url,category)
    xbmctools.renderItems(itemlist, params, url, category)