Example #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)
Example #2
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)
Example #3
0
def newest(categoria):
    logger.info()
    itemlist = []
    item = Item()

    try:
        if categoria in ['torrent', 'peliculas']:
            item.url = host + 'torrents'
        elif categoria == '4k':
            item.url = host + 'tags/4k'
            item.extra2 = 'categorias'
        item.extra = "peliculas"
        item.channel = channel
        item.category_new = 'newest'

        itemlist = listado(item)
        if ">> Página siguiente" in itemlist[-1].title:
            itemlist.pop()

    # Se captura la excepción, para no interrumpir al canal novedades si un canal falla
    except:
        import sys
        for line in sys.exc_info():
            logger.error("{0}".format(line))
        return []

    return itemlist
Example #4
0
def newest(categoria):
    logger.info()
    itemlist = []
    item = Item()

    item.title = "newest"
    item.category_new = "newest"
    item.channel = channel

    try:
        if categoria in ['peliculas', 'torrent']:
            item.url = host + "page/1/"
            item.extra = "peliculas"
            item.extra2 = "novedades"
            item.action = "listado"
            itemlist.extend(listado(item))

        if len(itemlist) > 0 and (">> Página siguiente" in itemlist[-1].title
                                  or "Pagina siguiente >>"
                                  in itemlist[-1].title):
            itemlist.pop()

    # Se captura la excepción, para no interrumpir al canal novedades si un canal falla
    except:
        for line in sys.exc_info():
            logger.error("{0}".format(line))
        logger.error(traceback.format_exc(1))
        return []

    return itemlist
Example #5
0
def newest(categoria):
    logger.info()
    itemlist = []
    item = Item()

    try:
        if categoria == 'torrent' or categoria == 'peliculas':
            item.category_new = 'newest'
            item.channel = channel
            item.category = channel.capitalize()
            item.extra = "peliculas"

            item.url = api + "?sort_by=date_added&page=0"
            itemlist = listado(item)
            if ">> Página siguiente" in itemlist[-1].title:
                itemlist.pop()

            if categoria == 'torrent':
                item.extra = "series"
                item.url = api_serie + "?sort_by=date_added&page=0"
                itemlist = listado(item)
                if ">> Página siguiente" in itemlist[-1].title:
                    itemlist.pop()

    # Se captura la excepción, para no interrumpir al canal novedades si un canal falla
    except:
        import sys
        for line in sys.exc_info():
            logger.error("{0}".format(line))
        return []

    return itemlist
def play_from_library(item):
    logger.info("[launcher.py] play_from_library")
    elegido = Item(url="")
    channelmodule = ImportarCanal(item.channel)
    if hasattr(channelmodule, 'findvideos'):
        itemlist = channelmodule.findvideos(item)
    else:
        itemlist= findvideos(item)
    
    if len(itemlist)>0:
        #Mostrar cuadro de seleccion de servers
        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
    
    if hasattr(channelmodule, 'play'):
      logger.info("[launcher.py] executing channel 'play' method")
      logger.info(channelmodule.__file__)
      itemlist = channelmodule.play(elegido)
      elegido= itemlist[0]
    else:
      logger.info("[launcher.py] no channel 'play' method, executing core method")
    
    elegido.channel= 'library'
    play(elegido)
Example #7
0
def newest(categoria):
    logger.info()
    itemlist = []
    item = Item()

    try:
        if categoria == 'peliculas':
            item.url = host + "peliculas-subtituladas/?filtro=estrenos"
            item.extra = "peliculas"
            item.channel = channel
            item.category_new = 'newest'

            itemlist = listado(item)
            if len(itemlist) > 0 and (
                    ">> Página siguiente" in itemlist[-1].title
                    or "Pagina siguiente >>" in itemlist[-1].title):
                itemlist.pop()

    # Se captura la excepción, para no interrumpir al canal novedades si un canal falla
    except:
        import sys
        for line in sys.exc_info():
            logger.error("{0}".format(line))
        return []

    return itemlist
Example #8
0
def newest(categoria):
    logger.info()
    itemlist = []
    item = Item()

    item.title = "newest"
    item.category_new = "newest"
    item.channel = channel
    
    try:
        if categoria in ['deportes']:
            item.url = host
            item.extra = "deportes"
            item.extra2 = "novedades"
            item.action = "listado"
            item.channel_sufix = "  [Dascer]"
            itemlist.extend(listado(item))
                
        if ">> Página siguiente" in itemlist[-1].title or "Pagina siguiente >>" in itemlist[-1].title:
            itemlist.pop()

    # Se captura la excepción, para no interrumpir al canal novedades si un canal falla
    except:
        for line in sys.exc_info():
            logger.error("{0}".format(line))
        logger.error(traceback.format_exc(1))
        return []

    return itemlist
