Ejemplo n.º 1
0
def findvideos(item):
    logger.info()
    from core import filetools
    from lib import generictools

    itemlist = []
    size = ''
    torrent_params = {
        'url': item.url,
        'torrents_path': None,
        'local_torr': item.torrents_path,
        'lookup': False,
        'force': True,
        'data_torrent': True,
        'subtitles': True,
        'file_list': True
    }

    #logger.debug(item)

    FOLDER_MOVIES = config.get_setting("folder_movies")
    FOLDER_TVSHOWS = config.get_setting("folder_tvshows")
    FOLDER = FOLDER_TVSHOWS if item.infoLabels[
        'mediatype'] == 'episode' else FOLDER_MOVIES
    VIDEOLIBRARY_PATH = config.get_videolibrary_path()
    MOVIES_PATH = filetools.join(VIDEOLIBRARY_PATH, FOLDER_MOVIES)
    TVSHOWS_PATH = filetools.join(VIDEOLIBRARY_PATH, FOLDER_TVSHOWS)
    VIDEO_FOLDER = filetools.join(VIDEOLIBRARY_PATH, FOLDER)

    # Viene desde Kodi/Videoteca de una canal desactivado
    if not item.list_type:
        if item.emergency_urls:
            # Llamamos al método para crear el título general del vídeo, con toda la información obtenida de TMDB
            item.infoLabels['playcount'] = 0
            if item.contentChannel == 'videolibrary':
                item.armagedon = True  # Lo marcammos como URLs de Emergencia
            item.channel_recovery = 'url'
            item, itemlist = generictools.post_tmdb_findvideos(item, itemlist)

            for x, link in enumerate(item.emergency_urls[0]):
                quality = item.quality
                if link.startswith('magnet'):
                    link_path = link
                    item.torrents_path = ''
                else:
                    link_path = filetools.join(VIDEO_FOLDER, link)

                if link_path.startswith('magnet') or filetools.isfile(
                        link_path):
                    if btdigg_magnet in link_path and len(
                            item.emergency_urls) > 3 and len(
                                item.emergency_urls[3]) >= x + 1:
                        try:
                            z, quality, size = item.emergency_urls[3][x].split(
                                '#')
                        except:
                            pass
                    else:
                        torrent_params['url'] = link_path
                        torrent_params['torrents_path'] = link_path
                        torrent_params['local_torr'] = link_path
                        torrent_params = generictools.get_torrent_size(
                            link_path,
                            torrent_params=torrent_params,
                            item=item)  # Tamaño en el .torrent
                        size = torrent_params['size']
                        item.torrents_path = torrent_params['torrents_path']
                    if size:
                        # Generamos una copia de Item para trabajar sobre ella
                        item_local = item.clone()

                        item_local.channel = 'url'
                        item_local.url = link_path
                        if btdigg_magnet in item_local.url:
                            item_local.btdigg = True
                        item_local.torrent_info = size

                        item_local.quality = quality
                        # Si viene de la Videoteca de Kodi, mostramos que son URLs de Emergencia
                        if item_local.contentChannel == 'videolibrary':
                            item_local.quality = '[COLOR hotpink][E][/COLOR] [COLOR limegreen]%s[/COLOR]' % item_local.quality

                        #Ahora pintamos el link del Torrent
                        item_local.title = '[[COLOR yellow]?[/COLOR]] [COLOR yellow][Torrent][/COLOR] ' \
                                        + '[COLOR limegreen][%s][/COLOR] [COLOR red]%s[/COLOR] %s' % \
                                        (item_local.quality, str(item_local.language), \
                                        item_local.torrent_info)

                        # Preparamos título y calidad, quitando etiquetas vacías
                        item_local.title = re.sub(
                            r'\s?\[COLOR \w+\]\[\[?\s?\]?\]\[\/COLOR\]', '',
                            item_local.title)
                        item_local.title = re.sub(
                            r'\s?\[COLOR \w+\]\s?\[\/COLOR\]', '',
                            item_local.title)
                        item_local.title = item_local.title.replace("--", "").replace("[]", "")\
                                        .replace("()", "").replace("(/)", "").replace("[/]", "")\
                                        .replace("|", "").strip()

                        item_local.quality = re.sub(
                            r'\s?\[COLOR \w+\]\[\[?\s?\]?\]\[\/COLOR\]', '',
                            item_local.quality)
                        item_local.quality = re.sub(
                            r'\s?\[COLOR \w+\]\s?\[\/COLOR\]', '',
                            item_local.quality)
                        item_local.quality = item_local.quality.replace("--", "").replace("[]", "")\
                                        .replace("()", "").replace("(/)", "").replace("[/]", "")\
                                        .replace("|", "").strip()

                        if not size or 'Magnet' in size:
                            item_local.alive = "??"  #Calidad del link sin verificar
                        elif 'ERROR' in size and 'Pincha' in size:
                            item_local.alive = "ok"  #link en error, CF challenge, Chrome disponible
                        elif 'ERROR' in size and 'Introduce' in size:
                            item_local.alive = "??"  #link en error, CF challenge, ruta de descarga no disponible
                            item_local.channel = 'setting'
                            item_local.action = 'setting_torrent'
                            item_local.unify = False
                            item_local.folder = False
                            item_local.item_org = item.tourl()
                        elif 'ERROR' in size:
                            item_local.alive = "no"  #Calidad del link en error, CF challenge?
                        else:
                            item_local.alive = "ok"  #Calidad del link verificada

                        item_local.action = "play"  #Visualizar vídeo
                        item_local.server = "torrent"  #Seridor Torrent

                        itemlist.append(item_local)  #Pintar pantalla
                        #logger.debug(item_local)

        return itemlist
Ejemplo n.º 2
0
def findvideos(item):
    logger.info()
    itemlist = []
    itemlist_t = []  #Itemlist total de enlaces
    itemlist_f = []  #Itemlist de enlaces filtrados
    if not item.language:
        item.language = ['CAST']  #Castellano por defecto

    post = None
    forced_proxy_opt = None
    referer = None
    if item.post:  # Rescatamos el Post, si lo hay
        post = item.post
    if item.referer:
        referer = item.referer

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

    #Bajamos los datos de la página
    if not item.matches:
        data, response, item, itemlist = generictools.downloadpage(
            item.url,
            timeout=timeout,
            canonical=canonical,
            post=post,
            referer=referer,
            forced_proxy_opt=forced_proxy_opt,
            s2=False,
            item=item,
            itemlist=[])  # Descargamos la página)

    if not data and not item.matches:
        logger.error(
            "ERROR 01: FINDVIDEOS: La Web no responde o la URL es erronea: " +
            item.url + " / DATA: " + data)
        itemlist.append(item.clone(action='', title=item.channel.capitalize() + \
                    ': ERROR 01: FINDVIDEOS:.  La Web no responde o la URL es erronea. Si la Web está activa, reportar el error con el log',
                    folder=False))
        if item.emergency_urls and not item.videolibray_emergency_urls:  # Hay urls de emergencia?
            link_torrent = item.emergency_urls[0][
                0]  # Guardamos la url del .Torrent
            link_magnet = item.emergency_urls[1][
                0]  # Guardamos la url del .Magnet
            item.armagedon = True  # Marcamos la situación como catastrófica
        else:
            if item.videolibray_emergency_urls:  # Si es llamado desde creación de Videoteca...
                return item  # Devolvemos el Item de la llamada
            else:
                return itemlist  # si no hay más datos, algo no funciona, pintamos lo que tenemos

    patron_t = '(?:<div\s*class="enlace_descarga"[^>]+>\s*<a\s*href=)?"([^"]+\.torrent)"'
    patron_m = '(?:<div\s*class="enlace_descarga"[^>]+>\s*<a\s*href=)?"(magnet:?[^"]+)"'
    if not item.armagedon:  # Si es un proceso normal, seguimos
        data_links = data
        for x in range(2):
            link_torrent = scrapertools.find_single_match(data_links, patron_t)
            if link_torrent:
                link_torrent = urlparse.urljoin(host, link_torrent)
                link_torrent = link_torrent.replace(
                    " ", "%20")  # sustituimos espacios por %20, por si acaso
            #logger.info("link Torrent: " + link_torrent)

            link_magnet = scrapertools.find_single_match(data_links, patron_m)
            #logger.info("link Magnet: " + link_magnet)

            if not (link_torrent and link_magnet) and x == 0:
                data_links = generictools.identifying_links(data_links)

    #Si es un lookup para cargar las urls de emergencia en la Videoteca...
    if (link_torrent or link_magnet) and item.videolibray_emergency_urls:
        item.emergency_urls = []
        item.emergency_urls.append([link_torrent
                                    ])  #Salvamos el enlace de .torrent
        item.emergency_urls.append([link_magnet
                                    ])  #Salvamos el enlace de .magnet
        return item  #... y nos vamos

    #Añadimos el tamaño para todos
    size = scrapertools.find_single_match(item.quality,
                                          '\s\[(\d+,?\d*?\s\w\s*[b|B]s*)\]')
    if size:
        item.title = re.sub('\s\[\d+,?\d*?\s\w\s*[b|B]s*\]', '',
                            item.title)  #Quitamos size de título, si lo traía
        item.quality = re.sub(
            '\s\[\d+,?\d*?\s\w\s*[b|B]s*\]', '',
            item.quality)  #Quitamos size de calidad, si lo traía

    if not link_torrent and not link_magnet:  #error
        item = generictools.web_intervenida(
            item, data)  #Verificamos que no haya sido clausurada
        if item.intervencion:  #Sí ha sido clausurada judicialmente
            item, itemlist = generictools.post_tmdb_findvideos(
                item, itemlist)  #Llamamos al método para el pintado del error
        else:
            logger.error(
                "ERROR 02: FINDVIDEOS: El archivo Torrent no existe o ha cambiado la estructura de la Web "
                + " / PATRON: " + patron_t + " / " + patron_m + " / DATA: " +
                data)
            itemlist.append(
                item.clone(
                    action='',
                    title=item.channel.capitalize() +
                    ': ERROR 02: FINDVIDEOS: El archivo Torrent no existe o ha cambiado la estructura de la Web.  Verificar en la Web y reportar el error con el log',
                    folder=False))
        if item.emergency_urls and not item.videolibray_emergency_urls:  #Hay urls de emergencia?
            link_torrent = item.emergency_urls[0][
                0]  #Guardamos la url del .Torrent
            link_magnet = item.emergency_urls[1][
                0]  #Guardamos la url del .Magnet
            item.armagedon = True  #Marcamos la situación como catastrófica
        else:
            if item.videolibray_emergency_urls:  #Si es llamado desde creación de Videoteca...
                return item  #Devolvemos el Item de la llamada
            else:
                return itemlist  #si no hay más datos, algo no funciona, pintamos lo que tenemos

    #Llamamos al método para crear el título general del vídeo, con toda la información obtenida de TMDB
    item, itemlist = generictools.post_tmdb_findvideos(item, itemlist)

    if not size and not item.armagedon:
        torrent_params['url'] = link_torrent
        torrent_params = generictools.get_torrent_size(
            link_torrent,
            torrent_params=torrent_params,
            referer=host,
            item=item)  # Tamaño en el .torrent
        size = torrent_params['size']
        if torrent_params['torrents_path']:
            item.torrents_path = torrent_params['torrents_path']
    if size:
        size = size.replace('GB', 'G·B').replace('Gb', 'G·b').replace('MB', 'M·B')\
                        .replace('Mb', 'M·b').replace('.', ',')

    #Ahora pintamos el link del Torrent, si lo hay
    if link_torrent:  # Hay Torrent ?
        #Generamos una copia de Item para trabajar sobre ella
        item_local = item.clone()

        item_local.torrent_info = "[Torrent] "
        item_local.torrent_info += '%s' % size  #Agregamos size
        if not item.unify:
            item_local.torrent_info = '[%s]' % item_local.torrent_info.strip(
            ).strip(',')
        if item.armagedon:  #Si es catastrófico, lo marcamos
            item_local.quality = '[/COLOR][COLOR hotpink][E] [COLOR limegreen]%s' % item_local.quality
        item_local.url = link_torrent
        if item_local.url and item.emergency_urls and not item.armagedon:
            item_local.torrent_alt = item.emergency_urls[0][
                0]  #Guardamos la url del .Torrent ALTERNATIVA

        item_local.title = '[[COLOR yellow]?[/COLOR]] [COLOR yellow][Torrent][/COLOR] ' \
                        + '[COLOR limegreen][%s][/COLOR] [COLOR red]%s[/COLOR] %s' % \
                        (item_local.quality, str(item_local.language),  \
                        item_local.torrent_info)                                #Preparamos título de Torrent

        #Preparamos título y calidad, quitamos etiquetas vacías
        item_local.title = re.sub(r'\s?\[COLOR \w+\]\[\[?\s?\]?\]\[\/COLOR\]',
                                  '', item_local.title)
        item_local.title = re.sub(r'\s?\[COLOR \w+\]\s?\[\/COLOR\]', '',
                                  item_local.title)
        item_local.title = item_local.title.replace("--", "").replace(
            "[]", "").replace("()", "").replace("(/)", "").replace("[/]",
                                                                   "").strip()
        item_local.quality = re.sub(
            r'\s?\[COLOR \w+\]\[\[?\s?\]?\]\[\/COLOR\]', '',
            item_local.quality)
        item_local.quality = re.sub(r'\s?\[COLOR \w+\]\s?\[\/COLOR\]', '',
                                    item_local.quality)
        item_local.quality = item_local.quality.replace("--", "").replace(
            "[]", "").replace("()", "").replace("(/)", "").replace("[/]",
                                                                   "").strip()

        if not size or 'Magnet' in size:
            item_local.alive = "??"  # Calidad del link sin verificar
        elif 'ERROR' in size and 'Pincha' in size:
            item_local.alive = "ok"  # link en error, CF challenge, Chrome disponible
        elif 'ERROR' in size and 'Introduce' in size:
            item_local.alive = "??"  # link en error, CF challenge, ruta de descarga no disponible
            item_local.channel = 'setting'
            item_local.action = 'setting_torrent'
            item_local.unify = False
            item_local.folder = False
            item_local.item_org = item.tourl()
        elif 'ERROR' in size:
            item_local.alive = "no"  # Calidad del link en error, CF challenge?
        else:
            item_local.alive = "ok"  # Calidad del link verificada
        if item_local.channel != 'setting':
            item_local.action = "play"  # Visualizar vídeo
            item_local.server = "torrent"  # Seridor Torrent

        itemlist_t.append(
            item_local.clone())  # Pintar pantalla, si no se filtran idiomas

        # Requerido para FilterTools
        if config.get_setting(
                'filter_languages',
                channel) > 0:  # Si hay idioma seleccionado, se filtra
            itemlist_f = filtertools.get_link(
                itemlist_f, item_local,
                list_language)  #Pintar pantalla, si no está vacío

        if len(itemlist_f) > 0:  #Si hay entradas filtradas...
            itemlist.extend(itemlist_f)  #Pintamos pantalla filtrada
        else:
            if config.get_setting('filter_languages', channel) > 0 and len(
                    itemlist_t) > 0:  #Si no hay entradas filtradas ...
                thumb_separador = get_thumb(
                    "next.png")  #... pintamos todo con aviso
                itemlist.append(
                    Item(
                        channel=item.channel,
                        url=host,
                        title=
                        "[COLOR red][B]NO hay elementos con el idioma seleccionado[/B][/COLOR]",
                        thumbnail=thumb_separador,
                        folder=False))
            itemlist.extend(
                itemlist_t)  #Pintar pantalla con todo si no hay filtrado

    #Ahora pintamos el link del Magnet, si lo hay
    itemlist_t = []  #Itemlist total de enlaces
    itemlist_f = []  #Itemlist de enlaces filtrados
    if link_magnet:  # Hay Magnet ?
        #Generamos una copia de Item para trabajar sobre ella
        item_local = item.clone()

        item_local.torrent_info = "[Magnet] "
        item_local.torrent_info += '%s' % size  #Agregamos size
        if not item.unify:
            item_local.torrent_info = '[%s]' % item_local.torrent_info.strip(
            ).strip(',')
        if item.armagedon:  #Si es catastrófico, lo marcamos
            item_local.quality = '[/COLOR][COLOR hotpink][E] [COLOR limegreen]%s' % item_local.quality
        item_local.url = link_magnet

        item_local.title = '[[COLOR yellow]?[/COLOR]] [COLOR yellow][Torrent][/COLOR] ' \
                        + '[COLOR limegreen][%s][/COLOR] [COLOR red]%s[/COLOR] %s' % \
                        (item_local.quality, str(item_local.language),  \
                        item_local.torrent_info)                                #Preparamos título de Magnet

        item_local.title = re.sub(r'\s\[COLOR \w+\]\[\[?\]?\]\[\/COLOR\]', '',
                                  item_local.title)  #Quitamos etiquetas vacías
        item_local.title = re.sub(r'\s\[COLOR \w+\]\[\/COLOR\]', '',
                                  item_local.title)  #Quitamos colores vacíos
        item_local.alive = "??"  #Calidad del link sin verificar
        item_local.action = "play"  #Visualizar vídeo
        item_local.server = "torrent"  #Seridor Torrent

        itemlist_t.append(
            item_local.clone())  #Pintar pantalla, si no se filtran idiomas

        # Requerido para FilterTools
        if config.get_setting(
                'filter_languages',
                channel) > 0:  #Si hay idioma seleccionado, se filtra
            itemlist_f = filtertools.get_link(
                itemlist_f, item_local,
                list_language)  #Pintar pantalla, si no está vacío

        if len(itemlist_f) > 0:  #Si hay entradas filtradas...
            itemlist.extend(itemlist_f)  #Pintamos pantalla filtrada
        else:
            if config.get_setting('filter_languages', channel) > 0 and len(
                    itemlist_t) > 0:  #Si no hay entradas filtradas ...
                thumb_separador = get_thumb(
                    "next.png")  #... pintamos todo con aviso
                itemlist.append(
                    Item(
                        channel=item.channel,
                        url=host,
                        title=
                        "[COLOR red][B]NO hay elementos con el idioma seleccionado[/B][/COLOR]",
                        thumbnail=thumb_separador,
                        folder=False))
            itemlist.extend(
                itemlist_t)  #Pintar pantalla con todo si no hay filtrado

    #logger.debug("TORRENT: " + link_torrent + "MAGNET: " + link_magnet + " / title gen/torr: " + item.title + " / " + item_local.title + " / calidad: " + item_local.quality + " / tamaño: " + size + " / content: " + item_local.contentTitle + " / " + item_local.contentSerieName)
    #logger.debug(item_local)

    # Requerido para AutoPlay
    autoplay.start(itemlist, item)  #Lanzamos Autoplay

    return itemlist
