Exemple #1
0
def get_episodios(item):
    logger.info("pelisalacarta.channels.biblioteca get_episodios")
    itemlist = []

    # Obtenemos los archivos de los episodios
    raiz, carpetas_series, ficheros = filetools.walk(item.path).next()

    # Crear un item en la lista para cada strm encontrado
    for i in ficheros:
        # strm
        if i.endswith(".strm"):
            season, episode = scrapertools.get_season_and_episode(i).split("x")
            # Si hay q filtrar por temporada, ignoramos los capitulos de otras temporadas
            if item.filtrar_season and int(season) != int(item.contentSeason):
                continue

            epi = Item().fromurl(filetools.read(filetools.join(raiz, i)))
            epi.contentChannel = item.contentChannel
            epi.path = filetools.join(raiz, i)
            epi.title = i
            epi.channel = "biblioteca"
            epi.action = "findvideos"
            epi.contentEpisodeNumber = episode
            epi.contentSeason = season
            # fix sobreescribe el color del texto si viene pasado en el strm
            epi.text_color = ""
            # fix para que no se ejecute el método de play para la biblioteca de Kodi
            epi.strm = False

            itemlist.append(epi)

        # videos
        elif not i.endswith(".nfo") and not i.endswith(
                ".json") and not i.endswith(".srt"):
            season, episode = scrapertools.get_season_and_episode(i).split("x")
            # Si hay q filtrar por temporada, ignoramos los capitulos de otras temporadas
            if item.filtrar_season and int(season) != int(item.contentSeason):
                continue

            epi = Item()
            epi.contentChannel = "local"
            epi.path = filetools.join(raiz, i)
            epi.title = i
            epi.channel = "biblioteca"
            epi.action = "play"
            epi.contentEpisodeNumber = episode
            epi.contentSeason = season

            itemlist.append(epi)

    library.set_infolabels_from_library(itemlist, tipo="Episodes")
    return sorted(itemlist, key=get_sort_temp_epi)
def get_episodios(item):
    logger.info("pelisalacarta.channels.biblioteca get_episodios")
    itemlist = []

    # Obtenemos los archivos de los episodios
    raiz, carpetas_series, ficheros = filetools.walk(item.path).next()

    # Crear un item en la lista para cada strm encontrado
    for i in ficheros:
        # strm
        if i.endswith(".strm"):
            season, episode = scrapertools.get_season_and_episode(i).split("x")
            # Si hay q filtrar por temporada, ignoramos los capitulos de otras temporadas
            if item.filtrar_season and int(season) != int(item.contentSeason):
                continue

            epi = Item().fromurl(filetools.read(filetools.join(raiz, i)))
            epi.contentChannel = item.contentChannel
            epi.path = filetools.join(raiz, i)
            epi.title = i
            epi.channel = "biblioteca"
            epi.action = "findvideos"
            epi.contentEpisodeNumber = episode
            epi.contentSeason = season
            # fix sobreescribe el color del texto si viene pasado en el strm
            epi.text_color = ""
            # fix para que no se ejecute el método de play para la biblioteca de Kodi
            epi.strm = False

            itemlist.append(epi)

        # videos
        elif not i.endswith(".nfo") and not i.endswith(".json") and not i.endswith(".srt"):
            season, episode = scrapertools.get_season_and_episode(i).split("x")
            # Si hay q filtrar por temporada, ignoramos los capitulos de otras temporadas
            if item.filtrar_season and int(season) != int(item.contentSeason):
                continue

            epi = Item()
            epi.contentChannel = "local"
            epi.path = filetools.join(raiz, i)
            epi.title = i
            epi.channel = "biblioteca"
            epi.action = "play"
            epi.contentEpisodeNumber = episode
            epi.contentSeason = season

            itemlist.append(epi)

    library.set_infolabels_from_library(itemlist, tipo="Episodes")
    return sorted(itemlist, key=get_sort_temp_epi)