Example #9
0
def newest(categoria):
    item = Item()
    item.action = "newest"
    item.channel = "hentaila"
    item.param = ""
    item.thumbnail = get_thumb("newest", auto=True)
    item.title = "Novedades"
    item.url = host + "/directorio?filter=recent"
    return list_all(item)
Example #10
0
def newest(categoria):
    logger.info()
    item = Item()
    item.channel = 'comamosramen'
    if categoria in ['peliculas']:
        item.list_type = 'pelicula'
        item.url = '{}/peliculas'.format(apihost)
    else:
        item.list_type = 'novedades'
        item.url = '{}/ultimos/48'.format(apihost)
    return list_all(item)
Example #11
0
def newest(categoria):
    logger.info()
    itemlist = []
    item = Item()
    try:
        if categoria == 'series':
            item.channel = "playmax"
            item.extra = "newest"
            item.url = host + "/catalogo.php?tipo[]=1&ad=2&ordenar=novedades&con_dis=on"
            item.contentType = "tvshow"
            itemlist = fichas(item)

            if itemlist[-1].action == "fichas":
                itemlist.pop()
        elif categoria == 'peliculas':
            item.channel = "playmax"
            item.extra = "newest"
            item.url = host + "/catalogo.php?tipo[]=2&ad=2&ordenar=novedades&con_dis=on"
            item.contentType = "movie"
            itemlist = fichas(item)

            if itemlist[-1].action == "fichas":
                itemlist.pop()
        elif categoria == 'infantiles':
            item.channel = "playmax"
            item.extra = "newest"
            item.url = host + "/catalogo.php?tipo[]=2&genero[]=60&ad=2&ordenar=novedades&con_dis=on"
            item.contentType = "movie"
            itemlist = fichas(item)

            if itemlist[-1].action == "fichas":
                itemlist.pop()

    # Se captura la excepción, para no interrumpir al canal novedades si un canal falla
    except:
        import sys
        for line in sys.exc_info():
            logger.error("{0}".format(line))
        return []

    return itemlist
Example #12
0
def newest(categoria):
    logger.info()
    item = Item()
    item.channel = canonical['channel']

    if categoria in ['peliculas']:
        item.list_type = 'pelicula'
        item.url = '{}p/peliculas'.format(host)

    else:
        item.list_type = 'novedades'
        item.url = '{}p/dramas'.format(host)

    return list_all(item)
Example #13
0
def mainlist(item):
    logger.info()
    item.category = 'Descargas'

    itemlist = []

    if download_path.startswith('smb://'):
        fichs = sorted(filetools.listdir(download_path))
        ficheros = [
            filetools.join(download_path, fit) for fit in fichs
            if fit.endswith('.json')
        ]
    else:
        path = filetools.join(download_path, '*.json')
        ficheros = glob.glob(path)
        ficheros.sort(key=os.path.getmtime, reverse=False)

    for down_path in ficheros:

        # ~ it = Item().fromjson(path=down_path) # falla con smb://
        it = Item().fromjson(filetools.read(down_path))

        it.from_channel = it.channel
        it.from_action = it.action
        it.channel = item.channel
        it.action = 'acciones_enlace'
        it.jsonfile = down_path
        it.folder = False

        if it.downloadStatus == STATUS_CODES.completed:
            it.title = '[B][COLOR gold][Ok] %s [%s][/COLOR][/B]' % (
                it.downloadFilename, config.format_bytes(it.downloadSize))

        elif it.downloadStatus == STATUS_CODES.canceled:
            it.title = '[COLOR red][%s%%] %s [%s de %s][/COLOR]' % (
                int(it.downloadProgress), it.downloadFilename,
                config.format_bytes(it.downloadCompleted),
                config.format_bytes(it.downloadSize))

        elif it.downloadStatus == STATUS_CODES.error:
            it.title = '[I][COLOR gray][Error] %s[/COLOR][/I]' % it.downloadFilename

        else:
            it.title = '[I][COLOR gray][???] %s[/COLOR][/I]' % it.downloadFilename

        itemlist.append(it)

    return itemlist