Ejemplo n.º 3
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
Ejemplo n.º 4
0
def findvideos(item):
    logger.info()
    itemlist = []
    itemlist_t = []                                                             #Itemlist total de enlaces
    itemlist_f = []                                                             #Itemlist de enlaces filtrados
    if not item.language:
        item.language = ['CAST']                                                #Castellano por defecto
        
    try:
        tmdb.set_infoLabels(item, True)                                         #TMDB actualizado
    except:
        pass

    #Bajamos los datos de la página
    data = ''
    try:
        data = re.sub(r"\n|\r|\t|\s{2}|(<!--.*?-->)", "", httptools.downloadpage(item.url, timeout=timeout).data)
    except:
        pass
        
    if not data:
        logger.error("ERROR 01: FINDVIDEOS: La Web no responde o la URL es erronea: " + item.url + " / DATA: " + data)
        itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 01: FINDVIDEOS:.  La Web no responde o la URL es erronea. Si la Web está activa, reportar el error con el log'))
        if item.emergency_urls and not item.videolibray_emergency_urls:         #Hay urls de emergencia?
            link_torrent = item.emergency_urls[0][0]                            #Guardamos la url del .Torrent
            link_magnet = item.emergency_urls[1][0]                             #Guardamos la url del .Magnet
            item.armagedon = True                                               #Marcamos la situación como catastrófica 
        else:
            if item.videolibray_emergency_urls:                                 #Si es llamado desde creación de Videoteca...
                return item                                                     #Devolvemos el Item de la llamada
            else:
                return itemlist                         #si no hay más datos, algo no funciona, pintamos lo que tenemos
    #data = unicode(data, "utf-8", errors="replace")

    patron_t = '<div class="enlace_descarga".*?<a href="(.*?\.torrent)"'
    patron_m = '<div class="enlace_descarga".*?<a href="(magnet:?.*?)"'
    if not item.armagedon:                                                      #Si es un proceso normal, seguimos
        link_torrent = scrapertools.find_single_match(data, patron_t)
        link_torrent = urlparse.urljoin(item.url, link_torrent)
        link_torrent = link_torrent.replace(" ", "%20")                         #sustituimos espacios por %20, por si acaso
        #logger.info("link Torrent: " + link_torrent)
        
        link_magnet = scrapertools.find_single_match(data, patron_m)
        link_magnet = urlparse.urljoin(item.url, link_magnet)
        #logger.info("link Magnet: " + link_magnet)
    
    #Si es un lookup para cargar las urls de emergencia en la Videoteca...
    if (link_torrent or link_magnet) and item.videolibray_emergency_urls:
        item.emergency_urls = []
        item.emergency_urls.append([link_torrent])                              #Salvamos el enlace de .torrent
        item.emergency_urls.append([link_magnet])                               #Salvamos el enlace de .magnet
        return item                                                             #... y nos vamos
    
    #Añadimos el tamaño para todos
    size = scrapertools.find_single_match(item.quality, '\s\[(\d+,?\d*?\s\w\s*[b|B]s*)\]')
    if size:
        item.title = re.sub('\s\[\d+,?\d*?\s\w\s*[b|B]s*\]', '', item.title)    #Quitamos size de título, si lo traía
        item.title = '%s [%s]' % (item.title, size)                             #Agregamos size al final del título
        item.quality = re.sub('\s\[\d+,?\d*?\s\w\s*[b|B]s*\]', '', item.quality)    #Quitamos size de calidad, si lo traía
    
    if not link_torrent and not link_magnet:                                    #error
        item = generictools.web_intervenida(item, data)                         #Verificamos que no haya sido clausurada
        if item.intervencion:                                                   #Sí ha sido clausurada judicialmente
            item, itemlist = generictools.post_tmdb_findvideos(item, itemlist)  #Llamamos al método para el pintado del error
        else:
            logger.error("ERROR 02: FINDVIDEOS: El archivo Torrent no existe o ha cambiado la estructura de la Web " + " / PATRON: " + patron_t + " / " + patron_m + " / DATA: " + data)
            itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 02: FINDVIDEOS: El archivo Torrent no existe o ha cambiado la estructura de la Web.  Verificar en la Web y reportar el error con el log'))
        if item.emergency_urls and not item.videolibray_emergency_urls:         #Hay urls de emergencia?
            link_torrent = item.emergency_urls[0][0]                            #Guardamos la url del .Torrent
            link_magnet = item.emergency_urls[1][0]                             #Guardamos la url del .Magnet
            item.armagedon = True                                               #Marcamos la situación como catastrófica 
        else:
            if item.videolibray_emergency_urls:                                 #Si es llamado desde creación de Videoteca...
                return item                                                     #Devolvemos el Item de la llamada
            else:
                return itemlist                         #si no hay más datos, algo no funciona, pintamos lo que tenemos

    #Llamamos al método para crear el título general del vídeo, con toda la información obtenida de TMDB
    item, itemlist = generictools.post_tmdb_findvideos(item, itemlist)
    
    if not size and not item.armagedon:
        size = generictools.get_torrent_size(link_torrent)                      #Buscamos el tamaño en el .torrent
    if size:
        item.quality = '%s [%s]' % (item.quality, size)                         #Agregamos size al final de calidad
        item.quality = item.quality.replace("GB", "G B").replace("MB", "M B").replace("Gb", "G B").replace("Mb", "M B")                                                                        #Se evita la palabra reservada en Unify
    #Ahora pintamos el link del Torrent, si lo hay
    if link_torrent:		                                                    # Hay Torrent ?
        #Generamos una copia de Item para trabajar sobre ella
        item_local = item.clone()
    
        if item_local.quality:
            item_local.quality += " "
        item_local.quality += "[Torrent]"
        if item.armagedon:                                                      #Si es catastrófico, lo marcamos
            item_local.quality = '[/COLOR][COLOR hotpink][E] [COLOR limegreen]%s' % item_local.quality
        item_local.url = link_torrent
        if item_local.url and item.emergency_urls and not item.armagedon:
            item_local.torrent_alt = item.emergency_urls[0][0]                  #Guardamos la url del .Torrent ALTERNATIVA
        
        item_local.title = '[COLOR yellow][?][/COLOR] [COLOR yellow][Torrent][/COLOR] [COLOR limegreen][%s][/COLOR] [COLOR red]%s[/COLOR]' % (item_local.quality, str(item_local.language))        #Preparamos título de Torrent
        
        #Preparamos título y calidad, quitamos etiquetas vacías
        item_local.title = re.sub(r'\s?\[COLOR \w+\]\[\[?\s?\]?\]\[\/COLOR\]', '', item_local.title)    
        item_local.title = re.sub(r'\s?\[COLOR \w+\]\s?\[\/COLOR\]', '', item_local.title)
        item_local.title = item_local.title.replace("--", "").replace("[]", "").replace("()", "").replace("(/)", "").replace("[/]", "").strip()
        item_local.quality = re.sub(r'\s?\[COLOR \w+\]\[\[?\s?\]?\]\[\/COLOR\]', '', item_local.quality)
        item_local.quality = re.sub(r'\s?\[COLOR \w+\]\s?\[\/COLOR\]', '', item_local.quality)
        item_local.quality = item_local.quality.replace("--", "").replace("[]", "").replace("()", "").replace("(/)", "").replace("[/]", "").strip()
                
        item_local.alive = "??"                                                 #Calidad del link sin verificar
        item_local.action = "play"                                              #Visualizar vídeo
        item_local.server = "torrent"                                           #Seridor Torrent
        
        itemlist_t.append(item_local.clone())                                   #Pintar pantalla, si no se filtran idiomas
        
        # Requerido para FilterTools
        if config.get_setting('filter_languages', channel) > 0:                 #Si hay idioma seleccionado, se filtra
            itemlist_f = filtertools.get_link(itemlist_f, item_local, list_language)  #Pintar pantalla, si no está vacío
            
        if len(itemlist_f) > 0:                                                 #Si hay entradas filtradas...
            itemlist.extend(itemlist_f)                                         #Pintamos pantalla filtrada
        else:                                                                       
            if config.get_setting('filter_languages', channel) > 0 and len(itemlist_t) > 0: #Si no hay entradas filtradas ...
                thumb_separador = get_thumb("next.png")                             #... pintamos todo con aviso
                itemlist.append(Item(channel=item.channel, url=host, title="[COLOR red][B]NO hay elementos con el idioma seleccionado[/B][/COLOR]", thumbnail=thumb_separador))
            itemlist.extend(itemlist_t)                                         #Pintar pantalla con todo si no hay filtrado
    
    #Ahora pintamos el link del Magnet, si lo hay
    itemlist_t = []                                                             #Itemlist total de enlaces
    itemlist_f = []                                                             #Itemlist de enlaces filtrados
    if link_magnet:		                                                        # Hay Magnet ?
        #Generamos una copia de Item para trabajar sobre ella
        item_local = item.clone()
        
        if item_local.quality:
            item_local.quality += " "
        item_local.quality = item_local.quality.replace("[Torrent]", "") + "[Magnet]"
        if item.armagedon:                                                      #Si es catastrófico, lo marcamos
            item_local.quality = '[/COLOR][COLOR hotpink][E] [COLOR limegreen]%s' % item_local.quality
        item_local.url = link_magnet
        item_local.title = '[COLOR yellow][?][/COLOR] [COLOR yellow][Torrent][/COLOR] [COLOR limegreen][%s][/COLOR] [COLOR red]%s[/COLOR]' % (item_local.quality, str(item_local.language))        #Preparamos título de Magnet
        item_local.title = re.sub(r'\s\[COLOR \w+\]\[\[?\]?\]\[\/COLOR\]', '', item_local.title)    #Quitamos etiquetas vacías
        item_local.title = re.sub(r'\s\[COLOR \w+\]\[\/COLOR\]', '', item_local.title)          #Quitamos colores vacíos
        item_local.alive = "??"                                                 #Calidad del link sin verificar
        item_local.action = "play"                                              #Visualizar vídeo
        item_local.server = "torrent"                                           #Seridor Torrent
        
        itemlist_t.append(item_local.clone())                                   #Pintar pantalla, si no se filtran idiomas
        
        # Requerido para FilterTools
        if config.get_setting('filter_languages', channel) > 0:                 #Si hay idioma seleccionado, se filtra
            itemlist_f = filtertools.get_link(itemlist_f, item_local, list_language)  #Pintar pantalla, si no está vacío
            
        if len(itemlist_f) > 0:                                                 #Si hay entradas filtradas...
            itemlist.extend(itemlist_f)                                         #Pintamos pantalla filtrada
        else:                                                                       
            if config.get_setting('filter_languages', channel) > 0 and len(itemlist_t) > 0: #Si no hay entradas filtradas ...
                thumb_separador = get_thumb("next.png")                             #... pintamos todo con aviso
                itemlist.append(Item(channel=item.channel, url=host, title="[COLOR red][B]NO hay elementos con el idioma seleccionado[/B][/COLOR]", thumbnail=thumb_separador))
            itemlist.extend(itemlist_t)                                         #Pintar pantalla con todo si no hay filtrado
    
    #logger.debug("TORRENT: " + link_torrent + "MAGNET: " + link_magnet + " / title gen/torr: " + item.title + " / " + item_local.title + " / calidad: " + item_local.quality + " / tamaño: " + size + " / content: " + item_local.contentTitle + " / " + item_local.contentSerieName)
    #logger.debug(item_local)

    # Requerido para AutoPlay
    autoplay.start(itemlist, item)                                              #Lanzamos Autoplay
    
    return itemlist