Exemple #3
0
def findvideos(item):
    from core import autoplay
    logger.info()
    # logger.debug("item:\n" + item.tostring('\n'))
    videolibrarytools.check_renumber_options(item)
    itemlist = []
    list_canales = {}
    item_local = None

    # Disable autoplay
    # autoplay.set_status(False)

    if not item.contentTitle or not item.strm_path:
        logger.debug("Unable to search for videos due to lack of parameters")
        return []

    content_title = str(item.contentSeason) + 'x' + (str(item.contentEpisodeNumber) if item.contentEpisodeNumber > 9 else '0' + str(item.contentEpisodeNumber))
    if item.contentType == 'movie':
        item.strm_path = filetools.join(videolibrarytools.MOVIES_PATH, item.strm_path)
        path_dir = filetools.dirname(item.strm_path)
        item.nfo = filetools.join(path_dir, filetools.basename(path_dir) + ".nfo")
    else:
        item.strm_path = filetools.join(videolibrarytools.TVSHOWS_PATH, item.strm_path)
        path_dir = filetools.dirname(item.strm_path)
        item.nfo = filetools.join(path_dir, 'tvshow.nfo')

    for fd in filetools.listdir(path_dir):
        if fd.endswith('.json'):
            contenido, nom_canal = fd[:-6].split('[')
            if (contenido.startswith(content_title) or item.contentType == 'movie') and nom_canal not in list(list_canales.keys()):
                list_canales[nom_canal] = filetools.join(path_dir, fd)

    num_canales = len(list_canales)

    if 'downloads' in list_canales:
        json_path = list_canales['downloads']
        item_json = Item().fromjson(filetools.read(json_path))
        item_json.contentChannel = "local"
        # Support for relative paths in downloads
        if filetools.is_relative(item_json.url):
            item_json.url = filetools.join(videolibrarytools.VIDEOLIBRARY_PATH, item_json.url)

        del list_canales['downloads']

        # Check that the video has not been deleted
        if filetools.exists(item_json.url):
            item_local = item_json.clone(action='play')
            itemlist.append(item_local)
        else:
            num_canales -= 1

    filtro_canal = ''
    if num_canales > 1 and config.get_setting("ask_channel", "videolibrary"):
        opciones = [config.get_localized_string(70089) % k.capitalize() for k in list(list_canales.keys())]
        opciones.insert(0, config.get_localized_string(70083))
        if item_local:
            opciones.append(item_local.title)

        from platformcode import platformtools
        index = platformtools.dialog_select(config.get_localized_string(30163), opciones)
        if index < 0:
            return []

        elif item_local and index == len(opciones) - 1:
            filtro_canal = 'downloads'
            platformtools.play_video(item_local)

        elif index > 0:
            filtro_canal = opciones[index].replace(config.get_localized_string(70078), "").strip()
            itemlist = []

    for nom_canal, json_path in list(list_canales.items()):
        if filtro_canal and filtro_canal != nom_canal.capitalize():
            continue

        item_canal = Item()

        # We import the channel of the selected part
        try:
            if nom_canal == 'community':
                channel = __import__('specials.%s' % nom_canal, fromlist=["channels.%s" % nom_canal])
            else:
                channel = __import__('channels.%s' % nom_canal, fromlist=["channels.%s" % nom_canal])
        except ImportError:
            exec("import channels." + nom_canal + " as channel")

        item_json = Item().fromjson(filetools.read(json_path))
        list_servers = []
        # from core.support import dbg;dbg()

        try:
            # FILTERTOOLS
            # if the channel has a filter, the name it has saved is passed to it so that it filters correctly.
            if "list_language" in item_json:
                # if it comes from the addon video library
                if "library_filter_show" in item:
                    item_json.show = item.library_filter_show.get(nom_canal, "")

            # We run find_videos, from the channel or common
            item_json.contentChannel = 'videolibrary'
            item_json.play_from = item.play_from
            item_json.nfo = item.nfo
            item_json.strm_path = item.strm_path
            if hasattr(channel, 'findvideos'):
                from core import servertools
                if item_json.videolibray_emergency_urls:
                    del item_json.videolibray_emergency_urls
                list_servers = getattr(channel, 'findvideos')(item_json)
            elif item_json.action == 'play':
                from platformcode import platformtools
                # autoplay.set_status(True)
                item_json.contentChannel = item_json.channel
                item_json.channel = "videolibrary"
                platformtools.play_video(item_json)
                return ''
            else:
                from core import servertools
                list_servers = servertools.find_video_items(item_json)
        except Exception as ex:
            logger.error("The findvideos function for the channel %s failed" % nom_canal)
            template = "An exception of type %s occured. Arguments:\n%r"
            message = template % (type(ex).__name__, ex.args)
            logger.error(message)
            logger.error(traceback.format_exc())

        # Change the title to the servers adding the name of the channel in front and the infoLabels and the images of the item if the server does not have
        for server in list_servers:
            server.contentChannel = server.channel
            server.channel = "videolibrary"
            server.nfo = item.nfo
            server.strm_path = item.strm_path
            server.play_from = item.play_from

            # Kodi 18 Compatibility - Prevents wheel from spinning around in Direct Links
            if server.action == 'play':
                server.folder = False

            # Channel name is added if desired
            if config.get_setting("quit_channel_name", "videolibrary") == 0:
                server.title = "%s: %s" % (nom_canal.capitalize(), server.title)

            if not server.thumbnail:
                server.thumbnail = item.thumbnail

            # logger.debug("server:\n%s" % server.tostring('\n'))
            itemlist.append(server)

    if autoplay.play_multi_channel(item, itemlist):  # hideserver
        return []

    add_download_items(item, itemlist)
    return itemlist