def newest(categoria):
    logger.info()
    itemlist = []
    item = Item()
    try:
        item.channel = "vernovelasonline"
        item.extra = "newest"
        item.url = "http://www.ver-novelas-online.com/"
        item.action = "capitulos_ultimos"
        itemlist = capitulos_ultimos(item)
    # Se captura la excepcion, para no interrumpir al canal novedades si un canal falla
    except:
        import sys
        for line in sys.exc_info():
            logger.error("{0}".format(line))
        return []

    return itemlist
Example #15
0
def newest(categoria):
    logger.info()
    itemlist = []
    item = Item()
    try:
        if categoria == 'torrent':
            item.url = host
            item.extra = "peliculas"
            item.channel = "alltorrents"

            itemlist = listado(item)
            if itemlist[-1].title == "Página siguiente >>":
                itemlist.pop()

    # Se captura la excepción, para no interrumpir al canal novedades si un canal falla
    except:
        import sys
        for line in sys.exc_info():
            logger.error("{0}".format(line))
        return []

    return itemlist
def newest(categoria):
    logger.info("pelisalacarta.channels.verseriesynovelas newest")
    itemlist = []
    item = Item()
    try:
        if categoria == 'series':
            item.channel = "verseriesynovelas"
            item.extra = "newest"
            item.url = "http://www.verseriesynovelas.tv/archivos/nuevo"
            itemlist = novedades(item)

            if itemlist[-1].action == "novedades":
                itemlist.pop()

    # Se captura la excepción, para no interrumpir al canal novedades si un canal falla
    except:
        import sys
        for line in sys.exc_info():
            logger.error("{0}".format(line))
        return []

    return itemlist
Example #17
0
def newest(categoria):
    logger.info("pelisalacarta.channels.verseriesynovelas newest")
    itemlist = []
    item = Item()
    try:
        if categoria == 'series':
            item.channel = "verseriesynovelas"
            item.extra = "newest"
            item.url = "http://www.verseriesynovelas.tv/archivos/nuevo"
            itemlist = novedades(item)

            if itemlist[-1].action == "novedades":
                itemlist.pop()

    # Se captura la excepción, para no interrumpir al canal novedades si un canal falla
    except:
        import sys
        for line in sys.exc_info():
            logger.error("{0}".format(line))
        return []

    return itemlist
Example #18
0
def play_from_library(item):
    logger.info("[launcher.py] play_from_library")
    elegido = Item(url="")
    channelmodule = ImportarCanal(item.channel)
    if hasattr(channelmodule, 'findvideos'):
        itemlist = channelmodule.findvideos(item)
    else:
        itemlist = findvideos(item)

    if len(itemlist) > 0:
        #Mostrar cuadro de seleccion de servers
        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

    if hasattr(channelmodule, 'play'):
        logger.info("[launcher.py] executing channel 'play' method")
        logger.info(channelmodule.__file__)
        itemlist = channelmodule.play(elegido)
        elegido = itemlist[0]
    else:
        logger.info(
            "[launcher.py] no channel 'play' method, executing core method")

    elegido.channel = 'library'
    play(elegido)