Ejemplo n.º 5
0
def findvideos(item):
    logger.info()
    
    itemlist = []
    itemlist_t = []                                                             #Itemlist total de enlaces
    itemlist_f = []                                                             #Itemlist de enlaces filtrados
    matches = []

    #logger.debug(item)

    #Ahora tratamos los enlaces .torrent con las diferentes calidades
    for scrapedurl, scrapedserver in item.url_enlaces:

        #Generamos una copia de Item para trabajar sobre ella
        item_local = item.clone()

        item_local.url = scrapedurl
        item_local.server = scrapedserver.lower()
        item_local.action = "play" 
        
        #Buscamos tamaño en el archivo .torrent
        size = ''
        if item_local.server == 'torrent' and not size and not item_local.url.startswith('magnet:'):
            size = generictools.get_torrent_size(item_local.url) #              Buscamos el tamaño en el .torrent desde la web

        if size:
            size = size.replace('GB', 'G·B').replace('Gb', 'G·b').replace('MB', 'M·B')\
                        .replace('Mb', 'M·b').replace('.', ',')
            item_local.torrent_info = '%s, ' % size                             #Agregamos size
        if item_local.url.startswith('magnet:') and not 'Magnet' in item_local.torrent_info:
            item_local.torrent_info += ' Magnet'
        if item_local.torrent_info:
            item_local.torrent_info = item_local.torrent_info.strip().strip(',')
            if not item.unify:
                item_local.torrent_info = '[%s]' % item_local.torrent_info

        #Ahora pintamos lo enlaces
        item_local.title = '[[COLOR yellow]?[/COLOR]] [COLOR yellow][%s][/COLOR] ' %item_local.server.capitalize() \
                        + '[COLOR limegreen][%s][/COLOR] [COLOR red]%s[/COLOR] %s' % \
                        (item_local.quality, str(item_local.language), \
                        item_local.torrent_info)

        # Verificamos enlaces
        if item_local.server != 'torrent':
            if config.get_setting("hidepremium"):                               #Si no se aceptan servidore premium, se ignoran
                if not servertools.is_server_enabled(item_local.server):
                    continue
            devuelve = servertools.findvideosbyserver(item_local.url, item_local.server)    #existe el link ?
            if not devuelve:
                continue
            item_local.url = devuelve[0][1]
            item_local.alive = servertools.check_video_link(item_local.url, item_local.server, timeout=timeout)     #activo el link ?
            if 'NO' in item_local.alive:
                continue
        else:
            if not size or 'Magnet' in size:
                item_local.alive = "??"                                         #Calidad del link sin verificar
            elif 'ERROR' in size:
                item_local.alive = "no"                                         #Calidad del link en error?
                continue
            else:
                item_local.alive = "ok"                                         #Calidad del link verificada
        
        itemlist_t.append(item_local.clone())                                   #Pintar pantalla, si no se filtran idiomas
        
        # Requerido para FilterTools
        if config.get_setting('filter_languages', channel) > 0:                 #Si hay idioma seleccionado, se filtra
            itemlist_f = filtertools.get_link(itemlist_f, item_local, list_language)  #Pintar pantalla, si no está vacío

    if len(itemlist_f) > 0:                                                     #Si hay entradas filtradas...
        itemlist.extend(itemlist_f)                                             #Pintamos pantalla filtrada
    else:                                                                       
        if config.get_setting('filter_languages', channel) > 0 and len(itemlist_t) > 0: #Si no hay entradas filtradas ...
            thumb_separador = get_thumb("next.png")                             #... pintamos todo con aviso
            itemlist.append(Item(channel=item.channel, url=host, 
                        title="[COLOR red][B]NO hay elementos con el idioma seleccionado[/B][/COLOR]", 
                        thumbnail=thumb_separador, folder=False))
        itemlist.extend(itemlist_t)                                             #Pintar pantalla con todo si no hay filtrado
    
    # Requerido para AutoPlay
    autoplay.start(itemlist, item)                                              #Lanzamos Autoplay
    
    return itemlist