Exemple #4
0
def findvideos(item):
    logger.info()
    # logger.debug("item:\n" + item.tostring('\n'))

    itemlist = []
    list_canales = {}
    item_local = None

    if not item.contentTitle or not item.strm_path:
        logger.debug("No se pueden buscar videos por falta de parametros")
        return []

    content_title = filter(lambda c: c not in ":*?<>|\/",
                           item.contentTitle.strip().lower())

    if item.contentType == 'movie':
        item.strm_path = filetools.join(videolibrarytools.MOVIES_PATH,
                                        item.strm_path)
        path_dir = os.path.dirname(item.strm_path)
        item.nfo = filetools.join(path_dir,
                                  os.path.basename(path_dir) + ".nfo")
    else:
        item.strm_path = filetools.join(videolibrarytools.TVSHOWS_PATH,
                                        item.strm_path)
        path_dir = os.path.dirname(item.strm_path)
        item.nfo = filetools.join(path_dir, 'tvshow.nfo')

    for fd in filetools.listdir(path_dir):
        if fd.endswith('.json'):
            contenido, nom_canal = fd[:-6].split('[')
            if (contenido.startswith(content_title) or item.contentType == 'movie') and nom_canal not in \
                    list_canales.keys():
                list_canales[nom_canal] = filetools.join(path_dir, fd)

    num_canales = len(list_canales)
    # logger.debug(str(list_canales))
    if 'downloads' in list_canales:
        json_path = list_canales['downloads']
        item_json = Item().fromjson(filetools.read(json_path))
        item_json.contentChannel = "local"
        # Soporte para rutas relativas en descargas
        if filetools.is_relative(item_json.url):
            item_json.url = filetools.join(videolibrarytools.VIDEOLIBRARY_PATH,
                                           item_json.url)

        del list_canales['downloads']

        # Comprobar q el video no haya sido borrado
        if filetools.exists(item_json.url):
            item_local = item_json.clone(action='play')
            itemlist.append(item_local)
        else:
            num_canales -= 1

    filtro_canal = ''
    if num_canales > 1 and config.get_setting("ask_channel", "videolibrary"):
        opciones = [
            "Mostrar solo los enlaces de %s" % k.capitalize()
            for k in list_canales.keys()
        ]
        opciones.insert(0, "Mostrar todos los enlaces")
        if item_local:
            opciones.append(item_local.title)

        from platformcode import platformtools
        index = platformtools.dialog_select(config.get_localized_string(30163),
                                            opciones)
        if index < 0:
            return []

        elif item_local and index == len(opciones) - 1:
            filtro_canal = 'downloads'
            platformtools.play_video(item_local)

        elif index > 0:
            filtro_canal = opciones[index].replace(
                "Mostrar solo los enlaces de ", "")
            itemlist = []

    for nom_canal, json_path in list_canales.items():
        if filtro_canal and filtro_canal != nom_canal.capitalize():
            continue

        # Importamos el canal de la parte seleccionada
        try:
            channel = __import__('channels.%s' % nom_canal,
                                 fromlist=["channels.%s" % nom_canal])
        except ImportError:
            exec "import channels." + nom_canal + " as channel"

        item_json = Item().fromjson(filetools.read(json_path))
        list_servers = []

        try:
            # FILTERTOOLS
            # si el canal tiene filtro se le pasa el nombre que tiene guardado para que filtre correctamente.
            if "list_language" in item_json:
                # si se viene desde la videoteca del addon
                if "library_filter_show" in item:
                    item_json.show = item.library_filter_show.get(
                        nom_canal, "")

            # Ejecutamos find_videos, del canal o común
            item_json.contentChannel = 'videolibrary'
            if hasattr(channel, 'findvideos'):
                from core import servertools
                list_servers = getattr(channel, 'findvideos')(item_json)
                list_servers = servertools.filter_servers(list_servers)
            else:
                from core import servertools
                list_servers = servertools.find_video_items(item_json)
        except Exception, ex:
            logger.error("Ha fallado la funcion findvideos para el canal %s" %
                         nom_canal)
            template = "An exception of type %s occured. Arguments:\n%r"
            message = template % (type(ex).__name__, ex.args)
            logger.error(message)

        # Cambiarle el titulo a los servers añadiendoles el nombre del canal delante y
        # las infoLabels y las imagenes del item si el server no tiene
        for server in list_servers:
            if not server.action:  # Ignorar las etiquetas
                continue

            server.contentChannel = server.channel
            server.channel = "videolibrary"
            server.nfo = item.nfo
            server.strm_path = item.strm_path

            # Se añade el nombre del canal si se desea
            if config.get_setting("quit_channel_name", "videolibrary") == 0:
                server.title = "%s: %s" % (nom_canal.capitalize(),
                                           server.title)

            server.infoLabels = item_json.infoLabels

            if not server.thumbnail:
                server.thumbnail = item.thumbnail

            # logger.debug("server:\n%s" % server.tostring('\n'))
            itemlist.append(server)
