def fichas(item):

    itemlist = []

    texto = scrapertools.get_match( item.url, "search...([^&]+)&" )

    data = jsontools.load_json( scrapertools.cache_page( item.url ) )

    nextPageToken = data.get('nextPageToken')

    _items = data.get('items', {})

    for _item in _items:

        url = page_url % _item['id']['videoId']
        title = _item['snippet']['title']
        plot = _item['snippet']['description']
        thumbnail = art_thumbnail % _item['id']['videoId']
        fanart = art_thumbnail % _item['id']['videoId']

        fulltitle = title
        title = scrapertools.htmlclean( title )
        show = library.title_to_folder_name( title )
        plot = scrapertools.htmlclean( plot )

        itemlist.append( Item( channel=__channel__, title=title, url=url, action="play", thumbnail=thumbnail, fanart=fanart, plot=plot, server="youtube", fulltitle=fulltitle, viewmode="movie_with_plot", show=show, folder=False ) )

    ## Paginación
    url = api_search % (texto, "50", nextPageToken)
    itemlist.append( Item( channel=__channel__, title="Pagina successiva >>", url=url, action="fichas", folder=True ) )

    return itemlist
def file_cine_library(item):
    import os
    from platformcode import library
    librarypath = os.path.join(config.get_library_path(),"CINE")
    archivo = library.title_to_folder_name(item.title.strip())
    strmfile = archivo+".strm"
    strmfilepath = os.path.join(librarypath,strmfile)

    if not os.path.exists(strmfilepath):
        itemlist.append( Item(channel=item.channel, title=">> Añadir a la biblioteca...", url=item.url, action="add_file_cine_library", extra="episodios", show=archivo) )

    return itemlist
Esempio n. 3
0
def file_cine_library(item):
    import os
    from platformcode import library
    librarypath = os.path.join(config.get_library_path(),"CINE")
    archivo = library.title_to_folder_name(item.title.strip())
    strmfile = archivo+".strm"
    strmfilepath = os.path.join(librarypath,strmfile)

    if not os.path.exists(strmfilepath):
        itemlist.append( Item(channel=item.channel, title=">> Añadir a la biblioteca...", url=item.url, action="add_file_cine_library", extra="episodios", show=archivo) )

    return itemlist
Esempio n. 4
0
def fichas(item):

    itemlist = []

    texto = scrapertools.get_match(item.url, "search...([^&]+)&")

    data = jsontools.load_json(scrapertools.cache_page(item.url))

    nextPageToken = data.get('nextPageToken')

    _items = data.get('items', {})

    for _item in _items:

        url = page_url % _item['id']['videoId']
        title = _item['snippet']['title']
        plot = _item['snippet']['description']
        thumbnail = art_thumbnail % _item['id']['videoId']
        fanart = art_thumbnail % _item['id']['videoId']

        fulltitle = title
        title = scrapertools.htmlclean(title)
        show = library.title_to_folder_name(title)
        plot = scrapertools.htmlclean(plot)

        itemlist.append(
            Item(channel=__channel__,
                 title=title,
                 url=url,
                 action="play",
                 thumbnail=thumbnail,
                 fanart=fanart,
                 plot=plot,
                 server="youtube",
                 fulltitle=fulltitle,
                 viewmode="movie_with_plot",
                 show=show,
                 folder=False))

    ## Paginación
    url = api_search % (texto, "50", nextPageToken)
    itemlist.append(
        Item(channel=__channel__,
             title="Pagina successiva >>",
             url=url,
             action="fichas",
             folder=True))

    return itemlist