Ejemplo n.º 6
0
def findvideos(item):
    logger.info()
    itemlist = []
    itemlist_t = []  #Itemlist total de enlaces
    itemlist_f = []  #Itemlist de enlaces filtrados
    if not item.language:
        item.language = ['CAST']  #Castellano por defecto
    matches = []
    subtitles = []
    item.category = categoria

    #logger.debug(item)

    if item.extra != 'episodios':
        #Bajamos los datos de la página
        data = ''
        patron = '<div class="secciones"><h1>[^<]+<\/h1><br\s*\/><br\s*\/><div class="fichimagen">\s*<img class="carat" src="([^"]+)"'
        try:
            data = re.sub(
                r"\n|\r|\t|\s{2}|(<!--.*?-->)", "",
                httptools.downloadpage(item.url, timeout=timeout).data)
            #data = unicode(data, "iso-8859-1", errors="replace").encode("utf-8")
        except:
            pass

        if not data:
            logger.error(
                "ERROR 01: FINDVIDEOS: La Web no responde o la URL es erronea: "
                + item.url)
            itemlist.append(
                item.clone(
                    action='',
                    title=item.channel.capitalize() +
                    ': ERROR 01: FINDVIDEOS:.  La Web no responde o la URL es erronea. Si la Web está activa, reportar el error con el log'
                ))

            if item.emergency_urls and not item.videolibray_emergency_urls:  #Hay urls de emergencia?
                matches = item.emergency_urls[
                    1]  #Restauramos matches de vídeos
                subtitles = item.emergency_urls[
                    2]  #Restauramos matches de subtítulos
                item.armagedon = True  #Marcamos la situación como catastrófica
            else:
                if item.videolibray_emergency_urls:  #Si es llamado desde creación de Videoteca...
                    return item  #Devolvemos el Item de la llamada
                else:
                    return itemlist  #si no hay más datos, algo no funciona, pintamos lo que tenemos

        if not item.armagedon:
            #Extraemos el thumb
            if not item.thumbnail:
                item.thumbnail = scrapertools.find_single_match(
                    data, patron)  #guardamos thumb si no existe

            #Extraemos quality, audio, year, country, size, scrapedlanguage
            patron = '<\/script><\/div><ul>(?:<li><label>Fecha de estreno <\/label>[^<]+<\/li>)?(?:<li><label>Genero <\/label>[^<]+<\/li>)?(?:<li><label>Calidad <\/label>([^<]+)<\/li>)?(?:<li><label>Audio <\/label>([^<]+)<\/li>)?(?:<li><label>Fecha <\/label>.*?(\d+)<\/li>)?(?:<li><label>Pais de Origen <\/label>([^<]+)<\/li>)?(?:<li><label>Tama&ntilde;o <\/label>([^<]+)<\/li>)?(<li> Idioma[^<]+<img src=.*?<br \/><\/li>)?'
            try:
                quality = ''
                audio = ''
                year = ''
                country = ''
                size = ''
                scrapedlanguage = ''
                quality, audio, year, country, size, scrapedlanguage = scrapertools.find_single_match(
                    data, patron)
            except:
                pass
            if quality: item.quality = quality
            if audio: item.quality += ' %s' % audio.strip()
            if not item.infoLabels['year'] and year:
                item.infoLabels['year'] = year
            if size:
                item.quality += ' [%s]' % size.replace('GB', 'G B').replace(
                    'Gb', 'G b').replace('MB', 'M B').replace(
                        'Mb', 'M b').replace('.', ',').strip()
            if size:
                item.title = re.sub(
                    r'\s*\[\d+,?\d*?\s\w\s*[b|B]\]', '',
                    item.title)  #Quitamos size de título, si lo traía
                item.title += ' [%s]' % size.replace('GB', 'G B').replace(
                    'Gb', 'G b').replace('MB', 'M B').replace(
                        'Mb', 'M b').replace('.', ',').strip()

            language = []
            matches_lang = re.compile('(\d+.png)',
                                      re.DOTALL).findall(scrapedlanguage)
            for lang in matches_lang:
                if "1.png" in lang and not 'CAST' in language:
                    language += ['CAST']
                if "512.png" in lang and not 'LAT' in language:
                    language += ['LAT']
                if ("1.png" not in lang
                        and "512.png" not in lang) and not 'VOSE' in language:
                    language += ['VOSE']
            if language: item.language = language

            #Extraemos los enlaces .torrent
            #Modalidad de varios archivos
            patron = '<div class="fichadescargat"><\/div><div class="table-responsive"[^>]+>.*?<\/thead><tbody>(.*?)<\/tbody><\/table><\/div>'
            if scrapertools.find_single_match(data, patron):
                data_torrents = scrapertools.find_single_match(data, patron)
                patron = '<tr><td>.*?<\/td><td><a href="([^"]+)"[^>]+><[^>]+><\/a><\/td><\/tr>'
            #Modalidad de un archivo
            else:
                data_torrents = data
                patron = '<div class="fichasubtitulos">.*?<\/div><\/li><\/ul>.*?<a href="([^"]+)"'
            matches = re.compile(patron, re.DOTALL).findall(data_torrents)
            if not matches:  #error
                logger.error(
                    "ERROR 02: FINDVIDEOS: No hay enlaces o ha cambiado la estructura de la Web "
                    + " / PATRON: " + patron + data)
                itemlist.append(
                    item.clone(
                        action='',
                        title=item.channel.capitalize() +
                        ': ERROR 02: FINDVIDEOS: No hay enlaces o ha cambiado la estructura de la Web.  Verificar en la Web esto último y reportar el error con el log'
                    ))

                if item.emergency_urls and not item.videolibray_emergency_urls:  #Hay urls de emergencia?
                    matches = item.emergency_urls[
                        1]  #Restauramos matches de vídeos
                    subtitles = item.emergency_urls[
                        2]  #Restauramos matches de subtítulos
                    item.armagedon = True  #Marcamos la situación como catastrófica
                else:
                    if item.videolibray_emergency_urls:  #Si es llamado desde creación de Videoteca...
                        return item  #Devolvemos el Item de la llamada
                    else:
                        return itemlist  #si no hay más datos, algo no funciona, pintamos lo que tenemos

    else:  #SERIES: ya viene con las urls
        data = item.url  #inicio data por compatibilidad
        matches = [item.url]  #inicio matches por compatibilidad

    #Extraemos las urls de los subtítulos (Platformtools usa item.subtitle como sub-titulo por defecto)
    patron = '<div class="fichasubtitulos">\s*<label class="fichsub">\s*<a href="([^"]+)">Subtitulos\s*<\/a>\s*<\/label>'
    if scrapertools.find_single_match(data, patron) or item.subtitle:
        if item.extra == 'episodios':  #Si viene de Series, ya tengo la primera url
            subtitle = item.subtitle
            del item.subtitle
        else:
            subtitle = scrapertools.find_single_match(data, patron).replace(
                '&#038;', '&').replace('.io/', sufix).replace('.com/', sufix)

        try:
            data_subtitle = re.sub(
                r"\n|\r|\t|\s{2}|(<!--.*?-->)", "",
                httptools.downloadpage(subtitle, timeout=timeout).data)
        except:
            pass

        if not data_subtitle:
            if item.emergency_urls and not item.videolibray_emergency_urls:  #Hay urls de emergencia?
                matches = item.emergency_urls[
                    1]  #Restauramos matches de vídeos
                subtitles = item.emergency_urls[
                    2]  #Restauramos matches de subtítulos
                item.armagedon = True  #Marcamos la situación como catastrófica
        else:
            patron = '<tbody>(<tr class="fichserietabla_b">.*?<\/tr>)<\/tbody>'  #salvamos el bloque
            data_subtitle = scrapertools.find_single_match(
                data_subtitle, patron)
            patron = '<tr class="fichserietabla_b">.*?<a href="([^"]+)"'
            subtitles = re.compile(patron, re.DOTALL).findall(
                data_subtitle)  #Creamos una lista con todos los sub-títulos
        if subtitles:
            item.subtitle = []
            for subtitle in subtitles:
                subtitle = subtitle.replace('&#038;', '&').replace(
                    '.io/', sufix).replace('.com/', sufix)
                item.subtitle.append(subtitle)

    #logger.debug("PATRON: " + patron)
    #logger.debug(matches)
    #logger.debug(subtitles)
    #logger.debug(data)

    #Si es un lookup para cargar las urls de emergencia en la Videoteca...
    if item.videolibray_emergency_urls:
        item.emergency_urls = []  #Iniciamos emergency_urls
        item.emergency_urls.append(
            [])  #Reservamos el espacio para los .torrents locales
        item.emergency_urls.append(
            matches)  #Salvamnos matches de los vídeos...
        item.emergency_urls.append(
            subtitles)  #Salvamnos matches de los subtítulos

    #Llamamos al método para crear el título general del vídeo, con toda la información obtenida de TMDB
    if not item.videolibray_emergency_urls:
        item, itemlist = generictools.post_tmdb_findvideos(item, itemlist)

    #Ahora tratamos los enlaces .torrent
    for scrapedurl in matches:  #leemos los torrents con la diferentes calidades
        #Generamos una copia de Item para trabajar sobre ella
        item_local = item.clone()

        item_local.url = scrapedurl.replace('&#038;', '&').replace(
            '.io/', sufix).replace('.com/', sufix)
        if item.videolibray_emergency_urls:
            item.emergency_urls[0].append(
                scrapedurl)  #guardamos la url y pasamos a la siguiente
            continue
        if item.emergency_urls and not item.videolibray_emergency_urls:
            item_local.torrent_alt = item.emergency_urls[0][
                0]  #Guardamos la url del .Torrent ALTERNATIVA
            if item.armagedon:
                item_local.url = item.emergency_urls[0][
                    0]  #... ponemos la emergencia como primaria
            del item.emergency_urls[0][0]  #Una vez tratado lo limpiamos

        #Buscamos si ya tiene tamaño, si no, los buscamos en el archivo .torrent
        size = scrapertools.find_single_match(
            item_local.quality, '\s*\[(\d+,?\d*?\s\w\s*[b|B])\]')
        if not size and not item.armagedon:
            size = generictools.get_torrent_size(
                scrapedurl)  #Buscamos el tamaño en el .torrent
        if size:
            size = size.replace('GB', 'G B').replace('Gb', 'G b').replace(
                'MB', 'M B').replace('Mb', 'M b')
            item_local.title = re.sub(
                r'\s*\[\d+,?\d*?\s\w\s*[b|B]\]', '',
                item_local.title)  #Quitamos size de título, si lo traía
            item_local.title = '%s [%s]' % (
                item_local.title, size)  #Agregamos size al final del título
            item_local.quality = re.sub(
                r'\s*\[\d+,?\d*?\s\w\s*[b|B]\]', '',
                item_local.quality)  #Quitamos size de calidad, si lo traía
            item_local.quality = '%s [%s]' % (
                item_local.quality, size
            )  #Agregamos size al final de la calidad
        if item.armagedon:  #Si es catastrófico, lo marcamos
            item_local.quality = '[/COLOR][COLOR hotpink][E] [COLOR limegreen]%s' % item_local.quality

        #Ahora pintamos el link del Torrent
        item_local.title = '[COLOR yellow][?][/COLOR] [COLOR yellow][Torrent][/COLOR] [COLOR limegreen][%s][/COLOR] [COLOR red]%s[/COLOR]' % (
            item_local.quality, str(item_local.language))

        #Preparamos título y calidad, quitamos etiquetas vacías
        item_local.title = re.sub(r'\s?\[COLOR \w+\]\[\[?\s?\]?\]\[\/COLOR\]',
                                  '', item_local.title)
        item_local.title = re.sub(r'\s?\[COLOR \w+\]\s?\[\/COLOR\]', '',
                                  item_local.title)
        item_local.title = item_local.title.replace("--", "").replace(
            "[]", "").replace("()", "").replace("(/)", "").replace("[/]",
                                                                   "").strip()
        item_local.quality = re.sub(
            r'\s?\[COLOR \w+\]\[\[?\s?\]?\]\[\/COLOR\]', '',
            item_local.quality)
        item_local.quality = re.sub(r'\s?\[COLOR \w+\]\s?\[\/COLOR\]', '',
                                    item_local.quality)
        item_local.quality = item_local.quality.replace("--", "").replace(
            "[]", "").replace("()",
                              "").replace("(/)",
                                          "").replace("[/]",
                                                      "").replace(".",
                                                                  ",").strip()

        item_local.alive = "??"  #Calidad del link sin verificar
        item_local.action = "play"  #Visualizar vídeo
        item_local.server = "torrent"  #Seridor Torrent

        itemlist_t.append(
            item_local.clone())  #Pintar pantalla, si no se filtran idiomas

        # Requerido para FilterTools
        if config.get_setting(
                'filter_languages',
                channel) > 0:  #Si hay idioma seleccionado, se filtra
            itemlist_f = filtertools.get_link(
                itemlist_f, item_local,
                list_language)  #Pintar pantalla, si no está vacío

        #logger.debug("TORRENT: " + scrapedurl + " / title gen/torr: " + item.title + " / " + item_local.title + " / calidad: " + item_local.quality + " / content: " + item_local.contentTitle + " / " + item_local.contentSerieName)
        #logger.debug(item_local)

    if item.videolibray_emergency_urls:  #Si ya hemos guardado todas las urls...
        return item  #... nos vamos

    if len(itemlist_f) > 0:  #Si hay entradas filtradas...
        itemlist.extend(itemlist_f)  #Pintamos pantalla filtrada
    else:
        if config.get_setting('filter_languages', channel) > 0 and len(
                itemlist_t) > 0:  #Si no hay entradas filtradas ...
            thumb_separador = get_thumb(
                "next.png")  #... pintamos todo con aviso
            itemlist.append(
                Item(
                    channel=item.channel,
                    url=host,
                    title=
                    "[COLOR red][B]NO hay elementos con el idioma seleccionado[/B][/COLOR]",
                    thumbnail=thumb_separador))
        itemlist.extend(
            itemlist_t)  #Pintar pantalla con todo si no hay filtrado

    # Requerido para AutoPlay
    autoplay.start(itemlist, item)  #Lanzamos Autoplay

    return itemlist