def peliculas(item):
    logger.info("pelisalacarta.channels.biblioteca peliculas")
    strm_path = library.MOVIES_PATH
    download_path = filetools.join(config.get_library_path(), "Descargas", "Cine")

    itemlist = []

    for raiz, subcarpetas, ficheros in filetools.walk(strm_path):
        for f in ficheros:
            if f.endswith(".strm"):
                i = filetools.join(raiz, f)

                movie = Item().fromurl(filetools.read(i))
                movie.contentChannel = movie.channel
                movie.path = i
                movie.title = os.path.splitext(os.path.basename(i))[0].capitalize()
                movie.channel = "biblioteca"
                movie.action = "findvideos"
                movie.text_color = "blue"
                # fix para que no se ejecute el método de play para la biblioteca de Kodi
                movie.strm = False

                itemlist.append(movie)

    # Obtenemos todos los videos de la biblioteca de CINE recursivamente
    for raiz, subcarpetas, ficheros in filetools.walk(download_path):
        for f in ficheros:
            if not f.endswith(".json") and not f.endswith(".nfo") and not f.endswith(".srt"):
                i = filetools.join(raiz, f)

                movie = Item()
                movie.contentChannel = "local"
                movie.path = i
                movie.title = os.path.splitext(os.path.basename(i))[0].capitalize()
                movie.channel = "biblioteca"
                movie.action = "play"
                movie.text_color = "green"

                itemlist.append(movie)

    library.set_infolabels_from_library(itemlist, tipo="Movies")

    # Agrupamos las peliculas por canales
    join_itemlist = []

    for i in range(len(itemlist)):
        encontrado = False
        for j in range(i + 1, len(itemlist)):
            if "tmdb_id" in itemlist[i].infoLabels and "tmdb_id" in itemlist[j].infoLabels:
                if itemlist[i].infoLabels["tmdb_id"] == itemlist[j].infoLabels["tmdb_id"]:
                    encontrado = True

                    if "list_channels" not in itemlist[i]:
                        list_channels = []
                        dict_first_channel = {"path": itemlist[i].path, "channel": itemlist[i].contentChannel}
                        list_channels.append(dict_first_channel.copy())
                        itemlist[j].list_channels = list_channels

                    dict_other_channel = {"path": itemlist[j].path, "channel": itemlist[j].contentChannel}
                    itemlist[j].list_channels.append(dict_other_channel.copy())
                    itemlist[j].action = "get_canales_movies"
                    itemlist[j].text_color = "orange"

        # TODO pendiente de probar
        if "contentTitle" in itemlist[i] and itemlist[i].contentTitle != "":
            itemlist[i].title = itemlist[i].contentTitle

        if not encontrado:
            join_itemlist.append(itemlist[i])

    return sorted(join_itemlist, key=lambda it: it.title.lower())
def series(item):
    logger.info("pelisalacarta.channels.biblioteca series")
    strm_path = library.TVSHOWS_PATH
    download_path = filetools.join(config.get_library_path(), "Descargas", "Series")

    itemlist = []

    # Obtenemos todos los strm de la biblioteca de SERIES recursivamente
    for raiz, subcarpetas, ficheros in filetools.walk(strm_path):
        for f in ficheros:
            if f == "tvshow.json":
                i = filetools.join(raiz, f)

                tvshow = Item().fromjson(filetools.read(i))
                logger.debug(tvshow.tostring())
                tvshow.contentChannel = tvshow.channel
                tvshow.path = os.path.dirname(i)
                tvshow.title = os.path.basename(os.path.dirname(i))
                tvshow.channel = "biblioteca"
                tvshow.action = "get_temporadas"
                tvshow.text_color = "blue"

                itemlist.append(tvshow)

    # Obtenemos todos los videos de la biblioteca de SERIES recursivamente
    for raiz, subcarpetas, ficheros in filetools.walk(download_path):
        for f in ficheros:
            if f == "tvshow.json":
                i = filetools.join(raiz, f)

                tvshow = Item().fromjson(filetools.read(i))
                tvshow.contentChannel = "local"
                tvshow.path = os.path.dirname(i)
                tvshow.title = os.path.basename(os.path.dirname(i))
                tvshow.channel = "biblioteca"
                tvshow.action = "get_temporadas"
                tvshow.text_color = "green"

                itemlist.append(tvshow)

    library.set_infolabels_from_library(itemlist, tipo="TVShows")

    # Agrupamos las series por canales
    join_itemlist = []

    for i in range(len(itemlist)):
        encontrado = False
        for j in range(i + 1, len(itemlist)):
            if "tmdb_id" in itemlist[i].infoLabels and "tmdb_id" in itemlist[j].infoLabels:
                if itemlist[i].infoLabels["tmdb_id"] == itemlist[j].infoLabels["tmdb_id"]:
                    encontrado = True

                    if "list_channels" not in itemlist[i]:
                        list_channels = []
                        dict_first_channel = {"path": itemlist[i].path, "channel": itemlist[i].contentChannel}
                        list_channels.append(dict_first_channel.copy())
                        itemlist[j].list_channels = list_channels

                    dict_other_channel = {"path": itemlist[j].path, "channel": itemlist[j].contentChannel}
                    itemlist[j].list_channels.append(dict_other_channel.copy())
                    itemlist[j].action = "get_canales_tvshow"
                    itemlist[j].text_color = "orange"

        if "contentTitle" in itemlist[i] and itemlist[i].contentTitle != "":
            itemlist[i].title = itemlist[i].contentTitle

        if not encontrado:
            join_itemlist.append(itemlist[i])

    return sorted(join_itemlist, key=lambda it: it.title.lower())