def get_next_items(item):

    plugintools.log("navigation.get_next_items item=" + item.tostring())

    try:
        # ----------------------------------------------------------------
        #  Main menu
        # ----------------------------------------------------------------
        if item.channel == "navigation":
            # --- Update channels list ---------------------------------------
            from core import config
            if item.action == "mainlist":
                plugintools.log("navigation.get_next_items Main menu")

                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
            # ----------------------------------------------------------------

            if item.action == "mainlist":
                plugintools.log("navigation.get_next_items Main menu")
                itemlist = channelselector.getmainlist("bannermenu")

        elif item.channel == "channelselector":

            if item.action == "channeltypes":
                plugintools.log("navigation.get_next_items Channel types menu")
                itemlist = channelselector.getchanneltypes("bannermenu")

            elif item.action == "listchannels":
                plugintools.log("navigation.get_next_items Channel list menu")
                itemlist = channelselector.filterchannels(
                    item.category, "bannermenu")

        elif item.channel == "configuracion":
            plugintools.open_settings_dialog()
            return []

        else:

            if item.action == "":
                item.action = "mainlist"

            plugintools.log("navigation.get_next_items Channel code (" +
                            item.channel + "." + item.action + ")")

            # --- Update channels files --------------------------------------
            if item.action == "mainlist":
                from core import config
                if config.get_setting("updatechannels") == "true":
                    try:
                        from core import updater
                        actualizado = updater.updatechannel(item.channel)

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

            try:
                exec "import channels." + item.channel + " as channel"
            except:
                exec "import core." + item.channel + " as channel"

            from platformcode import xbmctools

            if item.action == "play":
                plugintools.log("navigation.get_next_items play")

                # Si el canal tiene una acción "play" tiene prioridad
                if hasattr(channel, 'play'):
                    plugintools.log(
                        "streamondemand-pureita.navigation.py Channel has its own 'play' method"
                    )
                    itemlist = channel.play(item)
                    if len(itemlist) > 0:
                        item = itemlist[0]

                        # FIXME: Este error ha que tratarlo de otra manera, al dar a volver sin ver el vídeo falla
                        try:
                            xbmctools.play_video(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=item.fulltitle,
                                                 Serie=item.show)
                        except:
                            pass

                    else:
                        import xbmcgui
                        ventana_error = xbmcgui.Dialog()
                        ok = ventana_error.ok("plugin",
                                              "Nessun File Da Riprodurre")
                else:
                    plugintools.log(
                        "streamondemand-pureita.navigation.py No channel 'play' method, executing core method"
                    )

                    # FIXME: Este error ha que tratarlo de otra manera, por al dar a volver sin ver el vídeo falla
                    # Mejor hacer el play desde la ventana
                    try:
                        xbmctools.play_video(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=item.fulltitle,
                                             Serie=item.show)
                    except:
                        pass

                return []

            elif item.action == "findvideos":
                plugintools.log("navigation.get_next_items findvideos")

                # Si el canal tiene una acción "findvideos" tiene prioridad
                if hasattr(channel, 'findvideos'):
                    plugintools.log(
                        "streamondemand-pureita.navigation.py Channel has its own 'findvideos' method"
                    )
                    itemlist = channel.findvideos(item)
                else:
                    itemlist = []

                if len(itemlist) == 0:
                    from servers import servertools
                    itemlist = servertools.find_video_items(item)

                if len(itemlist) == 0:
                    itemlist = [
                        Item(title="No se han encontrado vídeos",
                             thumbnail=os.path.join(
                                 plugintools.get_runtime_path(), "resources",
                                 "images", "thumb_error.png"))
                    ]
            # ---------------add_serie_to_library-----------
            elif item.action == "add_serie_to_library":
                plugintools.log(
                    "navigation.get_next_items add_serie_to_library")
                from platformcode 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('streamondemand-pureita',
                                     'Añadiendo episodios...')
                pDialog.update(0, 'Añadiendo episodio...')
                totalepisodes = len(itemlist)
                plugintools.log("navigation.get_next_items 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)
                    plugintools.log(
                        "streamondemand-pureita.navigation.py add_serie_to_library, title="
                        + 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 que dice "Añadir esta serie..." o "Descargar esta serie..."
                        if item.action != "add_serie_to_library" and item.action != "download_all_episodes":
                            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)
                        plugintools.log(
                            "streamondemand-pureita.navigation.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=
                            "ERRORE, la serie NON si è aggiunta alla biblioteca o la fatto in modo incompleto"
                        ))
                    plugintools.log(
                        "navigation.get_next_items No se pudo añadir " +
                        str(errores) + " episodios")
                else:
                    itemlist.append(
                        Item(
                            title="La serie è stata aggiunta alla biblioteca"))
                    plugintools.log(
                        "navigation.get_next_items 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
                from core import config
                nombre_fichero_config_canal = os.path.join(
                    config.get_library_path(), "series.xml")
                if not os.path.exists(nombre_fichero_config_canal):
                    nombre_fichero_config_canal = os.path.join(
                        config.get_data_path(), "series.xml")

                plugintools.log("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)
                from platformcode import library
                f.write(
                    library.title_to_folder_name(item.show) + "," + item.url +
                    "," + item.channel + "\n")
                f.close()
                return itemlist
            # --------------------------------------------------------------------
            elif item.action == "download_all_episodes":
                plugintools.log(
                    "navigation.get_next_items download_all_episodes")
                download_all_episodes(item, channel)

#---------------------------------------------------------------------
            else:

                if item.action == "search":
                    tecleado = plugintools.keyboard_input()
                    if tecleado != "":
                        tecleado = tecleado.replace(" ", "+")
                        itemlist = channel.search(item, tecleado)
                elif item.channel == "novedades" and item.action == "mainlist":
                    itemlist = channel.mainlist(item, "bannermenu")
                elif item.channel == "buscador" and item.action == "mainlist":
                    itemlist = channel.mainlist(item, "bannermenu")
                else:
                    exec "itemlist = channel." + item.action + "(item)"

                for loaded_item in itemlist:

                    if loaded_item.thumbnail == "":
                        if loaded_item.folder:
                            loaded_item.thumbnail = os.path.join(
                                plugintools.get_runtime_path(), "resources",
                                "images", "thumb_folder.png")
                        else:
                            loaded_item.thumbnail = os.path.join(
                                plugintools.get_runtime_path(), "resources",
                                "images", "thumb_nofolder.png")

                if len(itemlist) == 0:
                    itemlist = [
                        Item(title="Nessun Elemento Da Visualizzare",
                             thumbnail=os.path.join(
                                 plugintools.get_runtime_path(), "resources",
                                 "images", "thumb_error.png"))
                    ]

    except:
        import traceback
        plugintools.log("navigation.get_next_items " + traceback.format_exc())
        itemlist = [
            Item(title="Rimozione Effettuata - Riavviare",
                 thumbnail=os.path.join(plugintools.get_runtime_path(),
                                        "resources", "images",
                                        "thumb_error.png"))
        ]

    return itemlist
Esempio n. 6
0
def play(url, is_view=None):

    # -- Necesario para algunas webs -------------------------- -
    if not url.endswith(".torrent") and not url.startswith("magnet"):
        t_file = scrapertools.get_header_from_response(url,header_to_get="location")
        if len(t_file) > 0:
            url = t_file
            t_file = scrapertools.get_header_from_response(url,header_to_get="location")
        if len(t_file) > 0:
            url = t_file

    # -- Crear dos carpetas en descargas para los archivos ------
    save_path_videos = os.path.join( config.get_setting("downloadpath") , "torrent-videos" )
    save_path_torrents = os.path.join( config.get_setting("downloadpath") , "torrent-torrents" )
    if not os.path.exists( save_path_torrents ): os.mkdir(save_path_torrents)

    # -- Usar - archivo torrent desde web, meagnet o HD ---------
    if not os.path.isfile(url) and not url.startswith("magnet"):
        # -- http - crear archivo torrent -----------------------
        data = url_get(url)
        # -- El nombre del torrent será el que contiene en los --
        # -- datos.                                             -
        #re_name_len = int( scrapertools.get_match(data,':name(\d+):') )
        re_name = library.title_to_folder_name( urllib.unquote( scrapertools.get_match(data,':name\d+:(.*?)\d+:') ) )
        torrent_file = os.path.join(save_path_torrents, re_name+'.torrent')

        f = open(torrent_file,'wb')
        f.write(data)
        f.close()
    elif os.path.isfile(url):
        # -- file - para usar torrens desde el HD ---------------
        torrent_file = url
    else:
        # -- magnet ---------------------------------------------
        torrent_file = url
    # -----------------------------------------------------------

    # -- MCT - MiniClienteTorrent -------------------------------
    ses = lt.session()

    print "#########################"
    print lt.version
    print "#########################"

    ses.add_dht_router("router.bittorrent.com",6881)
    ses.add_dht_router("router.utorrent.com",6881)
    ses.add_dht_router("router.bitcomet.com",554)
    ses.add_dht_router("dht.transmissionbt.com",6881)

    trackers = [
        "http://exodus.desync.com:6969/announce",
        "udp://tracker.publicbt.com:80/announce",
        "udp://tracker.openbittorrent.com:80/announce",
        "http://tracker.torrentbay.to:6969/announce",
        "http://fr33dom.h33t.com:3310/announce",
        "http://tracker.pow7.com/announce",
        "udp://tracker.ccc.de:80/announce",
        "http://tracker.bittorrent.am:80/announce",
        "http://denis.stalker.h3q.com:6969/announce",
        "udp://tracker.prq.to:80/announce",
        "udp://tracker.istole.it:80/announce",
        "udp://open.demonii.com:1337",

        "http://9.rarbg.com:2710/announce",
        "http://announce.torrentsmd.com:6969/announce",
        "http://bt.careland.com.cn:6969/announce",
        "http://explodie.org:6969/announce",
        "http://mgtracker.org:2710/announce",
        "http://tracker.best-torrents.net:6969/announce",
        "http://tracker.tfile.me/announce",
        "http://tracker.torrenty.org:6969/announce",
        "http://tracker1.wasabii.com.tw:6969/announce",
        "udp://9.rarbg.com:2710/announce",
        "udp://9.rarbg.me:2710/announce",
        "udp://coppersurfer.tk:6969/announce",
        "udp://tracker.btzoo.eu:80/announce",

        "http://www.spanishtracker.com:2710/announce",
        "http://www.todotorrents.com:2710/announce",
    ]

    video_file = ""
    ## -- magnet2torrent ----------------------------------------
    if torrent_file.startswith("magnet"):
        tempdir = tempfile.mkdtemp()
        params = {
            'save_path': tempdir,
            'trackers':trackers,
            'storage_mode': lt.storage_mode_t.storage_mode_allocate,
            'paused': False,
            'auto_managed': True,
            'duplicate_is_error': True
        }
        h = lt.add_magnet_uri(ses, torrent_file, params)
        dp = xbmcgui.DialogProgress()
        dp.create('pelisalacarta-MCT')
        while not h.has_metadata():
            message, porcent, msg_file, s, download = getProgress(h, "Creando torrent desde magnet")
            dp.update(porcent, message, msg_file)
        dp.close()
        info = h.get_torrent_info()
        data = lt.bencode( lt.create_torrent(info).generate() )
        torrent_file = os.path.join(save_path_torrents, info.name() + ".torrent")
        f = open(torrent_file,'wb')
        f.write(data)
        f.close()
        ses.remove_torrent(h)
        shutil.rmtree(tempdir)
    # -----------------------------------------------------------

    # -- Archivos torrent ---------------------------------------
    e = lt.bdecode(open(torrent_file, 'rb').read())
    info = lt.torrent_info(e)

    # -- El más gordo o uno de los más gordo se entiende que es -
    # -- el vídeo o es el vídeo que se usará como referencia    -
    # -- para el tipo de archivo                                -
    _index_file, _video_file, _size_file = get_video_file(info)

    if not _video_file.endswith('.avi'):
        print "##### storage_mode_t.storage_mode_sparse (no avi) #####"
        h = ses.add_torrent( { 'ti':info, 'save_path': save_path_videos, 'trackers':trackers, 'storage_mode':lt.storage_mode_t.storage_mode_sparse } )
    else:
        print "##### storage_mode_t.storage_mode_allocate (avi) #####"
        h = ses.add_torrent( { 'ti':info, 'save_path': save_path_videos, 'trackers':trackers, 'storage_mode':lt.storage_mode_t.storage_mode_allocate } )
    ## ----------------------------------------------------------

    # -- Prioritarizar ------------------------------------------
    _index, video_file, video_size = get_video_files_sizes( info )
    if _index == -1:
        _index = _index_file
        video_file = _video_file
        video_size = _size_file

    piece_set = set_priority_pieces(h, _index, video_file, video_size, _log=True)

    # -- Descarga secuencial - trozo 1, trozo 2, ... ------------
    #h.set_sequential_download(True)

    h.force_reannounce()
    h.force_dht_announce()

    # -- Crear diálogo de progreso para el primer bucle ---------
    dp = xbmcgui.DialogProgress()
    dp.create('pelisalacarta-MCT')

    # -- Para log -----------------------------------------------
    timer = time.time()

    # -- Local con el número de piezas por cluster global -------
    _cluster_pieces = __pieces__

    '''
    # -- Estimar cuando se comenzará el visionado ---------------
    # -- Pruebas: Porcentaje fijo                               -
    porcentage_to_play = 1.50
    '''

    # -- Estimar cuando se comenzará el visionado ---------------
    # -- Pruebas: Porcentaje segun tamaño cuando sólo hay un    -
    # -- vídeo en torrent                                       -
    porcentage_to_play = set_porcentage_to_play(video_size)

    # -- Doble bucle anidado ------------------------------------
    # -- Descarga - Primer bucle                                -
    while not h.is_seed():
        s = h.status()

        xbmc.sleep(100)

        # -- Recuperar los datos del progreso -------------------
        message, porcent, msg_file, s, download = getProgress(h, video_file)

        # -- Si hace 'checking' existe descarga -----------------
        # -- 'download' Se usará para saber si hay datos        -
        # -- descargados para el diálogo de 'remove_files'      -
        if s.state == 1: download = 1

        # -- Añadido: Log para las pruebas ----------------------
        # -- Print log have_piece. Procedimiento al final del   -
        # -- archivo                                            -
        timer2 = time.time() - timer
        if timer2 > time_sleep:
            print_have_piece_set(h, piece_set)
            timer = time.time()

            # -- Print log y procedimiento incrementar cluster --
            # -- Parte 1                                        -
            _cluster = False
            if _cluster_pieces < len(piece_set):
                _cluster = \
                    cluster_stat(
                        h,
                        piece_set[_cluster_pieces - __pieces__],
                        piece_set[_cluster_pieces],
                        _log=True
                    )
            else: _cluster_pieces = len(piece_set) -1
            # -- Parte 2                                        -
            if _cluster:
                _cluster_pieces+= __pieces__
                cluster_set(h, _cluster_pieces, piece_set, 7, _log=True)

                _cluster_pieces2 = _cluster_pieces + __pieces__
                cluster_set(h, _cluster_pieces2, piece_set, 6, _log=True)

                _cluster_pieces3 = _cluster_pieces2 + __pieces__
                cluster_set(h, _cluster_pieces3, piece_set, 5, _log=True)

        # -- Player - play --------------------------------------
        option_view = ( (s.progress * 100) >= porcentage_to_play )

        # -- Modificado: Se tendrá en cuenta el primer cluster --
        # -- completado para el inicio de la reproducción       -
        first_cluster = True
        _p = "##### first_cluster: "
        for i in range( piece_set[0], piece_set[__pieces__] ):
            _p+= "[%s:%s]" % ( i, h.have_piece(i) )
            first_cluster&= h.have_piece(i)
        print _p

        if (option_view and is_view != "Ok" and s.state == 3 and first_cluster ):
            print "##### porcentage_to_play ## %s ##" % porcentage_to_play

            is_view = "Ok"
            dp.close()

            # -- Player - Ver el vídeo --------------------------
            player = play_video()
            player.play( os.path.join( save_path_videos, video_file ) )

            # -- Segundo bucle - Player - Control de eventos ----
            while player.isPlaying():
                xbmc.sleep(100)

                # -- Añadido: Log para las pruebas --------------
                # -- Print log have_piece. Procedimiento al     -
                # -- final del archivo                          -
                timer2 = time.time() - timer
                if timer2 > time_sleep:
                    print_have_piece_set(h, piece_set)
                    timer = time.time()

                    # -- Print log y procedimiento incrementar --
                    # -- cluster                                -
                    # -- Parte 1                                -
                    _cluster = False
                    if _cluster_pieces < len(piece_set):
                        _cluster = \
                            cluster_stat(
                                h,
                                piece_set[_cluster_pieces - __pieces__],
                                piece_set[_cluster_pieces],
                                _log=True
                            )
                    else: _cluster_pieces = len(piece_set) -1
                    # -- Parte 2                                -
                    if _cluster:
                        _cluster_pieces+= __pieces__
                        cluster_set(h, _cluster_pieces, piece_set, 7, _log=True)

                        _cluster_pieces2 = _cluster_pieces + __pieces__
                        cluster_set(h, _cluster_pieces2, piece_set, 6, _log=True)

                        _cluster_pieces3 = _cluster_pieces2 + __pieces__
                        cluster_set(h, _cluster_pieces3, piece_set, 5, _log=True)

                # -- Cerrar el diálogo de progreso --------------
                if player.resumed:
                    dp.close()

                # -- Mostrar el diálogo de progreso -------------
                if player.paused:
                    # -- Crear diálogo si no existe -------------
                    if not player.statusDialogoProgress:
                        dp = xbmcgui.DialogProgress()
                        dp.create('pelisalacarta-MCT')
                        player.setDialogoProgress()

                    # -- Diálogos de estado en el visionado -----
                    if not h.is_seed():
                        # -- Recuperar los datos del progreso ---
                        message, porcent, msg_file, s, download = getProgress(h, video_file)
                        dp.update(porcent, message, msg_file)
                    else:
                        dp.update(100, "Descarga completa: " + video_file)

                    # -- Se canceló el progreso en el visionado -
                    # -- Continuar                              -
                    if dp.iscanceled():
                        dp.close()
                        player.pause()

                    # -- El usuario cancelo el visionado --------
                    # -- Terminar                               -
                    if player.ended:
                        if info.num_files() > 1:
                            _index, video_file, video_size = get_video_files_sizes( info )					
                            if _index == -1:
                                # -- Diálogo eliminar archivos ----------
                                remove_files( download, torrent_file, video_file, ses, h )
                                return
                            else:
                                set_porcentage_to_play(video_size)
                                piece_set = set_priority_pieces(h, _index, video_file, video_size, _log=True)
                        else:
                                # -- Diálogo eliminar archivos ----------
                                remove_files( download, torrent_file, video_file, ses, h )
                                return

        # -- Kodi - Se cerró el visionado -----------------------
        # -- Continuar | Terminar                               -
        if is_view == "Ok" and not xbmc.Player().isPlaying():

            # -- Diálogo continuar o terminar -------------------
            d = xbmcgui.Dialog()
            ok = d.yesno('pelisalacarta-MCT', 'XBMC-Kodi Cerró el vídeo.', '¿Continuar con la sesión?')

            # -- SI -------------------------------------------------
            if ok:
                # -- Continuar --------------------------------------
                is_view=None
            else:
                # -- Terminar ---------------------------------------
                if info.num_files() > 1:	
                    _index, video_file, video_size = get_video_files_sizes( info )			
                    if _index == -1:
                        # -- Diálogo eliminar archivos                      -
                        remove_files( download, torrent_file, video_file, ses, h )
                        return
                    else:
                        set_porcentage_to_play(video_size)
                        piece_set = set_priority_pieces(h, _index, video_file, video_size, _log=True)
                        is_view=None
                        dp = xbmcgui.DialogProgress()
                        dp.create('pelisalacarta-MCT')
                else:
                    # -- Diálogo eliminar archivos ----------
                    remove_files( download, torrent_file, video_file, ses, h )
                    return

        # -- Mostar progeso antes del visionado -----------------
        if is_view != "Ok" :
            dp.update(porcent, message, msg_file)

        # -- Se canceló el progreso antes del visionado ---------
        # -- Terminar                                           -
        if dp.iscanceled():
            dp.close()
            if info.num_files( )> 1:	
                _index, video_file, video_size = get_video_files_sizes( info )			
                if _index == -1:
                    # -- Diálogo eliminar archivos                      -
                    remove_files( download, torrent_file, video_file, ses, h )
                    return
                else:
                    set_porcentage_to_play(video_size)
                    piece_set = set_priority_pieces(h, _index, video_file, video_size, _log=True)
                    is_view=None
                    dp = xbmcgui.DialogProgress()
                    dp.create('pelisalacarta-MCT')
            else:
                # -- Diálogo eliminar archivos ----------
                remove_files( download, torrent_file, video_file, ses, h )
                return

    # -- Kodi - Error? - No debería llegar aquí -----------------
    if is_view == "Ok" and not xbmc.Player().isPlaying():
        dp.close()
        # -- Diálogo eliminar archivos --------------------------
        remove_files( download, torrent_file, video_file, ses, h )

    return
def run():
    logger.info("streamondemand-pureita.platformcode.launcher 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(
        "streamondemand-pureita.platformcode.launcher 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(params, url, category)

        # Actualizar version
        elif action == "update":
            try:
                from core import updater

                updater.update(params)
            except ImportError:
                logger.info("streamondemand-pureita.platformcode.launcher 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")

        elif action == "channeltypes":
            import channelselector as plugin

            plugin.channeltypes(params, url, category)

        elif action == "categories":
            import channelselector as plugin

            plugin.categories(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 streamondemand-pureita
            regular_channel_path = os.path.join(config.get_runtime_path(), "channels", channel_name + ".py")
            core_channel_path = os.path.join(config.get_runtime_path(), "core", channel_name + ".py")
            logger.info("streamondemand-pureita.platformcode.launcher regular_channel_path=%s" % regular_channel_path)
            logger.info("streamondemand-pureita.platformcode.launcher core_channel_path=%s" % core_channel_path)

            if (
                channel_name == "personal"
                or channel_name == "personal2"
                or channel_name == "personal3"
                or channel_name == "personal4"
                or channel_name == "personal5"
            ):
                import channels.personal as channel
            elif os.path.exists(regular_channel_path):
                exec "import channels." + channel_name + " as channel"
            elif os.path.exists(core_channel_path):
                exec "from core import " + channel_name + " as channel"

            logger.info(
                "streamondemand-pureita.platformcode.launcher 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("streamondemand-pureita.platformcode.launcher xbmc native channel")
                if action == "strm":
                    from platformcode import xbmctools

                    xbmctools.playstrm(params, url, category)
                else:
                    exec "channel." + action + "(params, url, category)"
            else:
                logger.info("streamondemand-pureita.platformcode.launcher 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("streamondemand-pureita.platformcode.launcher 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("streamondemand-pureita.platformcode.launcher No subtitle")
                """
                from platformcode import xbmctools

                if action == "play":
                    logger.info("streamondemand-pureita.platformcode.launcher play")
                    # Si el canal tiene una acción "play" tiene prioridad
                    if hasattr(channel, "play"):
                        logger.info("streamondemand-pureita.platformcode.launcher 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(
                            "streamondemand-pureita.platformcode.launcher 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("streamondemand-pureita.platformcode.launcher 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 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("streamondemand-pureita.platformcode.launcher add_pelicula_to_library")
                    from platformcode 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(
                        "streamondemand-pureita.platformcode.launcher add_serie_to_library, show=#" + item.show + "#"
                    )
                    from platformcode 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("streamondemand-pureita", "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)
                        logger.info(
                            "streamondemand-pureita.platformcode.launcher add_serie_to_library, title=" + 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 que dice "Añadir esta serie..." o "Descargar esta serie..."
                            if item.action != "add_serie_to_library" and item.action != "download_all_episodes":
                                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(
                                "streamondemand-pureita.platformcode.launcher Error al grabar el archivo " + item.title
                            )
                            errores = errores + 1

                    pDialog.close()

                    # Actualizacion de la biblioteca
                    itemlist = []
                    if errores > 0:
                        itemlist.append(
                            Item(
                                title="ERRORE, la serie NON si è aggiunta alla biblioteca o la fatto in modo incompleto"
                            )
                        )
                        logger.info("[launcher.py] No se pudo añadir " + str(errores) + " episodios")
                    else:
                        itemlist.append(Item(title="La serie è stata aggiunta alla 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_library_path(), "series.xml")
                    if not os.path.exists(nombre_fichero_config_canal):
                        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)
                    from platformcode import library

                    f.write(library.title_to_folder_name(item.show) + "," + item.url + "," + item.channel + "\n")
                    f.close()

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

                elif action == "search":
                    logger.info("streamondemand-pureita.platformcode.launcher 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(
                        "streamondemand-pureita.platformcode.launcher 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(
                                "streamondemand-pureita.platformcode.launcher no channel 'findvideos' method, executing core method"
                            )
                            from servers import servertools

                            itemlist = servertools.find_video_items(item)

                        from platformcode 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)
Esempio n. 8
0
def add_serie_to_library(item):
    logger.info(
        "pelisalacarta.platformcode.launcher add_serie_to_library, show=#" +
        item.show + "#")
    from platformcode import library

    # 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 = xplatformtools.dialog_progress('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)
        logger.info(
            "pelisalacarta.platformcode.launcher add_serie_to_library, title="
            + 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 que dice "Añadir esta serie..." o "Descargar esta serie..."
            if item.action != "add_serie_to_library" and item.action != "download_all_episodes":
                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(
                "pelisalacarta.platformcode.launcherError 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_library_path(),
                                               "series.xml")
    if not os.path.exists(nombre_fichero_config_canal):
        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)
    from platformcode import library
    f.write(
        library.title_to_folder_name(item.show) + "," + item.url + "," +
        item.channel + "\n")
    f.close()
Esempio n. 9
0
def add_serie_to_library(item):
    logger.info("pelisalacarta.platformcode.launcher add_serie_to_library, show=#"+item.show+"#")
    from platformcode import library
    

    # 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 = xplatformtools.dialog_progress('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)
        logger.info("pelisalacarta.platformcode.launcher add_serie_to_library, title="+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 que dice "Añadir esta serie..." o "Descargar esta serie..."
            if item.action!="add_serie_to_library" and item.action!="download_all_episodes":
                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("pelisalacarta.platformcode.launcherError 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_library_path() , "series.xml" )
    if not os.path.exists(nombre_fichero_config_canal):
        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)
    from platformcode import library
    f.write( library.title_to_folder_name(item.show)+","+item.url+","+item.channel+"\n")
    f.close();
def run():
    logger.info("streamondemand.platformcode.launcher 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(
        "streamondemand.platformcode.launcher 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(params, url, category)

        # Actualizar version
        elif (action == "update"):
            try:
                from core import updater
                updater.update(params)
            except ImportError:
                logger.info(
                    "streamondemand.platformcode.launcher 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")

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

        elif (action == "categories"):
            import channelselector as plugin
            plugin.categories(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(),
                                                'channels',
                                                channel_name + ".py")
            core_channel_path = os.path.join(config.get_runtime_path(), 'core',
                                             channel_name + ".py")
            logger.info(
                "streamondemand.platformcode.launcher regular_channel_path=%s"
                % regular_channel_path)
            logger.info(
                "streamondemand.platformcode.launcher core_channel_path=%s" %
                core_channel_path)

            if channel_name == "personal" or channel_name == "personal2" or channel_name == "personal3" or channel_name == "personal4" or channel_name == "personal5":
                import channels.personal as channel
            elif os.path.exists(regular_channel_path):
                exec "import channels." + channel_name + " as channel"
            elif os.path.exists(core_channel_path):
                exec "from core import " + channel_name + " as channel"

            logger.info(
                "streamondemand.platformcode.launcher 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(
                    "streamondemand.platformcode.launcher xbmc native channel")
                if (action == "strm"):
                    from platformcode import xbmctools
                    xbmctools.playstrm(params, url, category)
                else:
                    exec "channel." + action + "(params, url, category)"
            else:
                logger.info(
                    "streamondemand.platformcode.launcher 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("streamondemand.platformcode.launcher 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("streamondemand.platformcode.launcher No subtitle")
                '''
                from platformcode import xbmctools

                if action == "play":
                    logger.info("streamondemand.platformcode.launcher play")
                    # Si el canal tiene una acción "play" tiene prioridad
                    if hasattr(channel, 'play'):
                        logger.info(
                            "streamondemand.platformcode.launcher 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",
                                                  "Niente da riprodurre")
                    else:
                        logger.info(
                            "streamondemand.platformcode.launcher 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(
                        "streamondemand.platformcode.launcher 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 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(
                        "streamondemand.platformcode.launcher add_pelicula_to_library"
                    )
                    from platformcode 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(
                        "streamondemand.platformcode.launcher add_serie_to_library, show=#"
                        + item.show + "#")
                    from platformcode 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('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)
                        logger.info(
                            "streamondemand.platformcode.launcher add_serie_to_library, title="
                            + 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 que dice "Añadir esta serie..." o "Descargar esta serie..."
                            if item.action != "add_serie_to_library" and item.action != "download_all_episodes":
                                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(
                                "streamondemand.platformcode.launcher Error al grabar el archivo "
                                + item.title)
                            errores = errores + 1

                    pDialog.close()

                    # Actualizacion de la biblioteca
                    itemlist = []
                    if errores > 0:
                        itemlist.append(
                            Item(
                                title=
                                "ERRORE, la serie NON si è aggiunta alla biblioteca o la fatto in modo incompleto"
                            ))
                        logger.info("[launcher.py] No se pudo añadir " +
                                    str(errores) + " episodios")
                    else:
                        itemlist.append(
                            Item(title=
                                 "La serie è stata aggiunta alla 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_library_path(), "series.xml")
                    if not os.path.exists(nombre_fichero_config_canal):
                        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)
                    from platformcode import library
                    f.write(
                        library.title_to_folder_name(item.show) + "," +
                        item.url + "," + item.channel + "\n")
                    f.close()

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

                elif action == "search":
                    logger.info("streamondemand.platformcode.launcher 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(
                        "streamondemand.platformcode.launcher 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(
                                "streamondemand.platformcode.launcher no channel 'findvideos' method, executing core method"
                            )
                            from servers import servertools
                            itemlist = servertools.find_video_items(item)

                        from platformcode 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: %s , 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)
def get_next_items( item ):

    plugintools.log("navigation.get_next_items item="+item.tostring())

    try:
        # ----------------------------------------------------------------
        #  Main menu
        # ----------------------------------------------------------------
        if item.channel=="navigation":
		            # --- Update channels list ---------------------------------------
            from core import config
            if item.action=="mainlist":
                plugintools.log("navigation.get_next_items Main menu")

                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
            # ----------------------------------------------------------------

            if item.action=="mainlist":
                plugintools.log("navigation.get_next_items Main menu")
                itemlist = channelselector.getmainlist("bannermenu")

        elif item.channel=="channelselector":

            if item.action=="channeltypes":
                plugintools.log("navigation.get_next_items Channel types menu")
                itemlist = channelselector.getchanneltypes("bannermenu")

            elif item.action=="listchannels":
                plugintools.log("navigation.get_next_items Channel list menu")
                itemlist = channelselector.filterchannels(item.category,"bannermenu")

        elif item.channel=="configuracion":
            plugintools.open_settings_dialog()
            return []

        else:

            if item.action=="":
                item.action="mainlist"

            plugintools.log("navigation.get_next_items Channel code ("+item.channel+"."+item.action+")")

            # --- Update channels files --------------------------------------
            if item.action=="mainlist":
                from core import config
                if config.get_setting("updatechannels")=="true":
                    try:
                        from core import updater
                        actualizado = updater.updatechannel(item.channel)

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

            try:
                exec "import channels."+item.channel+" as channel"
            except:
                exec "import core."+item.channel+" as channel"

            from platformcode import xbmctools

            if item.action=="play":
                plugintools.log("navigation.get_next_items play")

                # Si el canal tiene una acción "play" tiene prioridad
                if hasattr(channel, 'play'):
                    plugintools.log("streamondemand-pureita.navigation.py Channel has its own 'play' method")
                    itemlist = channel.play(item)
                    if len(itemlist)>0:
                        item = itemlist[0]

                        # FIXME: Este error ha que tratarlo de otra manera, al dar a volver sin ver el vídeo falla
                        try:
                            xbmctools.play_video(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=item.fulltitle, Serie=item.show)
                        except:
                            pass

                    else:
                        import xbmcgui
                        ventana_error = xbmcgui.Dialog()
                        ok = ventana_error.ok ("plugin", "No hay nada para reproducir")
                else:
                    plugintools.log("streamondemand-pureita.navigation.py No channel 'play' method, executing core method")

                    # FIXME: Este error ha que tratarlo de otra manera, por al dar a volver sin ver el vídeo falla
                    # Mejor hacer el play desde la ventana
                    try:
                        xbmctools.play_video(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=item.fulltitle, Serie=item.show)
                    except:
                        pass


                return []

            elif item.action=="findvideos":
                plugintools.log("navigation.get_next_items findvideos")

                # Si el canal tiene una acción "findvideos" tiene prioridad
                if hasattr(channel, 'findvideos'):
                    plugintools.log("streamondemand-pureita.navigation.py Channel has its own 'findvideos' method")
                    itemlist = channel.findvideos(item)
                else:
                    itemlist = []

                if len(itemlist)==0:
                    from servers import servertools
                    itemlist = servertools.find_video_items(item)

                if len(itemlist)==0:
                    itemlist = [ Item(title="No se han encontrado vídeos", thumbnail=os.path.join( plugintools.get_runtime_path() , "resources" , "images" , "thumb_error.png" )) ]
            # ---------------add_serie_to_library-----------
            elif item.action=="add_serie_to_library":
                plugintools.log("navigation.get_next_items add_serie_to_library")
                from platformcode 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('streamondemand-pureita', 'Añadiendo episodios...')
                pDialog.update(0, 'Añadiendo episodio...')
                totalepisodes = len(itemlist)
                plugintools.log ("navigation.get_next_items 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)
                    plugintools.log("streamondemand-pureita.navigation.py add_serie_to_library, title="+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 que dice "Añadir esta serie..." o "Descargar esta serie..."
                        if item.action!="add_serie_to_library" and item.action!="download_all_episodes":
                            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 )
                        plugintools.log("streamondemand-pureita.navigation.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="ERRORE, la serie NON si è aggiunta alla biblioteca o la fatto in modo incompleto"))
                    plugintools.log ("navigation.get_next_items No se pudo añadir "+str(errores)+" episodios")
                else:
                    itemlist.append(Item(title="La serie è stata aggiunta alla biblioteca"))
                    plugintools.log ("navigation.get_next_items 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
                from core import config
                nombre_fichero_config_canal = os.path.join( config.get_library_path() , "series.xml" )
                if not os.path.exists(nombre_fichero_config_canal):
                    nombre_fichero_config_canal = os.path.join( config.get_data_path() , "series.xml" )

                plugintools.log("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)
                from platformcode import library
                f.write( library.title_to_folder_name(item.show)+","+item.url+","+item.channel+"\n")
                f.close();
                return itemlist
            # --------------------------------------------------------------------
            elif item.action=="download_all_episodes":
                plugintools.log("navigation.get_next_items download_all_episodes")
                download_all_episodes(item,channel)
			#---------------------------------------------------------------------
            else:

                if item.action=="search":
                    tecleado = plugintools.keyboard_input()
                    if tecleado!="":
                        tecleado = tecleado.replace(" ", "+")
                        itemlist = channel.search(item,tecleado)
                elif item.channel=="novedades" and item.action=="mainlist":
                    itemlist = channel.mainlist(item,"bannermenu")
                elif item.channel=="buscador" and item.action=="mainlist":
                    itemlist = channel.mainlist(item,"bannermenu")
                else:
                    exec "itemlist = channel."+item.action+"(item)"

                for loaded_item in itemlist:

                    if loaded_item.thumbnail=="":
                        if loaded_item.folder:
                            loaded_item.thumbnail = os.path.join( plugintools.get_runtime_path() , "resources" , "images" , "thumb_folder.png" )
                        else:
                            loaded_item.thumbnail = os.path.join( plugintools.get_runtime_path() , "resources" , "images" , "thumb_nofolder.png" )

                if len(itemlist)==0:
                    itemlist = [ Item(title="No hay elementos para mostrar", thumbnail=os.path.join( plugintools.get_runtime_path() , "resources" , "images" , "thumb_error.png" )) ]

    except:
        import traceback
        plugintools.log("navigation.get_next_items "+traceback.format_exc())
        itemlist = [ Item(title="Se ha producido un error", thumbnail=os.path.join( plugintools.get_runtime_path() , "resources" , "images" , "thumb_error.png" )) ]


    return itemlist
Esempio n. 12
0
def play(url, is_view=None):

    # -- Necesario para algunas webs -------------------------- -
    if not url.endswith(".torrent") and not url.startswith("magnet"):
        t_file = scrapertools.get_header_from_response(
            url, header_to_get="location")
        if len(t_file) > 0:
            url = t_file
            t_file = scrapertools.get_header_from_response(
                url, header_to_get="location")
        if len(t_file) > 0:
            url = t_file

    # -- Crear dos carpetas en descargas para los archivos ------
    save_path_videos = os.path.join(config.get_setting("downloadpath"),
                                    "torrent-videos")
    save_path_torrents = os.path.join(config.get_setting("downloadpath"),
                                      "torrent-torrents")
    if not os.path.exists(save_path_torrents): os.mkdir(save_path_torrents)

    # -- Usar - archivo torrent desde web, meagnet o HD ---------
    if not os.path.isfile(url) and not url.startswith("magnet"):
        # -- http - crear archivo torrent -----------------------
        data = url_get(url)
        # -- El nombre del torrent será el que contiene en los --
        # -- datos.                                             -
        #re_name_len = int( scrapertools.get_match(data,':name(\d+):') )
        re_name = library.title_to_folder_name(
            urllib.unquote(scrapertools.get_match(data, ':name\d+:(.*?)\d+:')))
        torrent_file = os.path.join(save_path_torrents, re_name + '.torrent')

        f = open(torrent_file, 'wb')
        f.write(data)
        f.close()
    elif os.path.isfile(url):
        # -- file - para usar torrens desde el HD ---------------
        torrent_file = url
    else:
        # -- magnet ---------------------------------------------
        torrent_file = url
    # -----------------------------------------------------------

    # -- MCT - MiniClienteTorrent -------------------------------
    ses = lt.session()

    print "#########################"
    print lt.version
    print "#########################"

    ses.add_dht_router("router.bittorrent.com", 6881)
    ses.add_dht_router("router.utorrent.com", 6881)
    ses.add_dht_router("router.bitcomet.com", 554)
    ses.add_dht_router("dht.transmissionbt.com", 6881)

    trackers = [
        "http://exodus.desync.com:6969/announce",
        "udp://tracker.publicbt.com:80/announce",
        "udp://tracker.openbittorrent.com:80/announce",
        "http://tracker.torrentbay.to:6969/announce",
        "http://fr33dom.h33t.com:3310/announce",
        "http://tracker.pow7.com/announce",
        "udp://tracker.ccc.de:80/announce",
        "http://tracker.bittorrent.am:80/announce",
        "http://denis.stalker.h3q.com:6969/announce",
        "udp://tracker.prq.to:80/announce",
        "udp://tracker.istole.it:80/announce",
        "udp://open.demonii.com:1337",
        "http://9.rarbg.com:2710/announce",
        "http://announce.torrentsmd.com:6969/announce",
        "http://bt.careland.com.cn:6969/announce",
        "http://explodie.org:6969/announce",
        "http://mgtracker.org:2710/announce",
        "http://tracker.best-torrents.net:6969/announce",
        "http://tracker.tfile.me/announce",
        "http://tracker.torrenty.org:6969/announce",
        "http://tracker1.wasabii.com.tw:6969/announce",
        "udp://9.rarbg.com:2710/announce",
        "udp://9.rarbg.me:2710/announce",
        "udp://coppersurfer.tk:6969/announce",
        "udp://tracker.btzoo.eu:80/announce",
        "http://www.spanishtracker.com:2710/announce",
        "http://www.todotorrents.com:2710/announce",
    ]

    video_file = ""
    ## -- magnet2torrent ----------------------------------------
    if torrent_file.startswith("magnet"):
        tempdir = tempfile.mkdtemp()
        params = {
            'save_path': tempdir,
            'trackers': trackers,
            'storage_mode': lt.storage_mode_t.storage_mode_allocate,
            'paused': False,
            'auto_managed': True,
            'duplicate_is_error': True
        }
        h = lt.add_magnet_uri(ses, torrent_file, params)
        dp = xbmcgui.DialogProgress()
        dp.create('pelisalacarta-MCT')
        while not h.has_metadata():
            message, porcent, msg_file, s, download = getProgress(
                h, "Creando torrent desde magnet")
            dp.update(porcent, message, msg_file)
        dp.close()
        info = h.get_torrent_info()
        data = lt.bencode(lt.create_torrent(info).generate())
        torrent_file = os.path.join(save_path_torrents,
                                    info.name() + ".torrent")
        f = open(torrent_file, 'wb')
        f.write(data)
        f.close()
        ses.remove_torrent(h)
        shutil.rmtree(tempdir)
    # -----------------------------------------------------------

    # -- Archivos torrent ---------------------------------------
    e = lt.bdecode(open(torrent_file, 'rb').read())
    info = lt.torrent_info(e)

    # -- El más gordo o uno de los más gordo se entiende que es -
    # -- el vídeo o es el vídeo que se usará como referencia    -
    # -- para el tipo de archivo                                -
    _index_file, _video_file, _size_file = get_video_file(info)

    if not _video_file.endswith('.avi'):
        print "##### storage_mode_t.storage_mode_sparse (no avi) #####"
        h = ses.add_torrent({
            'ti':
            info,
            'save_path':
            save_path_videos,
            'trackers':
            trackers,
            'storage_mode':
            lt.storage_mode_t.storage_mode_sparse
        })
    else:
        print "##### storage_mode_t.storage_mode_allocate (avi) #####"
        h = ses.add_torrent({
            'ti':
            info,
            'save_path':
            save_path_videos,
            'trackers':
            trackers,
            'storage_mode':
            lt.storage_mode_t.storage_mode_allocate
        })
    ## ----------------------------------------------------------

    # -- Prioritarizar ------------------------------------------
    _index, video_file, video_size = get_video_files_sizes(info)
    if _index == -1:
        _index = _index_file
        video_file = _video_file
        video_size = _size_file

    piece_set = set_priority_pieces(h,
                                    _index,
                                    video_file,
                                    video_size,
                                    _log=True)

    # -- Descarga secuencial - trozo 1, trozo 2, ... ------------
    #h.set_sequential_download(True)

    h.force_reannounce()
    h.force_dht_announce()

    # -- Crear diálogo de progreso para el primer bucle ---------
    dp = xbmcgui.DialogProgress()
    dp.create('pelisalacarta-MCT')

    # -- Para log -----------------------------------------------
    timer = time.time()

    # -- Local con el número de piezas por cluster global -------
    _cluster_pieces = __pieces__
    '''
    # -- Estimar cuando se comenzará el visionado ---------------
    # -- Pruebas: Porcentaje fijo                               -
    porcentage_to_play = 1.50
    '''

    # -- Estimar cuando se comenzará el visionado ---------------
    # -- Pruebas: Porcentaje segun tamaño cuando sólo hay un    -
    # -- vídeo en torrent                                       -
    porcentage_to_play = set_porcentage_to_play(video_size)

    # -- Doble bucle anidado ------------------------------------
    # -- Descarga - Primer bucle                                -
    while not h.is_seed():
        s = h.status()

        xbmc.sleep(100)

        # -- Recuperar los datos del progreso -------------------
        message, porcent, msg_file, s, download = getProgress(h, video_file)

        # -- Si hace 'checking' existe descarga -----------------
        # -- 'download' Se usará para saber si hay datos        -
        # -- descargados para el diálogo de 'remove_files'      -
        if s.state == 1: download = 1

        # -- Añadido: Log para las pruebas ----------------------
        # -- Print log have_piece. Procedimiento al final del   -
        # -- archivo                                            -
        timer2 = time.time() - timer
        if timer2 > time_sleep:
            print_have_piece_set(h, piece_set)
            timer = time.time()

            # -- Print log y procedimiento incrementar cluster --
            # -- Parte 1                                        -
            _cluster = False
            if _cluster_pieces < len(piece_set):
                _cluster = \
                    cluster_stat(
                        h,
                        piece_set[_cluster_pieces - __pieces__],
                        piece_set[_cluster_pieces],
                        _log=True
                    )
            else:
                _cluster_pieces = len(piece_set) - 1
            # -- Parte 2                                        -
            if _cluster:
                _cluster_pieces += __pieces__
                cluster_set(h, _cluster_pieces, piece_set, 7, _log=True)

                _cluster_pieces2 = _cluster_pieces + __pieces__
                cluster_set(h, _cluster_pieces2, piece_set, 6, _log=True)

                _cluster_pieces3 = _cluster_pieces2 + __pieces__
                cluster_set(h, _cluster_pieces3, piece_set, 5, _log=True)

        # -- Player - play --------------------------------------
        option_view = ((s.progress * 100) >= porcentage_to_play)

        # -- Modificado: Se tendrá en cuenta el primer cluster --
        # -- completado para el inicio de la reproducción       -
        first_cluster = True
        _p = "##### first_cluster: "
        for i in range(piece_set[0], piece_set[__pieces__]):
            _p += "[%s:%s]" % (i, h.have_piece(i))
            first_cluster &= h.have_piece(i)
        print _p

        if (option_view and is_view != "Ok" and s.state == 3
                and first_cluster):
            print "##### porcentage_to_play ## %s ##" % porcentage_to_play

            is_view = "Ok"
            dp.close()

            # -- Player - Ver el vídeo --------------------------
            player = play_video()
            player.play(os.path.join(save_path_videos, video_file))

            # -- Segundo bucle - Player - Control de eventos ----
            while player.isPlaying():
                xbmc.sleep(100)

                # -- Añadido: Log para las pruebas --------------
                # -- Print log have_piece. Procedimiento al     -
                # -- final del archivo                          -
                timer2 = time.time() - timer
                if timer2 > time_sleep:
                    print_have_piece_set(h, piece_set)
                    timer = time.time()

                    # -- Print log y procedimiento incrementar --
                    # -- cluster                                -
                    # -- Parte 1                                -
                    _cluster = False
                    if _cluster_pieces < len(piece_set):
                        _cluster = \
                            cluster_stat(
                                h,
                                piece_set[_cluster_pieces - __pieces__],
                                piece_set[_cluster_pieces],
                                _log=True
                            )
                    else:
                        _cluster_pieces = len(piece_set) - 1
                    # -- Parte 2                                -
                    if _cluster:
                        _cluster_pieces += __pieces__
                        cluster_set(h,
                                    _cluster_pieces,
                                    piece_set,
                                    7,
                                    _log=True)

                        _cluster_pieces2 = _cluster_pieces + __pieces__
                        cluster_set(h,
                                    _cluster_pieces2,
                                    piece_set,
                                    6,
                                    _log=True)

                        _cluster_pieces3 = _cluster_pieces2 + __pieces__
                        cluster_set(h,
                                    _cluster_pieces3,
                                    piece_set,
                                    5,
                                    _log=True)

                # -- Cerrar el diálogo de progreso --------------
                if player.resumed:
                    dp.close()

                # -- Mostrar el diálogo de progreso -------------
                if player.paused:
                    # -- Crear diálogo si no existe -------------
                    if not player.statusDialogoProgress:
                        dp = xbmcgui.DialogProgress()
                        dp.create('pelisalacarta-MCT')
                        player.setDialogoProgress()

                    # -- Diálogos de estado en el visionado -----
                    if not h.is_seed():
                        # -- Recuperar los datos del progreso ---
                        message, porcent, msg_file, s, download = getProgress(
                            h, video_file)
                        dp.update(porcent, message, msg_file)
                    else:
                        dp.update(100, "Descarga completa: " + video_file)

                    # -- Se canceló el progreso en el visionado -
                    # -- Continuar                              -
                    if dp.iscanceled():
                        dp.close()
                        player.pause()

                    # -- El usuario cancelo el visionado --------
                    # -- Terminar                               -
                    if player.ended:
                        if info.num_files() > 1:
                            _index, video_file, video_size = get_video_files_sizes(
                                info)
                            if _index == -1:
                                # -- Diálogo eliminar archivos ----------
                                remove_files(download, torrent_file,
                                             video_file, ses, h)
                                return
                            else:
                                set_porcentage_to_play(video_size)
                                piece_set = set_priority_pieces(h,
                                                                _index,
                                                                video_file,
                                                                video_size,
                                                                _log=True)
                        else:
                            # -- Diálogo eliminar archivos ----------
                            remove_files(download, torrent_file, video_file,
                                         ses, h)
                            return

        # -- Kodi - Se cerró el visionado -----------------------
        # -- Continuar | Terminar                               -
        if is_view == "Ok" and not xbmc.Player().isPlaying():

            # -- Diálogo continuar o terminar -------------------
            d = xbmcgui.Dialog()
            ok = d.yesno('pelisalacarta-MCT', 'XBMC-Kodi Cerró el vídeo.',
                         '¿Continuar con la sesión?')

            # -- SI -------------------------------------------------
            if ok:
                # -- Continuar --------------------------------------
                is_view = None
            else:
                # -- Terminar ---------------------------------------
                if info.num_files() > 1:
                    _index, video_file, video_size = get_video_files_sizes(
                        info)
                    if _index == -1:
                        # -- Diálogo eliminar archivos                      -
                        remove_files(download, torrent_file, video_file, ses,
                                     h)
                        return
                    else:
                        set_porcentage_to_play(video_size)
                        piece_set = set_priority_pieces(h,
                                                        _index,
                                                        video_file,
                                                        video_size,
                                                        _log=True)
                        is_view = None
                        dp = xbmcgui.DialogProgress()
                        dp.create('pelisalacarta-MCT')
                else:
                    # -- Diálogo eliminar archivos ----------
                    remove_files(download, torrent_file, video_file, ses, h)
                    return

        # -- Mostar progeso antes del visionado -----------------
        if is_view != "Ok":
            dp.update(porcent, message, msg_file)

        # -- Se canceló el progreso antes del visionado ---------
        # -- Terminar                                           -
        if dp.iscanceled():
            dp.close()
            if info.num_files() > 1:
                _index, video_file, video_size = get_video_files_sizes(info)
                if _index == -1:
                    # -- Diálogo eliminar archivos                      -
                    remove_files(download, torrent_file, video_file, ses, h)
                    return
                else:
                    set_porcentage_to_play(video_size)
                    piece_set = set_priority_pieces(h,
                                                    _index,
                                                    video_file,
                                                    video_size,
                                                    _log=True)
                    is_view = None
                    dp = xbmcgui.DialogProgress()
                    dp.create('pelisalacarta-MCT')
            else:
                # -- Diálogo eliminar archivos ----------
                remove_files(download, torrent_file, video_file, ses, h)
                return

    # -- Kodi - Error? - No debería llegar aquí -----------------
    if is_view == "Ok" and not xbmc.Player().isPlaying():
        dp.close()
        # -- Diálogo eliminar archivos --------------------------
        remove_files(download, torrent_file, video_file, ses, h)

    return