Ejemplo n.º 7
0
def findvideos(item):
    logger.info()

    itemlist = []
    itemlist_t = []  #Itemlist total de enlaces
    itemlist_f = []  #Itemlist de enlaces filtrados
    matches = []
    data = ''
    response = {'data': data, 'sucess': False, 'code': 0}
    response = type('HTTPResponse', (), response)

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

    #logger.debug(item)

    #Bajamos los datos de la página
    patron = '<a\s*class="torrent_download[^"]*"\s*href="([^"]+)"'

    if not item.matches:
        data, response, item, itemlist = generictools.downloadpage(
            item.url,
            timeout=timeout,
            canonical=canonical,
            headers=item.headers,
            s2=False,
            patron=patron,
            item=item,
            itemlist=itemlist)  # Descargamos la página

    #Verificamos si se ha cargado una página, y si además tiene la estructura correcta
    if (not data and not item.matches) or response.code == 999:
        if item.emergency_urls and not item.videolibray_emergency_urls:  # Hay urls de emergencia?
            if len(item.emergency_urls) > 1:
                matches = item.emergency_urls[
                    1]  # Restauramos matches de vídeos
            elif len(item.emergency_urls) == 1 and item.emergency_urls[0]:
                matches = item.emergency_urls[
                    0]  # Restauramos matches de vídeos - OLD FORMAT
            item.armagedon = True  # Marcamos la situación como catastrófica
        else:
            if item.videolibray_emergency_urls:  # Si es llamado desde creación de Videoteca...
                return item  # Devolvemos el Item de la llamada
            else:
                return itemlist  # si no hay más datos, algo no funciona, pintamos lo que tenemos

    if not item.armagedon:
        if not item.matches:
            matches = re.compile(patron, re.DOTALL).findall(data)
        else:
            matches = item.matches

    #logger.debug("PATRON: " + patron)
    #logger.debug(matches)
    #logger.debug(data)

    if not matches:  # error
        return itemlist

    # Si es un lookup para cargar las urls de emergencia en la Videoteca...
    if item.videolibray_emergency_urls:
        item.emergency_urls = []  # Iniciamos emergency_urls
        item.emergency_urls.append(
            [])  # Reservamos el espacio para los .torrents locales
        matches_list = []  # Convertimos matches-tuple a matches-list
        for tupla in matches:
            if isinstance(tupla, tuple):
                matches_list.append(list(tupla))
        if matches_list:
            item.emergency_urls.append(
                matches_list)  # Salvamnos matches de los vídeos...
        else:
            item.emergency_urls.append(matches)

    # Llamamos al método para crear el título general del vídeo, con toda la información obtenida de TMDB
    if not item.videolibray_emergency_urls:
        item, itemlist = generictools.post_tmdb_findvideos(item, itemlist)

    # Ahora tratamos los enlaces .torrent con las diferentes calidades
    for x, (scrapedurl) in enumerate(matches):
        scrapedpassword = ''

        #Generamos una copia de Item para trabajar sobre ella
        item_local = item.clone()

        item_local.url = generictools.convert_url_base64(
            scrapedurl, host_torrent)
        if item.videolibray_emergency_urls and item_local.url != scrapedurl:
            item.emergency_urls[1][x][0] = item_local.url

        # Buscamos el enlace definitivo, si es necesario
        if not item_local.url.startswith(
                'magnet') and not item_local.url.endswith('.torrent'):
            patron = '<a\s*id="link"[^>]*href="([^"]+)"'
            data, response, item, itemlist = generictools.downloadpage(
                item_local.url,
                timeout=timeout,
                canonical=canonical,
                s2=False,
                patron=patron,
                item=item,
                itemlist=itemlist)
            item_local.url = scrapertools.find_single_match(data, patron)
            if not item_local.url: continue

        # Restauramos urls de emergencia si es necesario
        local_torr = ''
        if item.emergency_urls and not item.videolibray_emergency_urls:
            try:  # Guardamos la url ALTERNATIVA
                if item.emergency_urls[0][0].startswith(
                        'http') or item.emergency_urls[0][0].startswith('//'):
                    item_local.torrent_alt = generictools.convert_url_base64(
                        item.emergency_urls[0][0], host_torrent)
                else:
                    item_local.torrent_alt = generictools.convert_url_base64(
                        item.emergency_urls[0][0])
            except:
                item_local.torrent_alt = ''
                item.emergency_urls[0] = []
            from core import filetools
            if item.contentType == 'movie':
                FOLDER = config.get_setting("folder_movies")
            else:
                FOLDER = config.get_setting("folder_tvshows")
            if item.armagedon and item_local.torrent_alt:
                item_local.url = item_local.torrent_alt  # Restauramos la url
                if not item.torrent_alt.startswith('http'):
                    local_torr = filetools.join(config.get_videolibrary_path(),
                                                FOLDER, item_local.url)
            if len(item.emergency_urls[0]) > 1:
                del item.emergency_urls[0][0]

        #Buscamos tamaño en el archivo .torrent
        size = ''
        if item_local.torrent_info:
            size = item_local.torrent_info
        if not size and not item.videolibray_emergency_urls and not item_local.url.startswith(
                'magnet:'):
            if not item.armagedon:
                torrent_params['url'] = item_local.url
                torrent_params[
                    'local_torr'] = local_torr or item_local.torrents_path
                torrent_params = generictools.get_torrent_size(
                    item_local.url,
                    torrent_params=torrent_params,
                    item=item_local)
                size = torrent_params['size']
                if torrent_params['torrents_path']:
                    item_local.torrents_path = torrent_params['torrents_path']

                if 'ERROR' in size and item.emergency_urls and not item.videolibray_emergency_urls:
                    item_local.armagedon = True
                    try:  # Restauramos la url
                        if item.emergency_urls[0][0].startswith(
                                'http'
                        ) or item.emergency_urls[0][0].startswith('//'):
                            item_local.url = generictools.convert_url_base64(
                                item.emergency_urls[0][0], host_torrent)
                        else:
                            item_local.url = generictools.convert_url_base64(
                                item.emergency_urls[0][0])
                            if not item.url.startswith('http'):
                                local_torr = filetools.join(
                                    config.get_videolibrary_path(), FOLDER,
                                    item_local.url)
                    except:
                        item_local.torrent_alt = ''
                        item.emergency_urls[0] = []
                    torrent_params['url'] = item_local.url
                    torrent_params['local_torr'] = local_torr
                    torrent_params = generictools.get_torrent_size(
                        item_local.url,
                        torrent_params=torrent_params,
                        item=item_local)
                    size = torrent_params['size']
                    if torrent_params['torrents_path']:
                        item_local.torrents_path = torrent_params[
                            'torrents_path']
        if size:
            size = size.replace('GB', 'G·B').replace('Gb', 'G·b').replace('MB', 'M·B')\
                        .replace('Mb', 'M·b').replace('.', ',')
            item_local.torrent_info = '%s, ' % size  #Agregamos size
        if item_local.url.startswith(
                'magnet:') and not 'Magnet' in item_local.torrent_info:
            item_local.torrent_info += ' Magnet'
        if item_local.torrent_info:
            item_local.torrent_info = item_local.torrent_info.strip().strip(
                ',')
            if item.videolibray_emergency_urls:
                item.torrent_info = item_local.torrent_info
            if not item.unify:
                item_local.torrent_info = '[%s]' % item_local.torrent_info

        # Guadamos la password del RAR
        password = scrapedpassword
        # Si tiene contraseña, la guardamos y la pintamos
        if password or item.password:
            if not item.password: item.password = password
            item_local.password = item.password
            itemlist.append(
                item.clone(
                    action="",
                    title="[COLOR magenta][B] Contraseña: [/B][/COLOR]'" +
                    item_local.password + "'",
                    folder=False))

        # Guardamos urls de emergencia si se viene desde un Lookup de creación de Videoteca
        if item.videolibray_emergency_urls:
            item.emergency_urls[0].append(
                item_local.url)  #guardamos la url y nos vamos
            continue

        if item_local.armagedon:
            item_local.quality = '[COLOR hotpink][E][/COLOR] [COLOR limegreen]%s[/COLOR]' % item_local.quality

        #Ahora pintamos el link del Torrent
        item_local.title = '[[COLOR yellow]?[/COLOR]] [COLOR yellow][Torrent][/COLOR] ' \
                        + '[COLOR limegreen][%s][/COLOR] [COLOR red]%s[/COLOR] %s' % \
                        (item_local.quality, str(item_local.language), \
                        item_local.torrent_info)

        #Preparamos título y calidad, quitando etiquetas vacías
        item_local.title = re.sub(r'\s?\[COLOR \w+\]\[\[?\s?\]?\]\[\/COLOR\]',
                                  '', item_local.title)
        item_local.title = re.sub(r'\s?\[COLOR \w+\]\s?\[\/COLOR\]', '',
                                  item_local.title)
        item_local.title = item_local.title.replace("--", "").replace("[]", "")\
                        .replace("()", "").replace("(/)", "").replace("[/]", "")\
                        .replace("|", "").strip()
        item_local.quality = re.sub(
            r'\s?\[COLOR \w+\]\[\[?\s?\]?\]\[\/COLOR\]', '',
            item_local.quality)
        item_local.quality = re.sub(r'\s?\[COLOR \w+\]\s?\[\/COLOR\]', '',
                                    item_local.quality)
        item_local.quality = item_local.quality.replace("--", "").replace("[]", "")\
                        .replace("()", "").replace("(/)", "").replace("[/]", "")\
                        .replace("|", "").strip()

        if not item_local.torrent_info or 'Magnet' in item_local.torrent_info:
            item_local.alive = "??"  #Calidad del link sin verificar
        elif 'ERROR' in item_local.torrent_info and 'Pincha' in item_local.torrent_info:
            item_local.alive = "ok"  #link en error, CF challenge, Chrome disponible
        elif 'ERROR' in item_local.torrent_info and 'Introduce' in item_local.torrent_info:
            item_local.alive = "??"  #link en error, CF challenge, ruta de descarga no disponible
            item_local.channel = 'setting'
            item_local.action = 'setting_torrent'
            item_local.unify = False
            item_local.folder = False
            item_local.item_org = item.tourl()
        elif 'ERROR' in item_local.torrent_info:
            item_local.alive = "no"  #Calidad del link en error, CF challenge?
        else:
            item_local.alive = "ok"  #Calidad del link verificada
        if item_local.channel != 'setting':
            item_local.action = "play"  #Visualizar vídeo
            item_local.server = "torrent"  #Seridor Torrent

        itemlist_t.append(
            item_local.clone())  #Pintar pantalla, si no se filtran idiomas

        # Requerido para FilterTools
        if config.get_setting(
                'filter_languages',
                channel) > 0:  #Si hay idioma seleccionado, se filtra
            itemlist_f = filtertools.get_link(
                itemlist_f, item_local,
                list_language)  #Pintar pantalla, si no está vacío

        #logger.debug("TORRENT: " + scrapedurl + " / title gen/torr: " + item.title + " / " + item_local.title + " / calidad: " + item_local.quality + " / content: " + item_local.contentTitle + " / " + item_local.contentSerieName)
        #logger.debug(item_local)

    #Si es un lookup para cargar las urls de emergencia en la Videoteca...
    if item.videolibray_emergency_urls:
        return item  #... nos vamos

    if len(itemlist_f) > 0:  #Si hay entradas filtradas...
        itemlist.extend(itemlist_f)  #Pintamos pantalla filtrada
    else:
        if config.get_setting('filter_languages', channel) > 0 and len(
                itemlist_t) > 0:  #Si no hay entradas filtradas ...
            thumb_separador = get_thumb(
                "next.png")  #... pintamos todo con aviso
            itemlist.append(
                Item(
                    channel=item.channel,
                    url=host,
                    title=
                    "[COLOR red][B]NO hay elementos con el idioma seleccionado[/B][/COLOR]",
                    thumbnail=thumb_separador,
                    folder=False))

        if len(itemlist_t) == 0:
            if len(itemlist) == 0 or (len(itemlist) > 0
                                      and itemlist[-1].server != 'torrent'):
                return []
        itemlist.extend(
            itemlist_t)  #Pintar pantalla con todo si no hay filtrado

    # Requerido para AutoPlay
    autoplay.start(itemlist, item)  #Lanzamos Autoplay

    return itemlist