Exemple #7
0
def findvideos(item):
    from channels import autoplay
    logger.info()
    # logger.debug("item:\n" + item.tostring('\n'))

    itemlist = []
    list_canales = {}
    item_local = None

    # Desactiva autoplay
    autoplay.set_status(False)

    if not item.contentTitle or not item.strm_path:
        logger.debug("No se pueden buscar videos por falta de parametros")
        return []

    #content_title = [c for c in item.contentTitle.strip().lower() if c not in ":*?<>|\/"]
    content_title = "".join(c for c in item.contentTitle.strip().lower()
                            if c not in ":*?<>|\/")

    if item.contentType == 'movie':
        item.strm_path = filetools.join(videolibrarytools.MOVIES_PATH,
                                        item.strm_path)
        path_dir = filetools.dirname(item.strm_path)
        item.nfo = filetools.join(path_dir,
                                  filetools.basename(path_dir) + ".nfo")
    else:
        item.strm_path = filetools.join(videolibrarytools.TVSHOWS_PATH,
                                        item.strm_path)
        path_dir = filetools.dirname(item.strm_path)
        item.nfo = filetools.join(path_dir, 'tvshow.nfo')

    for fd in filetools.listdir(path_dir):
        if fd.endswith('.json'):
            contenido, nom_canal = fd[:-6].split('[')
            if (contenido.startswith(content_title) or item.contentType == 'movie') and nom_canal not in \
                    list(list_canales.keys()):
                list_canales[nom_canal] = filetools.join(path_dir, fd)

    num_canales = len(list_canales)

    if 'downloads' in list_canales:
        json_path = list_canales['downloads']
        item_json = Item().fromjson(filetools.read(json_path))
        ###### Redirección al canal NewPct1.py si es un clone, o a otro canal y url si ha intervención judicial
        try:
            if item_json:
                item_json, it, overwrite = generictools.redirect_clone_newpct1(
                    item_json)
        except:
            logger.error(traceback.format_exc())
        item_json.contentChannel = "local"
        # Soporte para rutas relativas en descargas
        if filetools.is_relative(item_json.url):
            item_json.url = filetools.join(videolibrarytools.VIDEOLIBRARY_PATH,
                                           item_json.url)

        del list_canales['downloads']

        # Comprobar q el video no haya sido borrado
        if filetools.exists(item_json.url):
            item_local = item_json.clone(action='play')
            itemlist.append(item_local)
        else:
            num_canales -= 1

    filtro_canal = ''
    if num_canales > 1 and config.get_setting("ask_channel", "videolibrary"):
        opciones = [
            config.get_localized_string(70089) % k.capitalize()
            for k in list(list_canales.keys())
        ]
        opciones.insert(0, config.get_localized_string(70083))
        if item_local:
            opciones.append(item_local.title)

        from platformcode import platformtools
        index = platformtools.dialog_select(config.get_localized_string(30163),
                                            opciones)
        if index < 0:
            return []

        elif item_local and index == len(opciones) - 1:
            filtro_canal = 'downloads'
            platformtools.play_video(item_local)

        elif index > 0:
            filtro_canal = opciones[index].replace(
                config.get_localized_string(70078), "").strip()
            itemlist = []

    for nom_canal, json_path in list(list_canales.items()):
        if filtro_canal and filtro_canal != nom_canal.capitalize():
            continue

        item_canal = Item()
        item_canal.channel = nom_canal
        ###### Redirección al canal NewPct1.py si es un clone, o a otro canal y url si ha intervención judicial
        try:
            item_canal, it, overwrite = generictools.redirect_clone_newpct1(
                item_canal)
        except:
            logger.error(traceback.format_exc())
        nom_canal = item_canal.channel

        # Importamos el canal de la parte seleccionada
        try:
            channel = __import__('channels.%s' % nom_canal,
                                 fromlist=["channels.%s" % nom_canal])
        except ImportError:
            exec("import channels." + nom_canal + " as channel")

        item_json = Item().fromjson(filetools.read(json_path))
        item_json.nfo = item.nfo
        ###### Redirección al canal NewPct1.py si es un clone, o a otro canal y url si ha intervención judicial
        try:
            if item_json:
                item_json, it, overwrite = generictools.redirect_clone_newpct1(
                    item_json)
        except:
            logger.error(traceback.format_exc())
        list_servers = []

        try:
            # FILTERTOOLS
            # si el canal tiene filtro se le pasa el nombre que tiene guardado para que filtre correctamente.
            if "list_language" in item_json:
                # si se viene desde la videoteca del addon
                if "library_filter_show" in item:
                    item_json.show = item.library_filter_show.get(
                        nom_canal, "")

            # Ejecutamos find_videos, del canal o común
            item_json.contentChannel = 'videolibrary'
            if hasattr(channel, 'findvideos'):
                from core import servertools
                if item_json.videolibray_emergency_urls:
                    del item_json.videolibray_emergency_urls
                list_servers = getattr(channel, 'findvideos')(item_json)
                list_servers = servertools.filter_servers(list_servers)
            elif item_json.action == 'play':
                from platformcode import platformtools
                autoplay.set_status(True)
                item_json.contentChannel = item_json.channel
                item_json.channel = "videolibrary"
                platformtools.play_video(item_json)
                return ''
            else:
                from core import servertools
                list_servers = servertools.find_video_items(item_json)
        except Exception as ex:
            logger.error("Ha fallado la funcion findvideos para el canal %s" %
                         nom_canal)
            template = "An exception of type %s occured. Arguments:\n%r"
            message = template % (type(ex).__name__, ex.args)
            logger.error(message)
            logger.error(traceback.format_exc())

        # Cambiarle el titulo a los servers añadiendoles el nombre del canal delante y
        # las infoLabels y las imagenes del item si el server no tiene
        y = -1
        z_torrent_url = ''
        for x, server in enumerate(list_servers):
            #if not server.action:  # Ignorar/PERMITIR las etiquetas
            #    continue
            server.contentChannel = server.channel
            server.channel = "videolibrary"
            server.nfo = item.nfo
            server.strm_path = item.strm_path

            # Para downloads de Torrents desde ventana flotante (sin context menu)
            if server.contentChannel == 'downloads' and not server.sub_action:
                y = x
            if server.server == 'torrent' and server.contentChannel != 'downloads' and not z_torrent_url:
                z_torrent_url = server.url
            if server.contentChannel == 'downloads':
                server.channel = server.contentChannel

            #### Compatibilidad con Kodi 18: evita que se quede la ruedecedita dando vueltas en enlaces Directos
            if server.action == 'play':
                server.folder = False

            # Se añade el nombre del canal si se desea
            if config.get_setting("quit_channel_name", "videolibrary") == 0:
                server.title = "%s: %s" % (nom_canal.capitalize(),
                                           server.title)

            #server.infoLabels = item_json.infoLabels
            if not server.thumbnail:
                server.thumbnail = item.thumbnail

            # logger.debug("server:\n%s" % server.tostring('\n'))
            itemlist.append(server)

        #Pego la url del primer torrent en el pseudo-context "Descargar"
        if y >= 0:
            itemlist[y].url = z_torrent_url

    # return sorted(itemlist, key=lambda it: it.title.lower())
    autoplay.play_multi_channel(item, itemlist)
    from inspect import stack
    from channels import nextep
    if nextep.check(item) and stack()[1][3] == 'run':
        nextep.videolibrary(item)
    return itemlist