Example #19
0
def save_tvshow(item, episodelist):
    """
    guarda en la libreria de series la serie con todos los capitulos incluidos en la lista episodelist
    @type item: item
    @param item: item que representa la serie a guardar
    @type episodelist: list
    @param episodelist: listado de items que representan los episodios que se van a guardar.
    @rtype insertados: int
    @return:  el número de episodios insertados
    @rtype sobreescritos: int
    @return:  el número de episodios sobreescritos
    @rtype fallidos: int
    @return:  el número de episodios fallidos o -1 si ha fallado toda la serie
    @rtype path: str
    @return:  directorio serie
    """
    logger.info()
    # logger.debug(item.tostring('\n'))
    path = ""

    # Si llegados a este punto no tenemos titulo o code, salimos
    if not (item.contentSerieName or item.infoLabels['code']) or not item.channel:
        logger.error("NO ENCONTRADO contentSerieName NI code: " + item.url)
        return 0, 0, -1, path  # Salimos sin guardar

    scraper_return = scraper.find_and_set_infoLabels(item)
    # Llegados a este punto podemos tener:
    #  scraper_return = True: Un item con infoLabels con la información actualizada de la serie
    #  scraper_return = False: Un item sin información de la peli (se ha dado a cancelar en la ventana)
    #  item.infoLabels['code'] == "" : No se ha encontrado el identificador de IMDB necesario para continuar, salimos
    if not scraper_return or not item.infoLabels['code']:
        # TODO de momento si no hay resultado no añadimos nada,
        # aunq podriamos abrir un cuadro para introducir el identificador/nombre a mano
        logger.error("NO ENCONTRADO EN SCRAPER O NO TIENE code: " + item.url)
        return 0, 0, -1, path

    _id = item.infoLabels['code'][0]
    if not item.infoLabels['code'][0] or item.infoLabels['code'][0] == 'None': 
        if item.infoLabels['code'][1] and item.infoLabels['code'][1] != 'None':
            _id = item.infoLabels['code'][1]
        elif item.infoLabels['code'][2] and item.infoLabels['code'][2] != 'None':
            _id = item.infoLabels['code'][2]
        else:
            logger.error("NO ENCONTRADO EN SCRAPER O NO TIENE code: " + item.url 
                        + ' / ' + item.infoLabels['code'])
            return 0, 0, -1, path

    if config.get_setting("original_title_folder", "videolibrary") == 1 and item.infoLabels['originaltitle']:
        base_name = item.infoLabels['originaltitle']
    elif item.infoLabels['tvshowtitle']:
        base_name = item.infoLabels['tvshowtitle']
    elif item.infoLabels['title']:
        base_name = item.infoLabels['title']
    else:
        base_name = item.contentSerieName

    if not PY3:
        base_name = unicode(filetools.validate_path(base_name.replace('/', '-')), "utf8").encode("utf8")
    else:
        base_name = filetools.validate_path(base_name.replace('/', '-'))

    if config.get_setting("lowerize_title", "videolibrary") == 0:
        base_name = base_name.lower()

    for raiz, subcarpetas, ficheros in filetools.walk(TVSHOWS_PATH):
        for c in subcarpetas:
            code = scrapertools.find_single_match(c, '\[(.*?)\]')
            if code and code != 'None' and code in item.infoLabels['code']:
                path = filetools.join(raiz, c)
                _id = code
                break

    if not path:
        path = filetools.join(TVSHOWS_PATH, ("%s [%s]" % (base_name, _id)).strip())
        logger.info("Creando directorio serie: " + path)
        try:
            filetools.mkdir(path)
        except OSError as exception:
            if exception.errno != errno.EEXIST:
                raise

    tvshow_path = filetools.join(path, "tvshow.nfo")
    if not filetools.exists(tvshow_path):
        # Creamos tvshow.nfo, si no existe, con la head_nfo, info de la serie y marcas de episodios vistos
        logger.info("Creando tvshow.nfo: " + tvshow_path)
        head_nfo = scraper.get_nfo(item)
        item.infoLabels['mediatype'] = "tvshow"
        item.infoLabels['title'] = item.contentSerieName
        item_tvshow = Item(title=item.contentSerieName, channel="videolibrary", action="get_seasons",
                           fanart=item.infoLabels['fanart'], thumbnail=item.infoLabels['thumbnail'],
                           infoLabels=item.infoLabels, path=path.replace(TVSHOWS_PATH, ""))
        item_tvshow.library_playcounts = {}
        item_tvshow.library_urls = {item.channel: item.url}

    else:
        # Si existe tvshow.nfo, pero estamos añadiendo un nuevo canal actualizamos el listado de urls
        head_nfo, item_tvshow = read_nfo(tvshow_path)
        item_tvshow.channel = "videolibrary"
        item_tvshow.action = "get_seasons"
        item_tvshow.library_urls[item.channel] = item.url

    # FILTERTOOLS
    # si el canal tiene filtro de idiomas, añadimos el canal y el show
    if episodelist and "list_language" in episodelist[0]:
        # si ya hemos añadido un canal previamente con filtro, añadimos o actualizamos el canal y show
        if "library_filter_show" in item_tvshow:
            if item.title_from_channel:
                item_tvshow.library_filter_show[item.channel] = item.title_from_channel
            else:
                item_tvshow.library_filter_show[item.channel] = item.show
        # no habia ningún canal con filtro y lo generamos por primera vez
        else:
            if item.title_from_channel:
                item_tvshow.library_filter_show = {item.channel: item.title_from_channel}
            else:
                item_tvshow.library_filter_show = {item.channel: item.show}

    if item.channel != "downloads":
        item_tvshow.active = 1  # para que se actualice a diario cuando se llame a videolibrary_service

    filetools.write(tvshow_path, head_nfo + item_tvshow.tojson())

    if not episodelist:
        # La lista de episodios esta vacia
        return 0, 0, 0, path

    # Guardar los episodios
    '''import time
    start_time = time.time()'''
    insertados, sobreescritos, fallidos = save_episodes(path, episodelist, item)
    '''msg = "Insertados: %d | Sobreescritos: %d | Fallidos: %d | Tiempo: %2.2f segundos" % \
          (insertados, sobreescritos, fallidos, time.time() - start_time)
    logger.debug(msg)'''

    return insertados, sobreescritos, fallidos, path