Ejemplo n.º 8
0
def findvideos(item):
    logger.info()
    itemlist = []
    matches = []
    item.category = categoria

    #logger.debug(item)

    #Bajamos los datos de la página
    data = ''
    patron = '<a onclick="eventDownloadTorrent\(.*?\)".?class="linktorrent" href="([^"]+)">'
    if item.contentType == 'movie':
        try:
            data = re.sub(
                r"\n|\r|\t|\s{2}|(<!--.*?-->)", "",
                httptools.downloadpage(item.url, timeout=timeout).data)
            data = unicode(data, "utf-8", errors="replace").encode("utf-8")
        except:
            pass

        if not data:
            logger.error(
                "ERROR 01: FINDVIDEOS: La Web no responde o la URL es erronea: "
                + item.url)
            itemlist.append(
                item.clone(
                    action='',
                    title=item.channel.capitalize() +
                    ': ERROR 01: FINDVIDEOS:.  La Web no responde o la URL es erronea. Si la Web está activa, reportar el error con el log'
                ))
            return itemlist  #si no hay más datos, algo no funciona, pintamos lo que tenemos

        matches = re.compile(patron, re.DOTALL).findall(data)
        if not matches:  #error
            logger.error(
                "ERROR 02: FINDVIDEOS: No hay enlaces o ha cambiado la estructura de la Web "
                + " / PATRON: " + patron + data)
            itemlist.append(
                item.clone(
                    action='',
                    title=item.channel.capitalize() +
                    ': ERROR 02: FINDVIDEOS: No hay enlaces o ha cambiado la estructura de la Web.  Verificar en la Web esto último y reportar el error con el log'
                ))
            return itemlist  #si no hay más datos, algo no funciona, pintamos lo que tenemos
    else:
        matches = [item.url]

    #logger.debug("PATRON: " + patron)
    #logger.debug(matches)
    #logger.debug(data)

    #Llamamos al método para crear el título general del vídeo, con toda la información obtenida de TMDB
    item, itemlist = generictools.post_tmdb_findvideos(item, itemlist)

    #Ahora tratamos los enlaces .torrent
    for scrapedurl in matches:  #leemos los torrents con la diferentes calidades
        #Generamos una copia de Item para trabajar sobre ella
        item_local = item.clone()

        #Buscamos si ya tiene tamaño, si no, los buscamos en el archivo .torrent
        size = scrapertools.find_single_match(item_local.quality,
                                              '\s\[(\d+,?\d*?\s\w\s?[b|B])\]')
        if not size:
            size = generictools.get_torrent_size(
                item_local.url)  #Buscamos el tamaño en el .torrent
        if size:
            item_local.title = re.sub(
                r'\s\[\d+,?\d*?\s\w[b|B]\]', '',
                item_local.title)  #Quitamos size de título, si lo traía
            item_local.title = '%s [%s]' % (
                item_local.title, size)  #Agregamos size al final del título
            size = size.replace('GB', 'G B').replace('Gb', 'G b').replace(
                'MB', 'M B').replace('Mb', 'M b')
        item_local.quality = re.sub(
            r'\s\[\d+,?\d*?\s\w\s?[b|B]\]', '',
            item_local.quality)  #Quitamos size de calidad, si lo traía
        item_local.quality = '%s [%s]' % (
            item_local.quality, size)  #Agregamos size al final de la calidad

        #Ahora pintamos el link del Torrent
        item_local.url = scrapedurl
        if host not in item_local.url and host.replace(
                'https', 'http') not in item_local.url:
            item_local.url = host + item_local.url
        item_local.title = '[COLOR yellow][?][/COLOR] [COLOR yellow][Torrent][/COLOR] [COLOR limegreen][%s][/COLOR] [COLOR red]%s[/COLOR]' % (
            item_local.quality, str(item_local.language))

        #Preparamos título y calidad, quitamos etiquetas vacías
        item_local.title = re.sub(r'\s?\[COLOR \w+\]\[\[?\s?\]?\]\[\/COLOR\]',
                                  '', item_local.title)
        item_local.title = re.sub(r'\s?\[COLOR \w+\]\s?\[\/COLOR\]', '',
                                  item_local.title)
        item_local.title = item_local.title.replace("--", "").replace(
            "[]", "").replace("()", "").replace("(/)", "").replace("[/]",
                                                                   "").strip()
        item_local.quality = re.sub(
            r'\s?\[COLOR \w+\]\[\[?\s?\]?\]\[\/COLOR\]', '',
            item_local.quality)
        item_local.quality = re.sub(r'\s?\[COLOR \w+\]\s?\[\/COLOR\]', '',
                                    item_local.quality)
        item_local.quality = item_local.quality.replace("--", "").replace(
            "[]", "").replace("()", "").replace("(/)", "").replace("[/]",
                                                                   "").strip()

        item_local.alive = "??"  #Calidad del link sin verificar
        item_local.action = "play"  #Visualizar vídeo
        item_local.server = "torrent"  #Seridor Torrent

        itemlist.append(item_local.clone())  #Pintar pantalla

        #logger.debug("TORRENT: " + scrapedurl + " / title gen/torr: " + item.title + " / " + item_local.title + " / calidad: " + item_local.quality + " / content: " + item_local.contentTitle + " / " + item_local.contentSerieName)
        #logger.debug(item_local)

    return itemlist
Ejemplo n.º 9
0
def findvideos(item):
    logger.info()
    itemlist = []
    itemlist_t = []  #Itemlist total de enlaces
    itemlist_f = []  #Itemlist de enlaces filtrados
    if not item.language:
        item.language = ['CAST']  #Castellano por defecto

    item.category = categoria

    item.extra2 = 'xyz'
    del item.extra2

    #logger.debug(item)

    #Bajamos los datos de la página
    data = ''
    patron = '<p><a href="([^"]+)" rel'
    try:
        data = re.sub(r"\n|\r|\t|\s{2}|(<!--.*?-->)|&nbsp;", "",
                      httptools.downloadpage(item.url, timeout=timeout).data)
        data = unicode(data, "utf-8", errors="replace").encode("utf-8")
    except:
        pass

    if not data:
        logger.error(
            "ERROR 01: FINDVIDEOS: La Web no responde o la URL es erronea: " +
            item.url)
        itemlist.append(
            item.clone(
                action='',
                title=item.channel.capitalize() +
                ': ERROR 01: FINDVIDEOS:.  La Web no responde o la URL es erronea. Si la Web está activa, reportar el error con el log'
            ))

        if item.emergency_urls and not item.videolibray_emergency_urls:  #Hay urls de emergencia?
            matches = item.emergency_urls[1]  #Restauramos matches
            item.armagedon = True  #Marcamos la situación como catastrófica
        else:
            if item.videolibray_emergency_urls:  #Si es llamado desde creación de Videoteca...
                return item  #Devolvemos el Item de la llamada
            else:
                return itemlist  #si no hay más datos, algo no funciona, pintamos lo que tenemos

    if not item.armagedon:
        matches = re.compile(patron, re.DOTALL).findall(data)
    if not matches:  #error
        item = generictools.web_intervenida(
            item, data)  #Verificamos que no haya sido clausurada
        if item.intervencion:  #Sí ha sido clausurada judicialmente
            item, itemlist = generictools.post_tmdb_findvideos(
                item, itemlist)  #Llamamos al método para el pintado del error
        else:
            logger.error(
                "ERROR 02: FINDVIDEOS: No hay enlaces o ha cambiado la estructura de la Web "
                + " / PATRON: " + patron + data)
            itemlist.append(
                item.clone(
                    action='',
                    title=item.channel.capitalize() +
                    ': ERROR 02: FINDVIDEOS: No hay enlaces o ha cambiado la estructura de la Web.  Verificar en la Web esto último y reportar el error con el log'
                ))

        if item.emergency_urls and not item.videolibray_emergency_urls:  #Hay urls de emergencia?
            matches = item.emergency_urls[1]  #Restauramos matches
            item.armagedon = True  #Marcamos la situación como catastrófica
        else:
            if item.videolibray_emergency_urls:  #Si es llamado desde creación de Videoteca...
                return item  #Devolvemos el Item de la llamada
            else:
                return itemlist  #si no hay más datos, algo no funciona, pintamos lo que tenemos

    #logger.debug("PATRON: " + patron)
    #logger.debug(matches)
    #logger.debug(data)

    #Si es un lookup para cargar las urls de emergencia en la Videoteca...
    if item.videolibray_emergency_urls:
        item.emergency_urls = []  #Iniciamos emergency_urls
        item.emergency_urls.append(
            [])  #Reservamos el espacio para los .torrents locales
        item.emergency_urls.append(
            matches)  #Salvamnos matches de los vídeos...

    #Llamamos al método para crear el título general del vídeo, con toda la información obtenida de TMDB
    if not item.videolibray_emergency_urls:
        item, itemlist = generictools.post_tmdb_findvideos(item, itemlist)

    #Ahora tratamos los enlaces .torrent
    for scrapedurl in matches:  #leemos los torrents con la diferentes calidades
        if 'javascript' in scrapedurl:  #evitamos la basura
            continue
        url = ''
        if not item.armagedon:
            url = urlparse.urljoin(host, scrapedurl)
            #Leemos la siguiente página, que es de verdad donde está el magnet/torrent
            try:
                data = re.sub(
                    r"\n|\r|\t|\s{2}|(<!--.*?-->)|&nbsp;", "",
                    httptools.downloadpage(url, timeout=timeout).data)
                data = unicode(data, "utf-8", errors="replace").encode("utf-8")
            except:
                pass

            patron = "window.open\('([^']+)'"
            url = scrapertools.find_single_match(data, patron)
            if not url:  #error
                logger.error(
                    "ERROR 02: FINDVIDEOS: No hay enlaces o ha cambiado la estructura de la Web "
                    + " / PATRON: " + patron + data)
                itemlist.append(
                    item.clone(
                        action='',
                        title=item.channel.capitalize() +
                        ': ERROR 02: FINDVIDEOS: No hay enlaces o ha cambiado la estructura de la Web.  Verificar en la Web esto último y reportar el error con el log'
                    ))

                if item.emergency_urls and not item.videolibray_emergency_urls:  #Hay urls de emergencia?
                    item.armagedon = True  #Marcamos la situación como catastrófica
                else:
                    continue  #si no hay más datos, algo no funciona, pasamos al siguiente

        #Generamos una copia de Item para trabajar sobre ella
        item_local = item.clone()

        item_local.url = urlparse.urljoin(host, url)
        if item.videolibray_emergency_urls:
            item.emergency_urls[0].append(
                item_local.url)  #guardamos la url y pasamos a la siguiente
            continue
        if item.emergency_urls and not item.videolibray_emergency_urls:
            item_local.torrent_alt = item.emergency_urls[0][
                0]  #Guardamos la url del .Torrent ALTERNATIVA
            if item.armagedon:
                item_local.url = item.emergency_urls[0][0]  #Restauramos la url
            if len(item.emergency_urls[0]) > 1:
                del item.emergency_urls[0][0]

        #Buscamos si ya tiene tamaño, si no, los buscamos en el archivo .torrent
        size = scrapertools.find_single_match(
            item_local.quality, '\s?\[(\d+,?\d*?\s\w\s?[b|B])\]')
        if not size and not item.armagedon:
            size = generictools.get_torrent_size(
                item_local.url)  #Buscamos el tamaño en el .torrent
        if size:
            item_local.title = re.sub(
                r'\s?\[\d+,?\d*?\s\w\s?[b|B]\]', '',
                item_local.title)  #Quitamos size de título, si lo traía
            item_local.title = '%s [%s]' % (
                item_local.title, size)  #Agregamos size al final del título
            size = size.replace('GB', 'G B').replace('Gb', 'G b').replace(
                'MB', 'M B').replace('Mb', 'M b')
            item_local.quality = re.sub(
                r'\s?\[\d+,?\d*?\s\w\s?[b|B]\]', '',
                item_local.quality)  #Quitamos size de calidad, si lo traía
            item_local.quality = '%s [%s]' % (
                item_local.quality, size
            )  #Agregamos size al final de la calidad
        if item.armagedon:  #Si es catastrófico, lo marcamos
            item_local.quality = '[/COLOR][COLOR hotpink][E] [COLOR limegreen]%s' % item_local.quality

        #Ahora pintamos el link del Torrent
        item_local.title = '[COLOR yellow][?][/COLOR] [COLOR yellow][Torrent][/COLOR] [COLOR limegreen][%s][/COLOR] [COLOR red]%s[/COLOR]' % (
            item_local.quality, str(item_local.language))

        #Preparamos título y calidad, quitamos etiquetas vacías
        item_local.title = re.sub(r'\s?\[COLOR \w+\]\[\[?\s?\]?\]\[\/COLOR\]',
                                  '', item_local.title)
        item_local.title = re.sub(r'\s?\[COLOR \w+\]\s?\[\/COLOR\]', '',
                                  item_local.title)
        item_local.title = item_local.title.replace("--", "").replace(
            "[]", "").replace("()", "").replace("(/)", "").replace("[/]",
                                                                   "").strip()
        item_local.quality = re.sub(
            r'\s?\[COLOR \w+\]\[\[?\s?\]?\]\[\/COLOR\]', '',
            item_local.quality)
        item_local.quality = re.sub(r'\s?\[COLOR \w+\]\s?\[\/COLOR\]', '',
                                    item_local.quality).strip()
        item_local.quality = item_local.quality.replace("--", "").replace(
            "[]", "").replace("()", "").replace("(/)", "").replace("[/]",
                                                                   "").strip()

        item_local.alive = "??"  #Calidad del link sin verificar
        item_local.action = "play"  #Visualizar vídeo
        item_local.server = "torrent"  #Servidor Torrent

        itemlist_t.append(
            item_local.clone())  #Pintar pantalla, si no se filtran idiomas

        # Requerido para FilterTools
        if config.get_setting(
                'filter_languages',
                channel) > 0:  #Si hay idioma seleccionado, se filtra
            itemlist_f = filtertools.get_link(
                itemlist_f, item_local,
                list_language)  #Pintar pantalla, si no está vacío

        #logger.debug("TORRENT: " + scrapedurl + " / title gen/torr: " + item.title + " / " + item_local.title + " / calidad: " + item_local.quality + " / content: " + item_local.contentTitle + " / " + item_local.contentSerieName)

        #logger.debug(item_local)

    if item.videolibray_emergency_urls:  #Si ya hemos guardado todas las urls...
        return item  #... nos vamos

    if len(itemlist_f) > 0:  #Si hay entradas filtradas...
        itemlist.extend(itemlist_f)  #Pintamos pantalla filtrada
    else:
        if config.get_setting('filter_languages', channel) > 0 and len(
                itemlist_t) > 0:  #Si no hay entradas filtradas ...
            thumb_separador = get_thumb(
                "next.png")  #... pintamos todo con aviso
            itemlist.append(
                Item(
                    channel=item.channel,
                    url=host,
                    title=
                    "[COLOR red][B]NO hay elementos con el idioma seleccionado[/B][/COLOR]",
                    thumbnail=thumb_separador))
        itemlist.extend(
            itemlist_t)  #Pintar pantalla con todo si no hay filtrado

    # Requerido para AutoPlay
    autoplay.start(itemlist, item)  #Lanzamos Autoplay

    return itemlist