Exemple #8
0
def peliculas(item):
    logger.info("pelisalacarta.channels.biblioteca peliculas")
    strm_path = library.MOVIES_PATH
    download_path = filetools.join(config.get_library_path(), "Descargas",
                                   "Cine")

    itemlist = []

    for raiz, subcarpetas, ficheros in filetools.walk(strm_path):
        for f in ficheros:
            if f.endswith(".strm"):
                i = filetools.join(raiz, f)

                movie = Item().fromurl(filetools.read(i))
                movie.contentChannel = movie.channel
                movie.path = i
                movie.title = os.path.splitext(
                    os.path.basename(i))[0].capitalize()
                movie.channel = "biblioteca"
                movie.action = "findvideos"
                movie.text_color = "blue"
                # fix para que no se ejecute el método de play para la biblioteca de Kodi
                movie.strm = False

                itemlist.append(movie)

    # Obtenemos todos los videos de la biblioteca de CINE recursivamente
    for raiz, subcarpetas, ficheros in filetools.walk(download_path):
        for f in ficheros:
            if not f.endswith(".json") and not f.endswith(
                    ".nfo") and not f.endswith(".srt"):
                i = filetools.join(raiz, f)

                movie = Item()
                movie.contentChannel = "local"
                movie.path = i
                movie.title = os.path.splitext(
                    os.path.basename(i))[0].capitalize()
                movie.channel = "biblioteca"
                movie.action = "play"
                movie.text_color = "green"

                itemlist.append(movie)

    library.set_infolabels_from_library(itemlist, tipo='Movies')

    # Agrupamos las peliculas por canales
    join_itemlist = []

    for i in range(len(itemlist)):
        encontrado = False
        for j in range(i + 1, len(itemlist)):
            if "tmdb_id" in itemlist[i].infoLabels and "tmdb_id" in itemlist[
                    j].infoLabels:
                if itemlist[i].infoLabels["tmdb_id"] == itemlist[j].infoLabels[
                        "tmdb_id"]:
                    encontrado = True

                    if "list_channels" not in itemlist[i]:
                        list_channels = []
                        dict_first_channel = {
                            "path": itemlist[i].path,
                            "channel": itemlist[i].contentChannel
                        }
                        list_channels.append(dict_first_channel.copy())
                        itemlist[j].list_channels = list_channels

                    dict_other_channel = {
                        "path": itemlist[j].path,
                        "channel": itemlist[j].contentChannel
                    }
                    itemlist[j].list_channels.append(dict_other_channel.copy())
                    itemlist[j].action = "get_canales_movies"
                    itemlist[j].text_color = "orange"

        # TODO pendiente de probar
        if "contentTitle" in itemlist[i] and itemlist[i].contentTitle != "":
            itemlist[i].title = itemlist[i].contentTitle

        if not encontrado:
            join_itemlist.append(itemlist[i])

    return sorted(join_itemlist, key=lambda it: it.title.lower())