Example #20
0
def list_storage(item):
    logger.info()
    from core import filetools
    from lib import generictools

    itemlist = []

    torrent_params = {
        'url': item.url,
        'torrents_path': '',
        'local_torr': item.torrents_path,
        'lookup': False,
        'force': True,
        'data_torrent': True,
        'subtitles': True,
        'file_list': True
    }

    #logger.debug(item)

    browse_type = 0
    path_out = item.url
    if not filetools.exists(path_out):
        path_out = ''

    if not path_out:
        msg = 'Seleccione carpeta de destino:'
        path_out = platformtools.dialog_browse(browse_type, msg, shares='')

    path_list = filetools.listdir(path_out)
    VIDEOLIBRARY_PATH = config.get_videolibrary_path()
    FOLDER_MOVIES = config.get_setting("folder_movies")
    FOLDER_TVSHOWS = config.get_setting("folder_tvshows")
    FOLDER = ''
    if VIDEOLIBRARY_PATH in path_out:
        if FOLDER_MOVIES in path_out:
            FOLDER = FOLDER_MOVIES
        elif FOLDER_TVSHOWS in path_out:
            FOLDER = FOLDER_TVSHOWS
    MOVIES_PATH = filetools.join(VIDEOLIBRARY_PATH, FOLDER_MOVIES)
    TVSHOWS_PATH = filetools.join(VIDEOLIBRARY_PATH, FOLDER_TVSHOWS)
    VIDEO_FOLDER = filetools.join(VIDEOLIBRARY_PATH, FOLDER)
    TEMP_TORRENT_FOLDER = filetools.join(
        config.get_setting('downloadpath', default=''), 'cached_torrents_Alfa')
    MIS_TORRENT_FOLDER = filetools.join(
        config.get_setting('downloadpath', default=''), 'Mis_Torrents')

    for file in path_list:
        if FOLDER and file.endswith('.json') and file.split(
                '.')[0] + '_01.torrent' in str(path_list):
            json_video = Item().fromjson(
                filetools.read(filetools.join(path_out, file)))
            json_video.channel = 'url'
            json_video.action = 'findvideos'
            json_video.torrents_path = json_video.url
            itemlist.append(json_video)

        elif FOLDER and filetools.isdir(filetools.join(path_out, file)):
            if '.torrent' in str(filetools.listdir(filetools.join(path_out, file))) \
                                 or '.magnet' in str(filetools.listdir(filetools.join(path_out, file))):
                itemlist.append(
                    Item(channel=item.channel,
                         action="list_storage",
                         url=filetools.join(path_out, file),
                         title=file.title(),
                         contentTitle=file.title(),
                         contentType="list",
                         unify=False,
                         context=context))
                if len(itemlist) > 1:
                    itemlist = sorted(itemlist,
                                      key=lambda it: it.title)  #clasificamos

        elif not FOLDER and filetools.isdir(filetools.join(path_out, file)):
            if MIS_TORRENT_FOLDER in path_out:
                title = file.title()
                if 'BTDigg' in file:
                    title = title.replace(
                        'Btdigg',
                        '[B][COLOR limegreen]BT[/COLOR][COLOR red]Digg[/COLOR][/B]'
                    )
                itemlist.append(
                    Item(channel=item.channel,
                         action="list_storage",
                         url=filetools.join(path_out, file),
                         title=title,
                         contentTitle=title,
                         contentType="list",
                         unify=False,
                         btdigg=True if 'BTDigg' in file else False,
                         url_org=filetools.join(path_out, file),
                         context=context))
                if len(itemlist) > 1:
                    itemlist = sorted(itemlist,
                                      key=lambda it: it.title)  #clasificamos

        elif not FOLDER and ('.torrent' in file or '.magnet' in file):
            btdigg = False
            if '.torrent' in file:
                url = filetools.join(TEMP_TORRENT_FOLDER, file)
                filetools.copy(filetools.join(path_out, file),
                               url,
                               silent=True)
                if not filetools.exists(url): continue
            else:
                url = filetools.read(filetools.join(path_out, file),
                                     silent=True)
                if btdigg_magnet in url: btdigg = True
                size = 'MAGNET'
                if not url: continue

            torrent_params['url'] = url
            torrent_params['torrents_path'] = ''
            torrent_params['local_torr'] = filetools.join(
                TEMP_TORRENT_FOLDER, file)
            torrent_params = generictools.get_torrent_size(
                url, torrent_params=torrent_params)
            if '.magnet' in file and 'ERROR' in torrent_params['size']:
                torrent_params['size'] = 'MAGNET'
            size = torrent_params['size']

            itemlist.append(
                Item(channel=item.channel,
                     action="play",
                     url=url,
                     url_org=filetools.join(path_out, file),
                     server='torrent',
                     title=filetools.join(
                         filetools.basename(path_out.rstrip('/').rstrip('\\')),
                         file).title() + " [%s]" % size,
                     contentTitle=filetools.join(
                         filetools.basename(path_out.rstrip('/').rstrip('\\')),
                         file).title(),
                     contentType="movie",
                     unify=False,
                     torrents_path=torrent_params['torrents_path'],
                     infoLabels={"tmdb_id": "111"},
                     context=context,
                     btdigg=btdigg))
            if len(itemlist) > 1:
                itemlist = sorted(itemlist,
                                  key=lambda it: it.title)  #clasificamos

    return itemlist