Ejemplo n.º 10
0
def findvideos(item):
    logger.info()
    
    itemlist = []
    itemlist_t = []                                                             #Itemlist total de enlaces
    itemlist_f = []                                                             #Itemlist de enlaces filtrados
    matches = []
    data = ''
    code = 0
    
    #logger.debug(item)

    #Bajamos los datos de la página y seleccionamos el bloque
    patron = '\s*<th\s*class="hide-on-mobile">Total\s*Descargas<\/th>\s*<th>'
    patron += 'Descargar<\/th>\s*<\/thead>\s*<tbody>\s*(.*?<\/tr>)\s*<\/tbody>'
    patron += '\s*<\/table>\s*<\/div>\s*<\/div>\s*<\/div>'
    
    if not item.matches:
        data, success, code, item, itemlist = generictools.downloadpage(item.url, timeout=timeout, 
                                          s2=False, patron=patron, item=item, itemlist=[])      # Descargamos la página)

    #Verificamos si se ha cargado una página, y si además tiene la estructura correcta
    if (not data and not item.matches) or code == 999:
        if item.emergency_urls and not item.videolibray_emergency_urls:         #Hay urls de emergencia?
            if len(item.emergency_urls) > 1:
                matches = item.emergency_urls[1]                                #Restauramos matches de vídeos
            item.armagedon = True                                               #Marcamos la situación como catastrófica 
        else:
            if item.videolibray_emergency_urls:                                 #Si es llamado desde creación de Videoteca...
                return item                                                     #Devolvemos el Item de la llamada
            else:
                return itemlist                                                 #si no hay más datos, algo no funciona, pintamos lo que tenemos
    elif data:
        # Seleccionamos el bloque y buscamos los apartados
        data = scrapertools.find_single_match(data, patron)

    patron = '<tr>(?:\s*<td>[^<]+<\/td>)?\s*<td>([^<]+)<\/td>\s*<td>([^<]+)<\/td>\s*'
    patron += '<td\s*class=[^<]+<\/td>(?:<td>([^<]+)<\/td>)?\s*<td\s*class=[^<]+<\/td>\s*'
    patron += '<td>\s*<a\s*class="[^"]+"\s*(?:data-row="[^"]+"\s*data-post="[^"]+"\s*)?'
    patron += 'href="([^"]+)"\s*(?:data-season="([^"]+)"\s*data-serie="([^"]+)")?'
    
    if not item.armagedon:
        if not item.matches:
            matches = re.compile(patron, re.DOTALL).findall(data)
        else:
            matches = item.matches
    
    #logger.debug("PATRON: " + patron)
    #logger.debug(matches)
    #logger.debug(data)
    
    if not matches:                                                             #error
        return itemlist

    #Si es un lookup para cargar las urls de emergencia en la Videoteca...
    if item.videolibray_emergency_urls:
        item.emergency_urls = []                                                #Iniciamos emergency_urls
        item.emergency_urls.append([])                                          #Reservamos el espacio para los .torrents locales
        item.emergency_urls.append(matches)                                     #Salvamnos matches de los vídeos...  

    #Llamamos al método para crear el título general del vídeo, con toda la información obtenida de TMDB
    if not item.videolibray_emergency_urls:
        item, itemlist = generictools.post_tmdb_findvideos(item, itemlist)

    #Ahora tratamos los enlaces .torrent con las diferentes calidades
    for scrapedquality, scrapedlanguage, scrapedsize, scrapedurl, season_num, episode_num  in matches:
        scrapedpassword = ''

        #Generamos una copia de Item para trabajar sobre ella
        item_local = item.clone()

        item_local.url = scrapedurl

        # Restauramos urls de emergencia si es necesario
        local_torr = ''
        if item.emergency_urls and not item.videolibray_emergency_urls:
            item_local.torrent_alt = item.emergency_urls[0][0]                  #Guardamos la url del .Torrent ALTERNATIVA
            if item.armagedon:
                item_local.url = item.emergency_urls[0][0]                      #Restauramos la url
                if item_local.url.startswith("\\") or item_local.url.startswith("/"):
                    from core import filetools
                    if item.contentType == 'movie':
                        FOLDER = config.get_setting("folder_movies")
                    else:
                        FOLDER = config.get_setting("folder_tvshows")
                    local_torr = filetools.join(config.get_videolibrary_path(), FOLDER, item_local.url)
            if len(item.emergency_urls[0]) > 1:
                del item.emergency_urls[0][0]
        
        # Procesamos idiomas
        item_local.language = []                                                #creamos lista para los idiomas
        item_local.quality = scrapedquality                                     # Copiamos la calidad
        if '[Subs. integrados]' in scrapedlanguage or '(Sub Forzados)' in scrapedlanguage \
                    or 'Subs integrados' in scrapedlanguage:
            item_local.language = ['VOS']                                       # añadimos VOS
        if 'castellano' in scrapedlanguage.lower() or ('español' in scrapedlanguage.lower() and not 'latino' in scrapedlanguage.lower()):
            item_local.language += ['CAST']                                     # añadimos CAST
        if 'dual' in item_local.quality.lower():
            item_local.quality = re.sub(r'(?i)dual.*?', '', item_local.quality).strip()
            item_local.language += ['DUAL']                                     # añadimos DUAL
        if not item_local.language:
            item_local.language = ['LAT']                                       # [LAT] por defecto
        
        #Buscamos tamaño en el archivo .torrent
        size = ''
        if item_local.torrent_info:
            size = item_local.torrent_info
        elif scrapedsize:
            size = scrapedsize
        if not size and not item.videolibray_emergency_urls and not item_local.url.startswith('magnet:'):
            if not item.armagedon:
                size = generictools.get_torrent_size(item_local.url, local_torr=local_torr) #Buscamos el tamaño en el .torrent desde la web
                if 'ERROR' in size and item.emergency_urls and not item.videolibray_emergency_urls:
                    item_local.armagedon = True
                    item_local.url = item.emergency_urls[0][0]                      #Restauramos la url
                    local_torr = filetools.join(config.get_videolibrary_path(), FOLDER, item_local.url)
                    size = generictools.get_torrent_size(item_local.url, local_torr=local_torr) #Buscamos el tamaño en el .torrent emergencia
        if size:
            size = size.replace('GB', 'G·B').replace('Gb', 'G·b').replace('MB', 'M·B')\
                        .replace('Mb', 'M·b').replace('.', ',')
            item_local.torrent_info = '%s, ' % size                             #Agregamos size
        if item_local.url.startswith('magnet:') and not 'Magnet' in item_local.torrent_info:
            item_local.torrent_info += ' Magnet'
        if item_local.torrent_info:
            item_local.torrent_info = item_local.torrent_info.strip().strip(',')
            item.torrent_info = item_local.torrent_info
            if not item.unify:
                item_local.torrent_info = '[%s]' % item_local.torrent_info
   
        # Guadamos la password del RAR
        password = scrapedpassword
        # Si tiene contraseña, la guardamos y la pintamos
        if password or item.password:
            if not item.password: item.password = password
            item_local.password = item.password
            itemlist.append(item.clone(action="", title="[COLOR magenta][B] Contraseña: [/B][/COLOR]'" 
                        + item_local.password + "'", folder=False))
        
        # Guardamos urls de emergencia si se viene desde un Lookup de creación de Videoteca
        if item.videolibray_emergency_urls:
            item.emergency_urls[0].append(item_local.url)                       #guardamos la url y nos vamos
            continue

        if item_local.armagedon:
            item_local.quality = '[COLOR hotpink][E][/COLOR] [COLOR limegreen]%s[/COLOR]' % item_local.quality
        
        #Ahora pintamos el link del Torrent
        item_local.title = '[[COLOR yellow]?[/COLOR]] [COLOR yellow][Torrent][/COLOR] ' \
                        + '[COLOR limegreen][%s][/COLOR] [COLOR red]%s[/COLOR] %s' % \
                        (item_local.quality, str(item_local.language), \
                        item_local.torrent_info)
        
        #Preparamos título y calidad, quitando etiquetas vacías
        item_local.title = re.sub(r'\s?\[COLOR \w+\]\[\[?\s?\]?\]\[\/COLOR\]', '', item_local.title)    
        item_local.title = re.sub(r'\s?\[COLOR \w+\]\s?\[\/COLOR\]', '', item_local.title)
        item_local.title = item_local.title.replace("--", "").replace("[]", "")\
                        .replace("()", "").replace("(/)", "").replace("[/]", "")\
                        .replace("|", "").strip()
        item_local.quality = re.sub(r'\s?\[COLOR \w+\]\[\[?\s?\]?\]\[\/COLOR\]', '', item_local.quality)
        item_local.quality = re.sub(r'\s?\[COLOR \w+\]\s?\[\/COLOR\]', '', item_local.quality)
        item_local.quality = item_local.quality.replace("--", "").replace("[]", "")\
                        .replace("()", "").replace("(/)", "").replace("[/]", "")\
                        .replace("|", "").strip()
        
        if not size or 'Magnet' in size:
            item_local.alive = "??"                                             #Calidad del link sin verificar
        elif 'ERROR' in size and 'Pincha' in size:
            item_local.alive = "ok"                                             #link en error, CF challenge, Chrome disponible
        elif 'ERROR' in size and 'Introduce' in size:
            item_local.alive = "??"                                             #link en error, CF challenge, ruta de descarga no disponible
            item_local.channel = 'setting'
            item_local.action = 'setting_torrent'
            item_local.unify = False
            item_local.folder = False
            item_local.item_org = item.tourl()
        elif 'ERROR' in size:
            item_local.alive = "no"                                             #Calidad del link en error, CF challenge?
        else:
            item_local.alive = "ok"                                             #Calidad del link verificada
        if item_local.channel != 'setting':
            item_local.action = "play"                                          #Visualizar vídeo
            item_local.server = "torrent"                                       #Seridor Torrent
        
        itemlist_t.append(item_local.clone())                                   #Pintar pantalla, si no se filtran idiomas
        
        # Requerido para FilterTools
        if config.get_setting('filter_languages', channel) > 0:                 #Si hay idioma seleccionado, se filtra
            itemlist_f = filtertools.get_link(itemlist_f, item_local, list_language)  #Pintar pantalla, si no está vacío

        #logger.debug("TORRENT: " + scrapedurl + " / title gen/torr: " + item.title + " / " + item_local.title + " / calidad: " + item_local.quality + " / content: " + item_local.contentTitle + " / " + item_local.contentSerieName)
        #logger.debug(item_local)

    #Si es un lookup para cargar las urls de emergencia en la Videoteca...
    if item.videolibray_emergency_urls:
        return item                                                             #... nos vamos
    
    if len(itemlist_f) > 0:                                                     #Si hay entradas filtradas...
        itemlist.extend(itemlist_f)                                             #Pintamos pantalla filtrada
    else:                                                                       
        if config.get_setting('filter_languages', channel) > 0 and len(itemlist_t) > 0: #Si no hay entradas filtradas ...
            thumb_separador = get_thumb("next.png")                             #... pintamos todo con aviso
            itemlist.append(Item(channel=item.channel, url=host, 
                        title="[COLOR red][B]NO hay elementos con el idioma seleccionado[/B][/COLOR]", 
                        thumbnail=thumb_separador, folder=False))
        itemlist.extend(itemlist_t)                                             #Pintar pantalla con todo si no hay filtrado
    
    # Requerido para AutoPlay
    autoplay.start(itemlist, item)                                              #Lanzamos Autoplay
    
    return itemlist