Exemple #9
0
def series(item):
    logger.info("pelisalacarta.channels.biblioteca series")
    strm_path = library.TVSHOWS_PATH
    download_path = filetools.join(config.get_library_path(), "Descargas",
                                   "Series")

    itemlist = []

    # Obtenemos todos los strm de la biblioteca de SERIES recursivamente
    for raiz, subcarpetas, ficheros in filetools.walk(strm_path):
        for f in ficheros:
            if f == "tvshow.json":
                i = filetools.join(raiz, f)

                tvshow = Item().fromjson(filetools.read(i))
                logger.debug(tvshow.tostring())
                tvshow.contentChannel = tvshow.channel
                tvshow.path = os.path.dirname(i)
                tvshow.title = os.path.basename(os.path.dirname(i))
                tvshow.channel = "biblioteca"
                tvshow.action = "get_temporadas"
                tvshow.text_color = "blue"

                itemlist.append(tvshow)

    # Obtenemos todos los videos de la biblioteca de SERIES recursivamente
    for raiz, subcarpetas, ficheros in filetools.walk(download_path):
        for f in ficheros:
            if f == "tvshow.json":
                i = filetools.join(raiz, f)

                tvshow = Item().fromjson(filetools.read(i))
                tvshow.contentChannel = "local"
                tvshow.path = os.path.dirname(i)
                tvshow.title = os.path.basename(os.path.dirname(i))
                tvshow.channel = "biblioteca"
                tvshow.action = "get_temporadas"
                tvshow.text_color = "green"

                itemlist.append(tvshow)

    library.set_infolabels_from_library(itemlist, tipo='TVShows')

    # Agrupamos las series por canales
    join_itemlist = []

    for i in range(len(itemlist)):
        encontrado = False
        for j in range(i + 1, len(itemlist)):
            if "tmdb_id" in itemlist[i].infoLabels and "tmdb_id" in itemlist[
                    j].infoLabels:
                if itemlist[i].infoLabels["tmdb_id"] == itemlist[j].infoLabels[
                        "tmdb_id"]:
                    encontrado = True

                    if "list_channels" not in itemlist[i]:
                        list_channels = []
                        dict_first_channel = {
                            "path": itemlist[i].path,
                            "channel": itemlist[i].contentChannel
                        }
                        list_channels.append(dict_first_channel.copy())
                        itemlist[j].list_channels = list_channels

                    dict_other_channel = {
                        "path": itemlist[j].path,
                        "channel": itemlist[j].contentChannel
                    }
                    itemlist[j].list_channels.append(dict_other_channel.copy())
                    itemlist[j].action = "get_canales_tvshow"
                    itemlist[j].text_color = "orange"

        if "contentTitle" in itemlist[i] and itemlist[i].contentTitle != "":
            itemlist[i].title = itemlist[i].contentTitle

        if not encontrado:
            join_itemlist.append(itemlist[i])

    return sorted(join_itemlist, key=lambda it: it.title.lower())