Example #21
0
def main(overwrite=True):
    logger.info("pelisalacarta.library_service Actualizando series...")
    p_dialog = None

    try:

        if config.get_setting("updatelibrary") == "true":
            if not overwrite:  # No venimos del canal configuracion
                updatelibrary_wait = [0, 10000, 20000, 30000, 60000]
                wait = updatelibrary_wait[int(
                    config.get_setting("updatelibrary_wait"))]
                if wait > 0:
                    import xbmc
                    xbmc.sleep(wait)

            heading = 'Actualizando biblioteca....'
            p_dialog = platformtools.dialog_progress_bg(
                'pelisalacarta', heading)
            p_dialog.update(0, '')
            show_list = []

            for path, folders, files in filetools.walk(library.TVSHOWS_PATH):
                show_list.extend([
                    filetools.join(path, f) for f in files if f == "tvshow.nfo"
                ])

            # fix float porque la division se hace mal en python 2.x
            t = float(100) / len(show_list)

            for i, tvshow_file in enumerate(show_list):
                serie = Item().fromjson(filetools.read(tvshow_file, 1))
                path = filetools.dirname(tvshow_file)

                logger.info("pelisalacarta.library_service serie=" +
                            serie.contentSerieName)
                p_dialog.update(int(math.ceil((i + 1) * t)), heading,
                                serie.contentSerieName)

                if not serie.active:
                    continue

                # si la serie esta activa se actualiza
                logger.info("pelisalacarta.library_service Actualizando " +
                            path)

                # logger.debug("%s: %s" %(serie.contentSerieName,str(list_canales) ))
                for channel, url in serie.library_urls.items():
                    serie.channel = channel
                    serie.url = url

                    p_dialog.update(
                        int(math.ceil((i + 1) * t)), heading, "%s: %s" %
                        (serie.contentSerieName, serie.channel.capitalize()))
                    try:
                        pathchannels = filetools.join(
                            config.get_runtime_path(), "channels",
                            serie.channel + '.py')
                        logger.info(
                            "pelisalacarta.library_service Cargando canal: " +
                            pathchannels + " " + serie.channel)

                        if serie.library_filter_show:
                            serie.show = serie.library_filter_show.get(
                                channel, serie.contentSerieName)

                        obj = imp.load_source(serie.channel, pathchannels)
                        itemlist = obj.episodios(serie)

                        try:
                            library.save_library_episodes(path,
                                                          itemlist,
                                                          serie,
                                                          silent=True,
                                                          overwrite=overwrite)

                        except Exception as ex:
                            logger.info(
                                "pelisalacarta.library_service Error al guardar los capitulos de la serie"
                            )
                            template = "An exception of type {0} occured. Arguments:\n{1!r}"
                            message = template.format(
                                type(ex).__name__, ex.args)
                            logger.info(message)

                    except Exception as ex:
                        logger.error(
                            "Error al obtener los episodios de: {0}".format(
                                serie.show))
                        template = "An exception of type {0} occured. Arguments:\n{1!r}"
                        message = template.format(type(ex).__name__, ex.args)
                        logger.info(message)

            p_dialog.close()

        else:
            logger.info(
                "No actualiza la biblioteca, está desactivado en la configuración de pelisalacarta"
            )

    except Exception as ex:
        logger.info(
            "pelisalacarta.library_service Se ha producido un error al actualizar las series"
        )
        template = "An exception of type {0} occured. Arguments:\n{1!r}"
        message = template.format(type(ex).__name__, ex.args)
        logger.info(message)

        if p_dialog:
            p_dialog.close()