Ejemplo n.º 11
0
def findvideos(item):
    logger.info()
    itemlist = []

    #Bajamos los datos de la página
    data = ''
    try:
        data = re.sub(r"\n|\r|\t|\s{2}|(<!--.*?-->)", "", httptools.downloadpage(item.url).data)
    except:
        pass
        
    if not data:
        logger.error("ERROR 01: FINDVIDEOS: La Web no responde o la URL es erronea: " + item.url + " / DATA: " + data)
        itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 01: FINDVIDEOS:.  La Web no responde o la URL es erronea. Si la Web está activa, reportar el error con el log'))
        return itemlist                                     #si no hay más datos, algo no funciona, pintamos lo que tenemos
    #data = unicode(data, "utf-8", errors="replace")
    
    #Añadimos el tamaño para todos
    size = scrapertools.find_single_match(item.quality, '\s\[(\d+,?\d*?\s\w\s?[b|B]s)\]')
    if size:
        item.title = re.sub('\s\[\d+,?\d*?\s\w[b|B]s\]', '', item.title)        #Quitamos size de título, si lo traía
        item.title = '%s [%s]' % (item.title, size)                             #Agregamos size al final del título
        item.quality = re.sub('\s\[\d+,?\d*?\s\w\s?[b|B]s\]', '', item.quality) #Quitamos size de calidad, si lo traía

    patron_t = '<div class="enlace_descarga".*?<a href="(.*?\.torrent)"'
    link_torrent = scrapertools.find_single_match(data, patron_t)
    link_torrent = urlparse.urljoin(item.url, link_torrent)
    link_torrent = link_torrent.replace(" ", "%20")                             #sustituimos espacios por %20, por si acaso
    #logger.info("link Torrent: " + link_torrent)
    
    patron_m = '<div class="enlace_descarga".*?<a href="(magnet:?.*?)"'
    link_magnet = scrapertools.find_single_match(data, patron_m)
    link_magnet = urlparse.urljoin(item.url, link_magnet)
    #logger.info("link Magnet: " + link_magnet)
    
    if not link_torrent and not link_magnet:                                    #error
        item = generictools.web_intervenida(item, data)                         #Verificamos que no haya sido clausurada
        if item.intervencion:                                                   #Sí ha sido clausurada judicialmente
            item, itemlist = generictools.post_tmdb_findvideos(item, itemlist)  #Llamamos al método para el pintado del error
            return itemlist                                                     #Salimos
            
        logger.error("ERROR 02: FINDVIDEOS: El archivo Torrent no existe o ha cambiado la estructura de la Web " + " / PATRON: " + patron_t + " / " + patron_m + " / DATA: " + data)
        itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 02: FINDVIDEOS: El archivo Torrent no existe o ha cambiado la estructura de la Web.  Verificar en la Web y reportar el error con el log'))
        return itemlist                                     #si no hay más datos, algo no funciona, pintamos lo que tenemos

    #Llamamos al método para crear el título general del vídeo, con toda la información obtenida de TMDB
    item, itemlist = generictools.post_tmdb_findvideos(item, itemlist)
    
    if not size:
        size = generictools.get_torrent_size(link_torrent)                      #Buscamos el tamaño en el .torrent
    if size:
        item.quality = '%s [%s]' % (item.quality, size)                         #Agregamos size al final de calidad
        item.quality = item.quality.replace("GB", "G B").replace("MB", "M B")   #Se evita la palabra reservada en Unify
    
    #Generamos una copia de Item para trabajar sobre ella
    item_local = item.clone()

    #Ahora pintamos el link del Torrent, si lo hay
    if link_torrent:		# Hay Torrent ?
        if item_local.quality:
            item_local.quality += " "
        item_local.quality += "[Torrent]"
        item_local.url = link_torrent
        item_local.title = '[COLOR yellow][?][/COLOR] [COLOR yellow][Torrent][/COLOR] [COLOR limegreen][%s][/COLOR] [COLOR red]%s[/COLOR]' % (item_local.quality, str(item_local.language))        #Preparamos título de Torrent
        
        #Preparamos título y calidad, quitamos etiquetas vacías
        item_local.title = re.sub(r'\s?\[COLOR \w+\]\[\[?\s?\]?\]\[\/COLOR\]', '', item_local.title)    
        item_local.title = re.sub(r'\s?\[COLOR \w+\]\s?\[\/COLOR\]', '', item_local.title)
        item_local.title = item_local.title.replace("--", "").replace("[]", "").replace("()", "").replace("(/)", "").replace("[/]", "").strip()
        item_local.quality = re.sub(r'\s?\[COLOR \w+\]\[\[?\s?\]?\]\[\/COLOR\]', '', item_local.quality)
        item_local.quality = re.sub(r'\s?\[COLOR \w+\]\s?\[\/COLOR\]', '', item_local.quality)
        item_local.quality = item_local.quality.replace("--", "").replace("[]", "").replace("()", "").replace("(/)", "").replace("[/]", "").strip()
                
        item_local.alive = "??"                                                 #Calidad del link sin verificar
        item_local.action = "play"                                              #Visualizar vídeo
        item_local.server = "torrent"                                           #Seridor Torrent
        
        itemlist.append(item_local.clone())                                     #Pintar pantalla
    
    #Ahora pintamos el link del Magnet, si lo hay
    if link_magnet:		                                                        # Hay Magnet ?
        if item_local.quality:
            item_local.quality += " "
        item_local.quality = item_local.quality.replace("[Torrent]", "") + "[Magnet]"
        item_local.url = link_magnet
        item_local.title = '[COLOR yellow][?][/COLOR] [COLOR yellow][Torrent][/COLOR] [COLOR limegreen][%s][/COLOR] [COLOR red]%s[/COLOR]' % (item_local.quality, str(item_local.language))        #Preparamos título de Magnet
        item_local.title = re.sub(r'\s\[COLOR \w+\]\[\[?\]?\]\[\/COLOR\]', '', item_local.title)    #Quitamos etiquetas vacías
        item_local.title = re.sub(r'\s\[COLOR \w+\]\[\/COLOR\]', '', item_local.title)          #Quitamos colores vacíos
        item_local.alive = "??"                                                 #Calidad del link sin verificar
        item_local.action = "play"                                              #Visualizar vídeo
        item_local.server = "torrent"                                           #Seridor Torrent
        
        itemlist.append(item_local.clone())                                     #Pintar pantalla
    
    #logger.debug("TORRENT: " + link_torrent + "MAGNET: " + link_magnet + " / title gen/torr: " + item.title + " / " + item_local.title + " / calidad: " + item_local.quality + " / tamaño: " + size + " / content: " + item_local.contentTitle + " / " + item_local.contentSerieName)
    #logger.debug(item_local)

    return itemlist
Ejemplo n.º 12
0
def findvideos(item):
    logger.info()
    itemlist = []
    itemlist_t = []                                                         #Itemlist total de enlaces
    itemlist_f = []                                                         #Itemlist de enlaces filtrados
    if not item.language:
        item.language = ['CAST']                                            #Castellano por defecto
    matches = []
    item.category = categoria
    
    try:
        tmdb.set_infoLabels(item, True)                                     #TMDB actualizado
    except:
        pass
    
    item.extra2 = 'xyz'
    del item.extra2
    
    #logger.debug(item)

    matches = item.url
    if not matches:                                                         #error
        logger.error("ERROR 02: FINDVIDEOS: No hay enlaces o ha cambiado la estructura de la Web: " + str(item))
        itemlist.append(item.clone(action='', title=item.channel.capitalize() + ': ERROR 02: FINDVIDEOS: No hay enlaces o ha cambiado la estructura de la Web.  Verificar en la Web esto último y reportar el error con el log'))
        
        if item.emergency_urls and not item.videolibray_emergency_urls:     #Hay urls de emergencia?
            matches = item.emergency_urls[1]                                #Restauramos matches
            item.armagedon = True                                           #Marcamos la situación como catastrófica 
        else:
            if item.videolibray_emergency_urls:                             #Si es llamado desde creación de Videoteca...
                return item                                                 #Devolvemos el Item de la llamada
            else:
                return itemlist                                     #si no hay más datos, algo no funciona, pintamos lo que tenemos
    
    #logger.debug(matches)
    
    #Si es un lookup para cargar las urls de emergencia en la Videoteca...
    if item.videolibray_emergency_urls:
        item.emergency_urls = []                                            #Iniciamos emergency_urls
        item.emergency_urls.append([])                                      #Reservamos el espacio para los .torrents locales
        item.emergency_urls.append(matches)                                 #Salvamnos matches...  
    
    #Llamamos al método para crear el título general del vídeo, con toda la información obtenida de TMDB
    if not item.videolibray_emergency_urls:
        item, itemlist = generictools.post_tmdb_findvideos(item, itemlist)

    #Ahora tratamos los enlaces .torrent
    for scrapedurl, quality in matches:                                     #leemos los magnets con la diferentes calidades
        #Generamos una copia de Item para trabajar sobre ella
        item_local = item.clone()
            
        item_local.url = scrapedurl
        if item.videolibray_emergency_urls:
            item.emergency_urls[0].append(scrapedurl)                       #guardamos la url y pasamos a la siguiente
            continue
        if item.emergency_urls and not item.videolibray_emergency_urls:
            item_local.torrent_alt = item.emergency_urls[0][0]              #Guardamos la url del .Torrent ALTERNATIVA
            if item.armagedon:
                item_local.url = item.emergency_urls[0][0]                  #... ponemos la emergencia como primaria
            del item.emergency_urls[0][0]                                   #Una vez tratado lo limpiamos
        
        size = ''
        if not item.armagedon:
            size = generictools.get_torrent_size(item_local.url)            #Buscamos el tamaño en el .torrent
        if size:
            quality += ' [%s]' % size
        if item.armagedon:                                                  #Si es catastrófico, lo marcamos
            quality = '[/COLOR][COLOR hotpink][E] [COLOR limegreen]%s' % quality
            
        #Añadimos la calidad y copiamos la duración
        item_local.quality = quality
        if scrapertools.find_single_match(item.quality, '(\[\d+:\d+\ h])'):
            item_local.quality += ' [/COLOR][COLOR white]%s' % scrapertools.find_single_match(item.quality, '(\[\d+:\d+\ h])')
        
        #Ahora pintamos el link del Torrent
        item_local.title = '[COLOR yellow][?][/COLOR] [COLOR yellow][Torrent][/COLOR] [COLOR limegreen][%s][/COLOR] [COLOR red]%s[/COLOR]' % (item_local.quality, str(item_local.language))
        
        #Preparamos título y calidad, quitamos etiquetas vacías
        item_local.title = re.sub(r'\s?\[COLOR \w+\]\[\[?\s?\]?\]\[\/COLOR\]', '', item_local.title)    
        item_local.title = re.sub(r'\s?\[COLOR \w+\]\s?\[\/COLOR\]', '', item_local.title)
        item_local.title = item_local.title.replace("--", "").replace("[]", "").replace("()", "").replace("(/)", "").replace("[/]", "").strip()
        item_local.quality = re.sub(r'\s?\[COLOR \w+\]\[\[?\s?\]?\]\[\/COLOR\]', '', item_local.quality)
        item_local.quality = re.sub(r'\s?\[COLOR \w+\]\s?\[\/COLOR\]', '', item_local.quality).strip()
        item_local.quality = item_local.quality.replace("--", "").replace("[]", "").replace("()", "").replace("(/)", "").replace("[/]", "").strip()

        item_local.alive = "??"                                                 #Calidad del link sin verificar
        item_local.action = "play"                                              #Visualizar vídeo
        item_local.server = "torrent"                                           #Servidor Torrent
        
        itemlist_t.append(item_local.clone())                                   #Pintar pantalla, si no se filtran idiomas
        
        # Requerido para FilterTools
        if config.get_setting('filter_languages', channel) > 0:                 #Si hay idioma seleccionado, se filtra
            itemlist_f = filtertools.get_link(itemlist_f, item_local, list_language)  #Pintar pantalla, si no está vacío

        #logger.debug("TORRENT: " + scrapedurl + " / title gen/torr: " + item.title + " / " + item_local.title + " / calidad: " + item_local.quality + " / content: " + item_local.contentTitle + " / " + item_local.contentSerieName)
        
        #logger.debug(item_local)

    if item.videolibray_emergency_urls:                                         #Si ya hemos guardado todas las urls...
        return item                                                             #... nos vamos
    
    if len(itemlist_f) > 0:                                                     #Si hay entradas filtradas...
        itemlist.extend(itemlist_f)                                             #Pintamos pantalla filtrada
    else:                                                                       
        if config.get_setting('filter_languages', channel) > 0 and len(itemlist_t) > 0: #Si no hay entradas filtradas ...
            thumb_separador = get_thumb("next.png")                             #... pintamos todo con aviso
            itemlist.append(Item(channel=item.channel, url=host, title="[COLOR red][B]NO hay elementos con el idioma seleccionado[/B][/COLOR]", thumbnail=thumb_separador))
        itemlist.extend(itemlist_t)                                             #Pintar pantalla con todo si no hay filtrado

    # Requerido para AutoPlay
    autoplay.start(itemlist, item)                                              #Lanzamos Autoplay
    
    return itemlist