def findvideos(item):
    logger.info()
    # logger.debug("item:\n" + item.tostring('\n'))

    itemlist = []
    list_canales = {}
    item_local = None

    if not item.contentTitle or not item.strm_path:
        logger.debug("No se pueden buscar videos por falta de parametros")
        return []

    content_title = filter(lambda c: c not in ":*?<>|\/", item.contentTitle).strip().lower()

    if item.contentType == 'movie':
        item.strm_path = filetools.join(library.MOVIES_PATH, item.strm_path)
        path_dir = os.path.dirname(item.strm_path)
        item.nfo = filetools.join(path_dir, os.path.basename(path_dir) + ".nfo")
    else:
        item.strm_path = filetools.join(library.TVSHOWS_PATH, item.strm_path)
        path_dir = os.path.dirname(item.strm_path)
        item.nfo = filetools.join(path_dir, 'tvshow.nfo')


    for fd in filetools.listdir(path_dir):
        if fd.endswith('.json'):
            contenido, nom_canal = fd[:-6].split('[')
            if (contenido.startswith(content_title) or item.contentType == 'movie') and nom_canal not in \
                    list_canales.keys():
                list_canales[nom_canal] = filetools.join(path_dir, fd)

    num_canales = len(list_canales)
    # logger.debug(str(list_canales))
    if 'descargas' in list_canales:
        json_path = list_canales['descargas']
        item_json = Item().fromjson(filetools.read(json_path))
        item_json.contentChannel = "local"
        # Soporte para rutas relativas en descargas
        if filetools.is_relative(item_json.url):
            item_json.url = filetools.join(library.LIBRARY_PATH, item_json.url)

        del list_canales['descargas']

        # Comprobar q el video no haya sido borrado
        if filetools.exists(item_json.url):
            item_local = item_json.clone(action='play')
            itemlist.append(item_local)
        else:
            num_canales -= 1

    filtro_canal = ''
    if num_canales > 1 and config.get_setting("ask_channel", "biblioteca") == True:
        opciones = ["Mostra solo link %s" % k.capitalize() for k in list_canales.keys()]
        opciones.insert(0, "Mosta tutti i collegamenti")
        if item_local:
            opciones.append(item_local.title)

        from platformcode import platformtools
        index = platformtools.dialog_select(config.get_localized_string(30163), opciones)
        if index < 0:
            return []

        elif item_local and index == len(opciones) - 1:
            filtro_canal = 'descargas'
            platformtools.play_video(item_local)

        elif index > 0:
            filtro_canal = opciones[index].replace("Mostra solo link ", "")
            itemlist = []

    for nom_canal, json_path in list_canales.items():
        if filtro_canal and filtro_canal != nom_canal.capitalize():
            continue

        # Importamos el canal de la parte seleccionada
        try:
            channel = __import__('channels.%s' % nom_canal, fromlist=["channels.%s" % nom_canal])
        except ImportError:
            exec "import channels." + nom_canal + " as channel"

        item_json = Item().fromjson(filetools.read(json_path))
        list_servers = []

        try:
            # FILTERTOOLS
            # si el canal tiene filtro se le pasa el nombre que tiene guardado para que filtre correctamente.
            if "list_idiomas" in item_json:
                # si se viene desde la biblioteca de pelisalacarta
                if "library_filter_show" in item:
                    item_json.show = item.library_filter_show.get(nom_canal, "")

            # Ejecutamos find_videos, del canal o común
            if hasattr(channel, 'findvideos'):
                list_servers = getattr(channel, 'findvideos')(item_json)
            else:
                from core import servertools
                list_servers = servertools.find_video_items(item_json)
        except Exception as ex:
            logger.error("Ha fallado la funcion findvideos para el canal %s" % nom_canal)
            template = "An exception of type {0} occured. Arguments:\n{1!r}"
            message = template.format(type(ex).__name__, ex.args)
            logger.error(message)

        # Cambiarle el titulo a los servers añadiendoles el nombre del canal delante y
        # las infoLabels y las imagenes del item si el server no tiene
        for server in list_servers:
            if not server.action:  # Ignorar las etiquetas
                continue

            server.contentChannel = server.channel
            server.channel = "biblioteca"
            server.nfo = item.nfo
            server.strm_path = item.strm_path

            # Se añade el nombre del canal si se desea
            if config.get_setting("quit_channel_name", "biblioteca") == 0:
                server.title = "%s: %s" % (nom_canal.capitalize(), server.title)

            server.infoLabels = item_json.infoLabels

            if not server.thumbnail:
                server.thumbnail = item.thumbnail

            # logger.debug("server:\n%s" % server.tostring('\n'))
            itemlist.append(server)

    # return sorted(itemlist, key=lambda it: it.title.lower())
    return itemlist