Example #22
0
def main(overwrite=True):
    logger.info("pelisalacarta.library_service Actualizando series...")
    p_dialog = None

    try:

        if config.get_setting("updatelibrary") == "true":
            if not overwrite: # No venimos del canal configuracion
                updatelibrary_wait = [0, 10000, 20000, 30000, 60000]
                wait = updatelibrary_wait[int(config.get_setting("updatelibrary_wait"))]
                if wait > 0:
                    import xbmc
                    xbmc.sleep(wait)

            heading = 'Actualizando biblioteca....'
            p_dialog = platformtools.dialog_progress_bg('pelisalacarta', heading)
            p_dialog.update(0, '')
            show_list = []

            for path, folders, files in filetools.walk(library.TVSHOWS_PATH):
                show_list.extend([filetools.join(path, f) for f in files if f == "tvshow.nfo"])

            # fix float porque la division se hace mal en python 2.x
            t = float(100) / len(show_list)

            for i, tvshow_file in enumerate(show_list):
                serie = Item().fromjson(filetools.read(tvshow_file, 1))
                path = filetools.dirname(tvshow_file)

                logger.info("pelisalacarta.library_service serie=" + serie.contentSerieName)
                p_dialog.update(int(math.ceil((i+1) * t)), heading, serie.contentSerieName)

                if not serie.active:
                    continue

                # si la serie esta activa se actualiza
                logger.info("pelisalacarta.library_service Actualizando " + path)

                # logger.debug("%s: %s" %(serie.contentSerieName,str(list_canales) ))
                for channel, url in serie.library_urls.items():
                    serie.channel = channel
                    serie.url = url

                    p_dialog.update(int(math.ceil((i + 1) * t)), heading, "%s: %s" % (serie.contentSerieName,
                                                                                      serie.channel.capitalize()))
                    try:
                        pathchannels = filetools.join(config.get_runtime_path(), "channels", serie.channel + '.py')
                        logger.info("pelisalacarta.library_service Cargando canal: " + pathchannels + " " +
                                    serie.channel)

                        if serie.library_filter_show:
                            serie.show = serie.library_filter_show.get(channel, serie.contentSerieName)

                        obj = imp.load_source(serie.channel, pathchannels)
                        itemlist = obj.episodios(serie)

                        try:
                            library.save_library_episodes(path, itemlist, serie, silent=True, overwrite=overwrite)

                        except Exception as ex:
                            logger.info("pelisalacarta.library_service Error al guardar los capitulos de la serie")
                            template = "An exception of type {0} occured. Arguments:\n{1!r}"
                            message = template.format(type(ex).__name__, ex.args)
                            logger.info(message)

                    except Exception as ex:
                        logger.error("Error al obtener los episodios de: {0}".
                                     format(serie.show))
                        template = "An exception of type {0} occured. Arguments:\n{1!r}"
                        message = template.format(type(ex).__name__, ex.args)
                        logger.info(message)

            p_dialog.close()

        else:
            logger.info("No actualiza la biblioteca, está desactivado en la configuración de pelisalacarta")

    except Exception as ex:
        logger.info("pelisalacarta.library_service Se ha producido un error al actualizar las series")
        template = "An exception of type {0} occured. Arguments:\n{1!r}"
        message = template.format(type(ex).__name__, ex.args)
        logger.info(message)

        if p_dialog:
            p_dialog.close()
Example #23
0
            head_nfo = "Aqui ira el xml"  # TODO

        item_tvshow = Item(title=item.contentTitle,
                           channel="biblioteca",
                           action="get_temporadas",
                           fanart=item.infoLabels['fanart'],
                           thumbnail=item.infoLabels['thumbnail'],
                           infoLabels=item.infoLabels,
                           path=path.replace(TVSHOWS_PATH, ""))
        item_tvshow.library_playcounts = {}
        item_tvshow.library_urls = {item.channel: item.url}

    else:
        # Si existe tvshow.nfo, pero estamos añadiendo un nuevo canal actualizamos el listado de urls
        head_nfo, item_tvshow = read_nfo(tvshow_path)
        item_tvshow.channel = "biblioteca"
        item_tvshow.action = "get_temporadas"
        item_tvshow.library_urls[item.channel] = item.url

    # FILTERTOOLS
    # si el canal tiene filtro de idiomas, añadimos el canal y el show
    if episodelist and "list_idiomas" in episodelist[0]:
        # si ya hemos añadido un canal previamente con filtro, añadimos o actualizamos el canal y show
        if "library_filter_show" in item_tvshow:
            item_tvshow.library_filter_show[item.channel] = item.show
        # no habia ningún canal con filtro y lo generamos por primera vez
        else:
            item_tvshow.library_filter_show = {item.channel: item.show}

    if item.channel != "descargas":
        item_tvshow.active = 1  # para que se actualice a diario cuando se llame a library_service
Example #24
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
Example #25
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())
Example #26
0
        item.infoLabels['mediatype'] = "tvshow"
        item.infoLabels['title'] = item.contentSerieName
        item_tvshow = Item(title=item.contentSerieName,
                           channel="videolibrary",
                           action="get_seasons",
                           fanart=item.infoLabels['fanart'],
                           thumbnail=item.infoLabels['thumbnail'],
                           infoLabels=item.infoLabels,
                           path=path.replace(TVSHOWS_PATH, ""))
        item_tvshow.library_playcounts = {}
        item_tvshow.library_urls = {item.channel: item.url}

    else:
        # Si existe tvshow.nfo, pero estamos añadiendo un nuevo canal actualizamos el listado de urls
        head_nfo, item_tvshow = read_nfo(tvshow_path)
        item_tvshow.channel = "videolibrary"
        item_tvshow.action = "get_seasons"
        item_tvshow.library_urls[item.channel] = item.url

    # FILTERTOOLS
    # si el canal tiene filtro de idiomas, añadimos el canal y el show
    if episodelist and "list_language" in episodelist[0]:
        # si ya hemos añadido un canal previamente con filtro, añadimos o actualizamos el canal y show
        if "library_filter_show" in item_tvshow:
            if item.title_from_channel:
                item_tvshow.library_filter_show[
                    item.channel] = item.title_from_channel
            else:
                item_tvshow.library_filter_show[item.channel] = item.show
        # no habia ningún canal con filtro y lo generamos por primera vez
        else:
Example #27
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())
Example #28
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())
Example #29
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())
    tvshow_path = filetools.join(path, "tvshow.nfo")
    if not filetools.exists(tvshow_path):
        # Creamos tvshow.nfo, si no existe, con la head_nfo, info de la serie y marcas de episodios vistos
        logger.info("Creando tvshow.nfo: " + tvshow_path)
        head_nfo = scraper.get_nfo(item)

        item_tvshow = Item(title=item.contentTitle, channel="biblioteca", action="get_temporadas",
                           fanart=item.infoLabels['fanart'], thumbnail=item.infoLabels['thumbnail'],
                           infoLabels=item.infoLabels, path=path.replace(TVSHOWS_PATH, ""))
        item_tvshow.library_playcounts = {}
        item_tvshow.library_urls = {item.channel: item.url}

    else:
        # Si existe tvshow.nfo, pero estamos añadiendo un nuevo canal actualizamos el listado de urls
        head_nfo, item_tvshow = read_nfo(tvshow_path)
        item_tvshow.channel = "biblioteca"
        item_tvshow.action = "get_temporadas"
        item_tvshow.library_urls[item.channel] = item.url

    # FILTERTOOLS
    # si el canal tiene filtro de idiomas, añadimos el canal y el show
    if episodelist and "list_idiomas" in episodelist[0]:
        # si ya hemos añadido un canal previamente con filtro, añadimos o actualizamos el canal y show
        if "library_filter_show" in item_tvshow:
            item_tvshow.library_filter_show[item.channel] = item.show
        # no habia ningún canal con filtro y lo generamos por primera vez
        else:
            item_tvshow.library_filter_show = {item.channel: item.show}

    if item.channel != "descargas":
        item_tvshow.active = 1  # para que se actualice a diario cuando se llame a library_service
Example #31
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 = 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)

    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 = [
            config.get_localized_string(70089) % k.capitalize()
            for k in 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_canales.items():
        if filtro_canal and filtro_canal != nom_canal.capitalize():
            continue

        item_canal = Item()
        item_canal.channel = nom_canal

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

        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)
            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
        for server in 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

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