示例#1
0
def acciones_playlist(item):
    logger.info("pelisalacarta.channels.documaniatv acciones_playlist")
    itemlist = []
    if item.title == "Crear una nueva playlist y añadir el documental":
        from platformcode import platformtools
        texto = platformtools.dialog_input(heading="Introduce el título de la nueva playlist")
        if texto is not None:
            post= "p=playlists&do=create-playlist&title=%s&visibility=1&video-id=%s&ui=video-watch" % (texto, item.id)
            data = scrapertools.cachePage(item.url, headers=headers, post=post)
        else:
            return

    elif item.title != "Me gusta":
        if "Eliminar" in item.title: action = "remove-from-playlist"
        else: action = "add-to-playlist"
        post = "p=playlists&do=%s&playlist-id=%s&video-id=%s" % (action, item.list_id, item.id)
        data = scrapertools.cachePage(item.url, headers=headers, post=post)
    else:
        item.url = "http://www.documaniatv.com/ajax.php?vid=%s&p=video&do=like" % item.id
        data = scrapertools.cachePage(item.url, headers=headers)

    try:
        import xbmc
        from platformcode import platformtools
        platformtools.dialog_notification(item.title, "Se ha añadido/eliminado correctamente")
        xbmc.executebuiltin("Container.Refresh")
    except:
        itemlist.append(item.clone(action="", title="Se ha añadido/eliminado correctamente"))
        return itemlist
def manual_search(item):
    logger.info("streamondemand.channels.trailertools manual_search")
    texto = platformtools.dialog_input(default=item.contentTitle, heading=config.get_localized_string(30112))
    if texto is not None:
        if item.extra == "abandomoviez":
            return abandomoviez_search(item.clone(contentTitle=texto, page="", year=""))
        elif item.extra == "youtube":
            return youtube_search(item.clone(contentTitle=texto, page=""))
        elif item.extra == "filmaffinity":
            return filmaffinity_search(item.clone(contentTitle=texto, page="", year=""))
        elif item.extra == "jayhap":
            return jayhap_search(item.clone(contentTitle=texto))
示例#3
0
def download(item):
    from core import downloadtools
    if not item.fulltitle: item.fulltitle = item.title
    title = platformtools.dialog_input(default=item.fulltitle)
    if title is not None:
      devuelve = downloadtools.downloadbest(item.video_urls,title)
    
      if devuelve==0:
          platformtools.dialog_ok("Pelisalacarta", "Descargado con éxito")
      elif devuelve==-1:
          platformtools.dialog_ok("Pelisalacarta", "Descarga abortada")
      else:
          platformtools.dialog_ok("Pelisalacarta", "Error en la descarga")
    return
示例#4
0
def local_search(item):
    logger.info("pelisalacarta.channels.cinefox local_search")
    text = ""
    if config.get_setting("save_last_search", item.channel):
        text = config.get_setting("last_search", item.channel)
    from platformcode import platformtools
    texto = platformtools.dialog_input(default=text, heading="Buscar en Cinefox")
    if texto is None:
        return

    if config.get_setting("save_last_search", item.channel):
        config.set_setting("last_search", texto, item.channel)

    return search(item, texto)
示例#5
0
def add_to_downloads(item):
    if "item_action" in item: 
      item.action = item.item_action
      del item.item_action

    from core import descargas
    from core import downloadtools
    if not item.fulltitle: item.fulltitle = item.title
    title = platformtools.dialog_input(default=downloadtools.limpia_nombre_excepto_1(item.fulltitle))
    if title is not None:
      item.title = title
      descargas.savebookmark(item)

    platformtools.dialog_ok("Pelisalacarta", config.get_localized_string(30101) +"\n"+ item.title +"\n"+ config.get_localized_string(30109))
    return
示例#6
0
def add_to_favorites(item):
    #Proviene del menu contextual:
    if "item_action" in item:
      item.action = item.item_action
      del item.item_action
      item.context=[]

    from channels import favoritos
    from core import downloadtools
    if not item.fulltitle: item.fulltitle = item.title
    title = platformtools.dialog_input(default=downloadtools.limpia_nombre_excepto_1(item.fulltitle)+" ["+item.channel+"]")
    if title is not None:
        item.title = title
        favoritos.addFavourite(item)
        platformtools.dialog_ok("Pelisalacarta", config.get_localized_string(30102) +"\n"+ item.title +"\n"+ config.get_localized_string(30108))
    return
示例#7
0
def renameFavourite(item):
    logger.info("pelisalacarta.core.favoritos renameFavourite")
    #logger.debug(item.tostring('\n'))

    #Buscar el item q queremos renombrar en favourites.xml
    favourites_list = read_favourites()
    for i,fav in enumerate(favourites_list):
        if fav[0] == item.from_title:
            # abrir el teclado
            new_title = platformtools.dialog_input(item.from_title, item.title)
            if new_title:
                favourites_list[i] = (new_title, fav[1], fav[2])
                if save_favourites(favourites_list):
                    platformtools.dialog_ok(config.get_localized_string(30102), item.from_title,
                                            "se ha renombrado como:",new_title)  # 'Se ha quitado de favoritos'
                    platformtools.itemlist_refresh()
示例#8
0
def editar_perfil_titulo(item):
    logger.info()
    alfav = AlfavoritesData()

    if not alfav.user_favorites[item.i_perfil]: return False

    titulo = platformtools.dialog_input(
        default=alfav.user_favorites[item.i_perfil]['title'],
        heading='Nombre de la carpeta')
    if titulo is None or titulo == '' or titulo == alfav.user_favorites[
            item.i_perfil]['title']:
        return False

    alfav.user_favorites[item.i_perfil]['title'] = titulo
    alfav.save()

    platformtools.itemlist_refresh()
    return True
def renameFavourite(item):
    logger.info()
    # logger.debug(item.tostring('\n'))

    # Buscar el item q queremos renombrar en favourites.xml
    favourites_list = read_favourites()
    for i, fav in enumerate(favourites_list):
        if fav[0] == item.from_title:
            # abrir el teclado
            new_title = platformtools.dialog_input(item.from_title, item.title)
            if new_title:
                favourites_list[i] = (new_title, fav[1], fav[2])
                if save_favourites(favourites_list):
                    platformtools.dialog_ok(
                        config.get_localized_string(30102), item.from_title,
                        "se ha renombrado como:",
                        new_title)  # 'Se ha quitado de favoritos'
                    platformtools.itemlist_refresh()
示例#10
0
def renameFavourite(item):
    logger.info()
    # logger.debug(item.tostring('\n'))

    # Find the item we want to rename in favorites.xml
    favourites_list = read_favourites()
    for i, fav in enumerate(favourites_list):
        if fav[0] == item.from_title:
            # open keyboard
            new_title = platformtools.dialog_input(item.from_title, item.title)
            if new_title:
                favourites_list[i] = (new_title, fav[1], fav[2])
                if save_favourites(favourites_list):
                    platformtools.dialog_ok(
                        config.get_localized_string(30102), item.from_title +
                        '\n' + config.get_localized_string(60086) + '\n' +
                        new_title)  # 'Removed from favorites'
                    platformtools.itemlist_refresh()
示例#11
0
def editar_perfil_titulo(item):
    logger.info()
    alfav = AlfavoritesData()

    if not alfav.user_favorites[item.i_perfil]: return False

    titulo = platformtools.dialog_input(
        default=alfav.user_favorites[item.i_perfil]['title'],
        heading=config.get_localized_string(70533))
    if titulo is None or titulo == '' or titulo == alfav.user_favorites[
            item.i_perfil]['title']:
        return False

    alfav.user_favorites[item.i_perfil]['title'] = titulo
    alfav.save()

    platformtools.itemlist_refresh()
    return True
示例#12
0
def add_to_downloads(item):
    if "item_action" in item:
        item.action = item.item_action
        del item.item_action

    from core import descargas
    from core import downloadtools
    if not item.fulltitle: item.fulltitle = item.title
    title = platformtools.dialog_input(
        default=downloadtools.limpia_nombre_excepto_1(item.fulltitle))
    if title is not None:
        item.title = title
        descargas.addFavourite(item)

    platformtools.dialog_ok(
        "Pelisalacarta",
        config.get_localized_string(30101) + "\n" + item.title + "\n" +
        config.get_localized_string(30109))
    return
示例#13
0
    def lastSearch(self):
        logger.debug()
        if not self.item.text:
            if self.item.contentTitle:
                self.item.text = self.item.contentTitle
            elif self.item.contentSerieName:
                self.item.text = self.item.contentSerieName

            if not self.item.text:
                if config.get_setting('last_search'): last_search = channeltools.get_channel_setting('Last_searched', 'search', '')
                else: last_search = ''
                if not self.item.text: self.item.text = platformtools.dialog_input(default=last_search, heading='')
                if self.item.text:
                    channeltools.set_channel_setting('Last_searched', self.item.text, 'search')
                    if self.item.mode == 'all':
                        save_search(self.item.text)
        else:
            if self.item.context:
                del self.item.context  # needed for preventing same content twice in saved search
            save_search(self.item.__dict__)
示例#14
0
def editar_enlace_titulo(item):
    logger.debug()
    alfav = KodfavouritesData()

    if not alfav.user_favorites[item.i_perfil]: return False
    if not alfav.user_favorites[item.i_perfil]['items'][item.i_enlace]: return False

    it = Item().fromurl(alfav.user_favorites[item.i_perfil]['items'][item.i_enlace])

    titulo = platformtools.dialog_input(default=it.title, heading=config.get_localized_string(70553))
    if titulo is None or titulo == '' or titulo == it.title:
        return False

    it.title = titulo

    alfav.user_favorites[item.i_perfil]['items'][item.i_enlace] = it.tourl()
    alfav.save()

    platformtools.itemlist_refresh()
    return True
示例#15
0
def editar_enlace_titulo(item):
    logger.info()
    alfav = AlfavoritesData()

    if not alfav.user_favorites[item.i_perfil]: return False
    if not alfav.user_favorites[item.i_perfil]['items'][item.i_enlace]: return False

    it = Item().fromurl(alfav.user_favorites[item.i_perfil]['items'][item.i_enlace])
    
    titulo = platformtools.dialog_input(default=it.title, heading='Cambiar título del enlace')
    if titulo is None or titulo == '' or titulo == it.title:
        return False
    
    it.title = titulo

    alfav.user_favorites[item.i_perfil]['items'][item.i_enlace] = it.tourl()
    alfav.save()

    platformtools.itemlist_refresh()
    return True
示例#16
0
文件: launcher.py 项目: rrosajp/addon
def search(item):
    channel = importChannel(item)
    from core import channeltools

    if config.get_setting('last_search'):
        last_search = channeltools.get_channel_setting('Last_searched',
                                                       'search', '')
    else:
        last_search = ''

    search_text = platformtools.dialog_input(last_search)

    if search_text is not None:
        channeltools.set_channel_setting('Last_searched', search_text,
                                         'search')
        itemlist = new_search(item.clone(text=search_text), channel)
    else:
        return

    platformtools.render_items(itemlist, item)
示例#17
0
def add_to_favorites(item):
    #Proviene del menu contextual:
    if "item_action" in item:
        item.action = item.item_action
        del item.item_action
        item.context = []

    from channels import favoritos
    from core import downloadtools
    if not item.fulltitle: item.fulltitle = item.title
    title = platformtools.dialog_input(
        default=downloadtools.limpia_nombre_excepto_1(item.fulltitle) + " [" +
        item.channel + "]")
    if title is not None:
        item.title = title
        favoritos.addFavourite(item)
        platformtools.dialog_ok(
            "Pelisalacarta",
            config.get_localized_string(30102) + "\n" + item.title + "\n" +
            config.get_localized_string(30108))
    return
示例#18
0
def crear_lista(item):
    logger.debug()

    titulo = platformtools.dialog_input(default='', heading=config.get_localized_string(70612))
    if titulo is None or titulo == '':
        return False
    titulo = text_clean(titulo, blank_char='_')

    filename = get_filename_from_name(titulo)
    fullfilename = os.path.join(config.get_data_path(), filename)

    # Check that the file does not already exist
    if os.path.exists(fullfilename):
        platformtools.dialog_ok('KoD', config.get_localized_string(70613) + '\n' + fullfilename)
        return False

    # Cause it to be saved with empty folders by default
    alfav = KodfavouritesData(filename)

    platformtools.itemlist_refresh()
    return True
示例#19
0
def crear_lista(item):
    logger.info()

    titulo = platformtools.dialog_input(default='', heading='Nombre de la lista')
    if titulo is None or titulo == '':
        return False
    titulo = text_clean(titulo, blank_char='_')

    filename = get_filename_from_name(titulo)
    fullfilename = os.path.join(config.get_data_path(), filename)

    # Comprobar que el fichero no exista ya
    if os.path.exists(fullfilename):
        platformtools.dialog_ok('Alfa', 'Error, ya existe una lista con este nombre!', fullfilename)
        return False

    # Provocar que se guarde con las carpetas vacías por defecto
    alfav = AlfavoritesData(filename)

    platformtools.itemlist_refresh()
    return True
示例#20
0
def configurar_proxies_canal(canal, url):
    logger.info()
    
    while True:
        proxies = config.get_setting('proxies', canal, default='').strip()
        provider, tipo_proxy, pais_proxy, max_proxies = get_settings_proxytools(canal)
        if provider == 'lista_proxies.txt':
            tipo_proxy = '-'
            pais_proxy = '-'
        else:
            tipo_proxy = opciones_tipo[0] if tipo_proxy == '' else tipo_proxy.capitalize()
            pais_proxy = opciones_pais[0] if pais_proxy == '' else pais_proxy

        acciones = []
        lbl = proxies if proxies else '(sin proxies)'
        acciones.append(platformtools.listitem_to_select('Modificar proxies manualmente', lbl, ''))
        acciones.append(platformtools.listitem_to_select('Buscar proxies automáticamente', 'Iniciar búsqueda con los parámetros actuales'))
        acciones.append(platformtools.listitem_to_select('Parámetros para buscar proxies', '%s, %s, %s, %d' % (provider, tipo_proxy, pais_proxy, max_proxies), ''))
        if proxies: acciones.append(platformtools.listitem_to_select('Quitar proxies', 'Eliminar los proxies actuales para probar sin ellos'))

        ret = platformtools.dialog_select('Configurar proxies para %s' % canal.capitalize(), acciones, useDetails=True)
        if ret == -1: # pedido cancel
            break

        elif ret == 0:
            new_proxies = platformtools.dialog_input(default=proxies, heading='Introduce el proxy a utilizar o varios separados por comas')
            if new_proxies is not None and new_proxies != proxies:
                config.set_setting('proxies', new_proxies, canal)
                break

        elif ret == 1:
            if _buscar_proxies(canal, url): break # si no se encuentran proxies válidos seguir para poder cambiar parámetros o entrar manualmente

        elif ret == 2:
            _settings_proxies_canal(canal)

        elif ret == 3:
            config.set_setting('proxies', '', canal)

    return True
示例#21
0
def renombrar_lista(item):
    logger.debug()

    fullfilename_current = os.path.join(config.get_data_path(), item.lista)
    if not os.path.exists(fullfilename_current):
        platformtools.dialog_ok(
            'KoD',
            config.get_localized_string(70630) + '\n' + fullfilename_current)
        return False

    nombre = get_name_from_filename(item.lista)
    titulo = platformtools.dialog_input(
        default=nombre, heading=config.get_localized_string(70612))
    if titulo is None or titulo == '' or titulo == nombre:
        return False
    titulo = text_clean(titulo, blank_char='_')

    filename = get_filename_from_name(titulo)
    fullfilename = os.path.join(config.get_data_path(), filename)

    # Check that the new name does not exist
    if os.path.exists(fullfilename):
        platformtools.dialog_ok(
            'KoD',
            config.get_localized_string(70613) + '\n' + fullfilename)
        return False

    # Rename the file
    if not filetools.rename(fullfilename_current, filename):
        platformtools.dialog_ok(
            'KoD',
            config.get_localized_string(70631) + '\n' + fullfilename)
        return False

    # Update settings if it is the active list
    if item.lista == get_lista_activa():
        config.set_setting('lista_activa', filename)

    platformtools.itemlist_refresh()
    return True
示例#22
0
def crear_lista(item):
    logger.info()

    titulo = platformtools.dialog_input(default='', heading='Nombre de la lista')
    if titulo is None or titulo == '':
        return False
    titulo = config.text_clean(titulo, blank_char='_')

    filename = titulo.replace('.sqlite', '') + '.sqlite'
    fullfilename = filetools.join(trackingtools.get_tracking_path(), filename)

    # Comprobar que el fichero no exista ya
    if filetools.exists(fullfilename):
        platformtools.dialog_ok(config.__addon_name, 'Error, ya existe una lista con este nombre!', filename)
        return False

    # Provocar que se guarde
    db = trackingtools.TrackingData(filename)
    db.close(commit=True)

    platformtools.itemlist_refresh()
    return True
示例#23
0
def renombrar_lista(item):
    logger.info()

    fullfilename_current = os.path.join(config.get_data_path(), item.lista)
    if not os.path.exists(fullfilename_current):
        platformtools.dialog_ok('Alfa', 'Error, no se encuentra la lista!',
                                fullfilename_current)
        return False

    nombre = get_name_from_filename(item.lista)
    titulo = platformtools.dialog_input(default=nombre,
                                        heading='Nombre de la lista')
    if titulo is None or titulo == '' or titulo == nombre:
        return False
    titulo = text_clean(titulo, blank_char='_')

    filename = get_filename_from_name(titulo)
    fullfilename = os.path.join(config.get_data_path(), filename)

    # Comprobar que el nuevo nombre no exista
    if os.path.exists(fullfilename):
        platformtools.dialog_ok('Alfa',
                                'Error, ya existe una lista con este nombre!',
                                fullfilename)
        return False

    # Rename del fichero
    if not filetools.rename(fullfilename_current, filename):
        platformtools.dialog_ok('Alfa',
                                'Error, no se ha podido renombrar la lista!',
                                fullfilename)
        return False

    # Update settings si es la lista activa
    if item.lista == get_lista_activa():
        config.set_setting('lista_activa', filename)

    platformtools.itemlist_refresh()
    return True
示例#24
0
    def lastSearch(self):
        logger.debug()
        if not self.item.text:
            if self.item.contentTitle:
                self.item.text = self.item.contentTitle
            elif self.item.contentSerieName:
                self.item.text = self.item.contentSerieName

            if not self.item.text:
                if config.get_setting('last_search'):
                    last_search = channeltools.get_channel_setting(
                        'Last_searched', 'search', '')
                else:
                    last_search = ''
                if not self.item.text:
                    self.item.text = platformtools.dialog_input(
                        default=last_search, heading='')
                if self.item.text:
                    channeltools.set_channel_setting('Last_searched',
                                                     self.item.text, 'search')
                    from specials.search import save_search
                    save_search(self.item.text)
示例#25
0
def acciones_playlist(item):
    logger.info()
    itemlist = []
    if item.title == "Crear una nueva playlist y añadir el documental":
        from platformcode import platformtools
        texto = platformtools.dialog_input(
            heading="Introduce el título de la nueva playlist")
        if texto is not None:
            post = "p=playlists&do=create-playlist&title=%s&visibility=1&video-id=%s&ui=video-watch" % (
                texto, item.id)
            data = scrapertools.cachePage(item.url, headers=headers, post=post)
        else:
            return

    elif item.title != "Me gusta":
        if "Eliminar" in item.title:
            action = "remove-from-playlist"
        else:
            action = "add-to-playlist"
        post = "p=playlists&do=%s&playlist-id=%s&video-id=%s" % (
            action, item.list_id, item.id)
        data = scrapertools.cachePage(item.url, headers=headers, post=post)
    else:
        item.url = "http://www.documaniatv.com/ajax.php?vid=%s&p=video&do=like" % item.id
        data = scrapertools.cachePage(item.url, headers=headers)

    try:
        import xbmc
        from platformcode import platformtools
        platformtools.dialog_notification(
            item.title, "Se ha añadido/eliminado correctamente")
        xbmc.executebuiltin("Container.Refresh")
    except:
        itemlist.append(
            item.clone(action="",
                       title="Se ha añadido/eliminado correctamente"))
        return itemlist
示例#26
0
def show_result(item):
    tecleado = None
    if item.adult and config.get_setting("adult_request_password"):
        # Solicitar contraseña
        tecleado = platformtools.dialog_input(
            "", config.get_localized_string(60334), True)
        if tecleado is None or tecleado != config.get_setting(
                "adult_password"):
            return []

    item.channel = item.__dict__.pop('from_channel')
    item.action = item.__dict__.pop('from_action')
    if item.__dict__.has_key('tecleado'):
        tecleado = item.__dict__.pop('tecleado')

    try:
        channel = __import__('channels.%s' % item.channel,
                             fromlist=["channels.%s" % item.channel])
    except:
        import traceback
        logger.error(traceback.format_exc())
        return []

    if tecleado:
        # Mostrar resultados: agrupados por canales
        return channel.search(item, tecleado)
    else:
        # Mostrar resultados: todos juntos
        if item.infoPlus:  #Si viene de una ventana de InfoPlus, hay que salir de esta forma...
            del item.infoPlus  #si no, se mete en un bucle mostrando la misma pantalla,
            item.title = item.title.strip()  #dando error en "handle -1"
            return getattr(channel, item.action)(item)
        try:
            from platformcode import launcher
            launcher.run(item)
        except ImportError:
            return getattr(channel, item.action)(item)
示例#27
0
def file(item):
    itemlist = []
    logger.info("[bibiolteca.py] file")
    logger.info("[biblioteca.py] urlfile--->>>" + item.url)

    risp = platformtools.dialog_select('Stream On Demand play video', ['Guarda', 'Rinomina', 'Elimina'])
    try:

        if risp == 0:
            xbmc.Player().play(item.url)

        elif risp == 1:
            nome = platformtools.dialog_input(item.fulltitle)
            os.renames(item.url, filetools.join(config.get_library_path(), nome))
            xbmc.executebuiltin("Container.Refresh")

        elif risp == 2:
            if elimina_file(item):
                filetools.remove(item.url)
                xbmc.executebuiltin("Container.Refresh")
    except:
        pass

    return itemlist
示例#28
0
def config_item(item):
    log(item)
    tvdb.find_and_set_infoLabels(item)
    data = []
    title = item.show
    count = 0

    while not item.infoLabels['tvdb_id']:
        try:
            item.show = platformtools.dialog_input(
                default=item.show, heading=config.get_localized_string(30112))
            tvdb.find_and_set_infoLabels(item)
            count = count + 1
        except:
            heading = config.get_localized_string(70704)
            item.infoLabels['tvdb_id'] = platformtools.dialog_numeric(
                0, heading)
    data.append(item.infoLabels['tvdb_id'])
    if item.infoLabels['tvdb_id'] != '':
        write_data(item.from_channel, title, item.infoLabels['tvdb_id'])
    else:
        message = config.get_localized_string(60444)
        heading = item.show.strip()
        platformtools.dialog_notification(heading, message)
def file(item):
    itemlist = []
    logger.info("[bibiolteca.py] file")
    logger.info("[biblioteca.py] urlfile--->>>" + item.url)

    risp = platformtools.dialog_select('Stream On Demand play video', ['Guarda', 'Rinomina', 'Elimina'])
    try:

        if risp == 0:
            xbmc.Player().play(item.url)

        elif risp == 1:
            nome = platformtools.dialog_input(item.fulltitle)
            os.renames(item.url, filetools.join(config.get_library_path(), nome))
            xbmc.executebuiltin("Container.Refresh")

        elif risp == 2:
            if elimina_file(item):
                filetools.remove(item.url)
                xbmc.executebuiltin("Container.Refresh")
    except:
        pass

    return itemlist
示例#30
0
文件: launcher.py 项目: Hasimov/addon
def run(item=None):
    logger.info()

    if not item:
        # Extract item from sys.argv
        if sys.argv[2]:
            item = Item().fromurl(sys.argv[2])

        # If no item, this is mainlist
        else:
            if config.get_setting("start_page"):

                if not config.get_setting("custom_start"):
                    category = config.get_setting("category").lower()
                    item = Item(channel="news",
                                action="novedades",
                                extra=category,
                                mode='silent')
                else:
                    from channels import side_menu
                    item = Item()
                    item = side_menu.check_user_home(item)
                    item.start = True
            else:
                item = Item(channel="channelselector",
                            action="getmainlist",
                            viewmode="movie")
        if not config.get_setting('show_once'):
            from platformcode import xbmc_videolibrary
            xbmc_videolibrary.ask_set_content(1)
            config.set_setting('show_once', True)

    logger.info(item.tostring())

    try:
        # If item has no action, stops here
        if item.action == "":
            logger.info("Item sin accion")
            return

        # Action for main menu in channelselector
        elif item.action == "getmainlist":
            import channelselector

            itemlist = channelselector.getmainlist()

            platformtools.render_items(itemlist, item)

        # Action for channel types on channelselector: movies, series, etc.
        elif item.action == "getchanneltypes":
            import channelselector
            itemlist = channelselector.getchanneltypes()

            platformtools.render_items(itemlist, item)

        # Action for channel listing on channelselector
        elif item.action == "filterchannels":
            import channelselector
            itemlist = channelselector.filterchannels(item.channel_type)

            platformtools.render_items(itemlist, item)

        # Special action for playing a video from the library
        elif item.action == "play_from_library":
            play_from_library(item)
            return

        elif item.action == "keymap":
            from platformcode import keymaptools
            if item.open:
                return keymaptools.open_shortcut_menu()
            else:
                return keymaptools.set_key()

        elif item.action == "script":
            from core import tmdb
            if tmdb.drop_bd():
                platformtools.dialog_notification("Alfa",
                                                  "caché eliminada",
                                                  time=2000,
                                                  sound=False)

        # Action in certain channel specified in "action" and "channel" parameters
        else:

            # Entry point for a channel is the "mainlist" action, so here we check parental control
            if item.action == "mainlist":

                # Parental control
                # If it is an adult channel, and user has configured pin, asks for it
                if channeltools.is_adult(item.channel) and config.get_setting(
                        "adult_request_password"):
                    tecleado = platformtools.dialog_input(
                        "", "Contraseña para canales de adultos", True)
                    if tecleado is None or tecleado != config.get_setting(
                            "adult_password"):
                        return

            # # Actualiza el canal individual
            # if (item.action == "mainlist" and item.channel != "channelselector" and
            #             config.get_setting("check_for_channel_updates") == True):
            #     from core import updater
            #     updater.update_channel(item.channel)

            # Checks if channel exists
            channel_file = os.path.join(config.get_runtime_path(), 'channels',
                                        item.channel + ".py")
            logger.info("channel_file=%s" % channel_file)

            channel = None

            if os.path.exists(channel_file):
                try:
                    channel = __import__('channels.%s' % item.channel, None,
                                         None, ["channels.%s" % item.channel])
                except ImportError:
                    exec "import channels." + item.channel + " as channel"

            logger.info("Running channel %s | %s" %
                        (channel.__name__, channel.__file__))

            # Special play action
            if item.action == "play":
                #define la info para trakt
                try:
                    trakt_tools.set_trakt_info(item)
                except:
                    pass
                logger.info("item.action=%s" % item.action.upper())
                # logger.debug("item_toPlay: " + "\n" + item.tostring('\n'))

                # First checks if channel has a "play" function
                if hasattr(channel, 'play'):
                    logger.info("Executing channel 'play' method")
                    itemlist = channel.play(item)
                    b_favourite = item.isFavourite
                    # Play should return a list of playable URLS
                    if len(itemlist) > 0 and isinstance(itemlist[0], Item):
                        item = itemlist[0]
                        if b_favourite:
                            item.isFavourite = True
                        platformtools.play_video(item)

                    # Permitir varias calidades desde play en el canal
                    elif len(itemlist) > 0 and isinstance(itemlist[0], list):
                        item.video_urls = itemlist
                        platformtools.play_video(item)

                    # If not, shows user an error message
                    else:
                        platformtools.dialog_ok("alfa",
                                                "No hay nada para reproducir")

                # If player don't have a "play" function, not uses the standard play from platformtools
                else:
                    logger.info("Executing core 'play' method")
                    platformtools.play_video(item)

            # Special action for findvideos, where the plugin looks for known urls
            elif item.action == "findvideos":

                # First checks if channel has a "findvideos" function
                if hasattr(channel, 'findvideos'):
                    itemlist = getattr(channel, item.action)(item)
                    itemlist = servertools.filter_servers(itemlist)

                # If not, uses the generic findvideos function
                else:
                    logger.info("No channel 'findvideos' method, "
                                "executing core method")
                    itemlist = servertools.find_video_items(item)

                if config.get_setting("max_links", "videolibrary") != 0:
                    itemlist = limit_itemlist(itemlist)

                from platformcode import subtitletools
                subtitletools.saveSubtitleName(item)

                platformtools.render_items(itemlist, item)

            # Special action for adding a movie to the library
            elif item.action == "add_pelicula_to_library":
                videolibrarytools.add_movie(item)

            # Special action for adding a serie to the library
            elif item.action == "add_serie_to_library":
                videolibrarytools.add_tvshow(item, channel)

            # Special action for downloading all episodes from a serie
            elif item.action == "download_all_episodes":
                from channels import downloads
                item.action = item.extra
                del item.extra
                downloads.save_download(item)

            # Special action for searching, first asks for the words then call the "search" function
            elif item.action == "search":
                logger.info("item.action=%s" % item.action.upper())

                last_search = ""
                last_search_active = config.get_setting(
                    "last_search", "search")
                if last_search_active:
                    try:
                        current_saved_searches_list = list(
                            config.get_setting("saved_searches_list",
                                               "search"))
                        last_search = current_saved_searches_list[0]
                    except:
                        pass

                tecleado = platformtools.dialog_input(last_search)
                if tecleado is not None:
                    if last_search_active and not tecleado.startswith("http"):
                        from channels import search
                        search.save_search(tecleado)

                    itemlist = channel.search(item, tecleado)
                else:
                    return

                platformtools.render_items(itemlist, item)

            # For all other actions
            else:
                logger.info("Executing channel '%s' method" % item.action)
                itemlist = getattr(channel, item.action)(item)
                if config.get_setting('trakt_sync'):
                    token_auth = config.get_setting("token_trakt", "trakt")
                    if not token_auth:
                        trakt_tools.auth_trakt()
                    else:
                        import xbmc
                        if not xbmc.getCondVisibility(
                                'System.HasAddon(script.trakt)'
                        ) and config.get_setting('install_trakt'):
                            trakt_tools.ask_install_script()
                    itemlist = trakt_tools.trakt_check(itemlist)
                else:
                    config.set_setting('install_trakt', True)

                platformtools.render_items(itemlist, item)

    except urllib2.URLError, e:
        import traceback
        logger.error(traceback.format_exc())

        # Grab inner and third party errors
        if hasattr(e, 'reason'):
            logger.error("Razon del error, codigo: %s | Razon: %s" %
                         (str(e.reason[0]), str(e.reason[1])))
            texto = config.get_localized_string(
                30050)  # "No se puede conectar con el sitio web"
            platformtools.dialog_ok("alfa", texto)

        # Grab server response errors
        elif hasattr(e, 'code'):
            logger.error("Codigo de error HTTP : %d" % e.code)
            # "El sitio web no funciona correctamente (error http %d)"
            platformtools.dialog_ok(
                "alfa",
                config.get_localized_string(30051) % e.code)
示例#31
0
def buscartrailer(item, trailers=[]):
    logger.info()

    # Lista de acciones si se ejecuta desde el menú contextual
    if item.action == "manual_search" and item.contextual:
        itemlist = manual_search(item)
        item.contentTitle = itemlist[0].contentTitle
    elif 'search' in item.action and item.contextual:
        itemlist = globals()[item.action](item)
    else:
        # Se elimina la opción de Buscar Trailer del menú contextual para evitar redundancias
        if isinstance(item.context, str) and "buscar_trailer" in item.context:
            item.context = item.context.replace("buscar_trailer", "")
        elif isinstance(item.context, list) and "buscar_trailer" in item.context:
            item.context.remove("buscar_trailer")

        item.text_color = ""

        itemlist = []
        if item.contentTitle != "":
            item.contentTitle = item.contentTitle.strip()
        elif keyboard:
            contentTitle = re.sub('\[\/*(B|I|COLOR)\s*[^\]]*\]', '', item.contentTitle.strip())
            item.contentTitle = platformtools.dialog_input(default=contentTitle, heading=config.get_localized_string(70505))
            if item.contentTitle is None:
                item.contentTitle = contentTitle
            else:
                item.contentTitle = item.contentTitle.strip()
        else:
            contentTitle = re.sub('\[\/*(B|I|COLOR)\s*[^\]]*\]', '', item.contentTitle.strip())
            item.contentTitle = contentTitle

        item.year = item.infoLabels['year']

        logger.info("Búsqueda: %s" % item.contentTitle)
        logger.info("Año: %s" % item.year)
        if item.infoLabels['trailer'] and not trailers:
            url = item.infoLabels['trailer']
            if "youtube" in url:
                url = url.replace("embed/", "watch?v=")
            titulo, url, server = servertools.findvideos(url)[0]
            title = "Trailer por defecto  [" + server + "]"
            itemlist.append(item.clone(title=title, url=url, server=server, action="play"))
        if item.show or item.infoLabels['tvshowtitle'] or item.contentType != "movie":
            tipo = "tv"
        else:
            tipo = "movie"
        try:
            if not trailers:
                itemlist.extend(tmdb_trailers(item, tipo))
            else:
                for trailer in trailers:
                    title = trailer['name'] + " [" + trailer['size'] + "p] (" + trailer['language'].replace("en", "ING") \
                        .replace("es", "ESP") + ")  [tmdb/youtube]"
                    itemlist.append(item.clone(action="play", title=title, url=trailer['url'], server="youtube"))
        except:
            import traceback
            logger.error(traceback.format_exc())

        if item.contextual:
            title = "[COLOR green]%s[/COLOR]"
        else:
            title = "%s"
        itemlist.append(item.clone(title=title % config.get_localized_string(70507), action="youtube_search",
                                   text_color="green", current=""))
        itemlist.append(item.clone(title=title % config.get_localized_string(70024),
                                   action="filmaffinity_search", text_color="green", current=""))
        # Si se trata de una serie, no se incluye la opción de buscar en Abandomoviez
        if not item.show and not item.infoLabels['tvshowtitle']:
            itemlist.append(item.clone(title=title % config.get_localized_string(70508),
                                       action="abandomoviez_search", text_color="green", current=""))

    if item.contextual:
        global window_select, result
        select = Select("DialogSelect.xml", config.get_runtime_path(), item=item, itemlist=itemlist,
                        caption=config.get_localized_string(70506) + item.contentTitle)
        window_select.append(select)
        select.doModal()

        if item.current != "" and item.current >= 0:
            from channels import info_popup
            info_popup.show_popup(item, ignore_new_wish=True)

        if item.windowed:
            return result, window_select
    else:
        return itemlist
示例#32
0
def descargar_lista(item, url):
    logger.info()
    from core import httptools, scrapertools

    if 'tinyupload.com/' in url:
        try:
            from urlparse import urlparse
            data = httptools.downloadpage(url).data
            logger.debug(data)
            down_url, url_name = scrapertools.find_single_match(
                data, ' href="(download\.php[^"]*)"><b>([^<]*)')
            url_json = '{uri.scheme}://{uri.netloc}/'.format(
                uri=urlparse(url)) + down_url
        except:
            platformtools.dialog_ok('Alfa', config.get_localized_string(70655),
                                    url)
            return False

    elif 'zippyshare.com/' in url:
        from core import servertools
        video_urls, puedes, motivo = servertools.resolve_video_urls_for_playing(
            'zippyshare', url)

        if not puedes:
            platformtools.dialog_ok('Alfa', config.get_localized_string(70655),
                                    motivo)
            return False
        url_json = video_urls[0][
            1]  # https://www58.zippyshare.com/d/qPzzQ0UM/25460/alfavorites-testeanding.json
        url_name = url_json[url_json.rfind('/') + 1:]

    elif 'friendpaste.com/' in url:
        url_json = url if url.endswith('/raw') else url + '/raw'
        url_name = 'friendpaste'

    else:
        url_json = url
        url_name = url[url.rfind('/') + 1:]

    # Download json
    data = httptools.downloadpage(url_json).data

    # Verificar formato json de alfavorites y añadir info de la descarga
    jsondata = jsontools.load(data)
    if 'user_favorites' not in jsondata or 'info_lista' not in jsondata:
        logger.debug(data)
        platformtools.dialog_ok('Alfa', config.get_localized_string(70656))
        return False

    jsondata['info_lista']['downloaded_date'] = fechahora_actual()
    jsondata['info_lista']['downloaded_from'] = url
    data = jsontools.dump(jsondata)

    # Pedir nombre para la lista descargada
    nombre = get_name_from_filename(url_name)
    titulo = platformtools.dialog_input(
        default=nombre, heading=config.get_localized_string(70657))
    if titulo is None or titulo == '':
        return False
    titulo = text_clean(titulo, blank_char='_')

    filename = get_filename_from_name(titulo)
    fullfilename = os.path.join(config.get_data_path(), filename)

    # Si el nuevo nombre ya existe pedir confirmación para sobrescribir
    if os.path.exists(fullfilename):
        if not platformtools.dialog_yesno(
                'Alfa', config.get_localized_string(70613),
                config.get_localized_string(70658), filename):
            return False

    if not filetools.write(fullfilename, data):
        platformtools.dialog_ok('Alfa', config.get_localized_string(70659),
                                filename)

    platformtools.dialog_ok('Alfa', config.get_localized_string(70660),
                            filename)
    platformtools.itemlist_refresh()
    return True
def run():
    logger.info()

    # Extract item from sys.argv
    if sys.argv[2]:
        item = Item().fromurl(sys.argv[2])

    # If no item, this is mainlist
    else:
        item = Item(channel="channelselector", action="getmainlist", viewmode="movie")

    logger.info(item.tostring())
    
    try:

        # If item has no action, stops here
        if item.action == "":
            logger.info("Item sin accion")
            return

        # Action for main menu in channelselector
        if item.action == "getmainlist":
            import channelselector

            # Check for updates only on first screen
            if config.get_setting("check_for_plugin_updates") == "true":
                logger.info("Check for plugin updates enabled")
                from core import updater
                
                try:
                    config.set_setting("plugin_updates_available","0")
                    version = updater.checkforupdates()
                    itemlist = channelselector.getmainlist()

                    if version:
                        config.set_setting("plugin_updates_available","1")

                        platformtools.dialog_ok("Versione "+version+" disponible",
                                                "E' possibile fare il download della nuova versione\n"
                                                "selezionare la relativa voce nel menu principale")

                        itemlist = channelselector.getmainlist()
                        itemlist.insert(0, Item(title="Download versione "+version, version=version, channel="updater",
                                                action="update", thumbnail=os.path.join(config.get_runtime_path() , "resources" , "images", "service_update.png")))
                except:
                    import traceback
                    logger.info(traceback.format_exc())
                    platformtools.dialog_ok("Impossibile connettersi", "Non è stato possibile verificare",
                                            "aggiornamenti")
                    logger.info("Fallo al verificar la actualización")
                    config.set_setting("plugin_updates_available","0")
                    itemlist = channelselector.getmainlist()

            else:
                logger.info("Check for plugin updates disabled")
                config.set_setting("plugin_updates_available","0")
                itemlist = channelselector.getmainlist()

            platformtools.render_items(itemlist, item)

        # Action for updating plugin
        elif item.action == "update":

            from core import updater
            updater.update(item)
            config.set_setting("plugin_updates_available","0")
            if config.get_system_platform() != "xbox":
                import xbmc
                xbmc.executebuiltin("Container.Refresh")

        # Action for channel types on channelselector: movies, series, etc.
        elif item.action == "getchanneltypes":
            import channelselector
            itemlist = channelselector.getchanneltypes()

            platformtools.render_items(itemlist, item)

        # Action for channel listing on channelselector
        elif item.action == "filterchannels":
            import channelselector
            itemlist = channelselector.filterchannels(item.channel_type)

            platformtools.render_items(itemlist, item)

        # Special action for playing a video from the library
        elif item.action == "play_from_library":
            play_from_library(item)
            return

        # Action in certain channel specified in "action" and "channel" parameters
        else:

            # Entry point for a channel is the "mainlist" action, so here we check parental control
            if item.action == "mainlist":
                
                # Parental control
                can_open_channel = False

                # If it is an adult channel, and user has configured pin, asks for it
                if channeltools.is_adult(item.channel) and config.get_setting("adult_pin") != "":

                    tecleado = platformtools.dialog_input("", "PIN per canali per adulti", True)
                    if tecleado is not None:
                        if tecleado == config.get_setting("adult_pin"):
                            can_open_channel = True

                # All the other cases can open the channel
                else:
                    can_open_channel = True

                if not can_open_channel:
                    return

            # Actualiza el canal individual
            if (item.action == "mainlist" and
                    item.channel != "channelselector" and
                    config.get_setting("check_for_channel_updates") == "true"):
                from core import updater
                updater.update_channel(item.channel)

            # Checks if channel exists
            channel_file = os.path.join(config.get_runtime_path(),
                                        'channels', item.channel + ".py")
            logger.info("channel_file=%s" % channel_file)

            channel = None

            if item.channel in ["personal", "personal2", "personal3", "personal4", "personal5"]:
                import channels.personal as channel

            elif os.path.exists(channel_file):
                try:
                    channel = __import__('channels.%s' % item.channel, None,
                                         None, ["channels.%s" % item.channel])
                except ImportError:
                    exec "import channels." + item.channel + " as channel"

            logger.info("Running channel %s | %s" % (channel.__name__, channel.__file__))

            # Special play action
            if item.action == "play":
                logger.info("item.action=%s" % item.action.upper())
                # logger.debug("item_toPlay: " + "\n" + item.tostring('\n'))

                # First checks if channel has a "play" function
                if hasattr(channel, 'play'):
                    logger.info("Executing channel 'play' method")
                    itemlist = channel.play(item)
                    b_favourite = item.isFavourite
                    # Play should return a list of playable URLS
                    if len(itemlist) > 0 and isinstance(itemlist[0], Item):
                        item = itemlist[0]
                        if b_favourite:
                            item.isFavourite = True
                        platformtools.play_video(item)

                    # Permitir varias calidades desde play en el canal
                    elif len(itemlist) > 0 and isinstance(itemlist[0], list):
                        item.video_urls = itemlist
                        platformtools.play_video(item)

                    # If not, shows user an error message
                    else:
                        platformtools.dialog_ok("plugin", "Niente da riprodurre")

                # If player don't have a "play" function, not uses the standard play from platformtools
                else:
                    logger.info("Executing core 'play' method")
                    platformtools.play_video(item)

            # Special action for findvideos, where the plugin looks for known urls
            elif item.action == "findvideos":

                # First checks if channel has a "findvideos" function
                if hasattr(channel, 'findvideos'):
                    itemlist = getattr(channel, item.action)(item)

                # If not, uses the generic findvideos function
                else:
                    logger.info("No channel 'findvideos' method, "
                                "executing core method")
                    from core import servertools
                    itemlist = servertools.find_video_items(item)

                if config.get_setting('filter_servers') == 'true':
                    itemlist = filtered_servers(itemlist)

                if config.get_setting("max_links", "biblioteca") != 0:
                    itemlist = limit_itemlist(itemlist)

                from platformcode import subtitletools
                subtitletools.saveSubtitleName(item)

                platformtools.render_items(itemlist, item)

            # Special action for adding a movie to the library
            elif item.action == "add_pelicula_to_library":
                library.add_pelicula_to_library(item)

            # Special action for adding a serie to the library
            elif item.action == "add_serie_to_library":
                library.add_serie_to_library(item, channel)

            # Special action for downloading all episodes from a serie
            elif item.action == "download_all_episodes":
                from channels import descargas
                item.action = item.extra
                del item.extra
                descargas.save_download(item)

            # Special action for searching, first asks for the words then call the "search" function
            elif item.action == "search":
                logger.info("item.action=%s" % item.action.upper())

                tecleado = platformtools.dialog_input('')
                if tecleado is not None:

                    # TODO revisar 'personal.py' porque no tiene función search y daría problemas
                    # DrZ3r0
                    itemlist = channel.search(item, tecleado.replace(" ", "+"))
                else:
                    return
                
                platformtools.render_items(itemlist, item)

            # For all other actions
            else:
                logger.info("Executing channel '%s' method" % item.action)
                itemlist = getattr(channel, item.action)(item)
                platformtools.render_items(itemlist, item)

    except urllib2.URLError, e:
        import traceback
        logger.error(traceback.format_exc())

        # Grab inner and third party errors
        if hasattr(e, 'reason'):
            logger.info("Razon del error, codigo: %s | Razon: %s" %
                        (str(e.reason[0]), str(e.reason[1])))
            texto = config.get_localized_string(30050)  # "No se puede conectar con el sitio web"
            platformtools.dialog_ok("plugin", texto)

        # Grab server response errors
        elif hasattr(e, 'code'):
            logger.info("Codigo de error HTTP : %d" % e.code)
            # "El sitio web no funciona correctamente (error http %d)"
            platformtools.dialog_ok("plugin", config.get_localized_string(30051) % e.code)
示例#34
0
def acciones_cuenta(item):
    logger.info()
    itemlist = []

    if "Tus fichas" in item.title:
        itemlist.append(
            item.clone(title="Capítulos",
                       url="tf_block_c a",
                       contentType="tvshow"))
        itemlist.append(
            item.clone(title="Series", url="tf_block_s", contentType="tvshow"))
        itemlist.append(item.clone(title="Películas", url="tf_block_p"))
        itemlist.append(item.clone(title="Documentales", url="tf_block_d"))
        return itemlist
    elif "Añadir a una lista" in item.title:
        data = httptools.downloadpage(host + "/c_listas.php?apikey=%s&sid=%s" %
                                      (apikey, sid)).data
        data = json.xmlTojson(None, data)
        itemlist.append(item.clone(title="Crear nueva lista", folder=False))
        if data["Data"]["TusListas"] != "\t":
            import random
            data = data["Data"]["TusListas"]["Item"]
            if type(data) is not list:
                data = [data]
            for child in data:
                image = ""

                child['Title'] = scrapertools.find_single_match(
                    child['Title'], '<!\[CDATA\[(.+?)\]\]>')
                title = "%s (%s fichas)" % (child["Title"],
                                            child["FichasInList"])
                images = []
                for i in range(1, 5):
                    if "sinimagen.png" not in child["Poster%s" % i]:
                        images.append(child["Poster%s" % i].replace(
                            "/100/", "/400/"))
                if images:
                    image = images[random.randint(0, len(images) - 1)]
                url = host + "/data.php?mode=add_listas&apikey=%s&sid=%s&ficha_id=%s" % (
                    apikey, sid, item.ficha)
                post = "lista_id[]=%s" % child["Id"]
                itemlist.append(
                    item.clone(title=title,
                               url=url,
                               post=post,
                               thumbnail=image,
                               folder=False))

        return itemlist
    elif "Crear nueva lista" in item.title:
        from platformcode import platformtools
        nombre = platformtools.dialog_input(
            "", "Introduce un nombre para la lista")
        if nombre:
            dict_priv = {0: 'Pública', 1: 'Privada'}
            priv = platformtools.dialog_select("Privacidad de la lista",
                                               ['Pública', 'Privada'])
            if priv != -1:
                url = host + "/data.php?mode=create_list&apikey=%s&sid=%s" % (
                    apikey, sid)
                post = "name=%s&private=%s" % (nombre, priv)
                data = httptools.downloadpage(url, post)
                platformtools.dialog_notification(
                    "Lista creada correctamente",
                    "Nombre: %s - %s" % (nombre, dict_priv[priv]))
                platformtools.itemlist_refresh()
        return
    elif re.search(r"(?i)Seguir Lista", item.title):
        from platformcode import platformtools
        data = httptools.downloadpage(item.url)
        platformtools.dialog_notification("Operación realizada con éxito",
                                          "Lista: %s" % item.lista)
        return
    elif item.post:
        from platformcode import platformtools
        data = httptools.downloadpage(item.url, item.post).data
        platformtools.dialog_notification("Ficha añadida a la lista",
                                          "Lista: %s" % item.title)
        platformtools.itemlist_refresh()
        return

    data = httptools.downloadpage("https://playmax.mx/tusfichas.php").data
    data = re.sub(r"\n|\r|\t|\s{2}|&nbsp;|<br>", "", data)

    bloque = scrapertools.find_single_match(
        data,
        item.url + '">(.*?)(?:<div class="tf_blocks|<div class="tf_o_move">)')
    matches = scrapertools.find_multiple_matches(
        bloque, '<div class="tf_menu_mini">([^<]+)<(.*?)<cb></cb></div>')
    for category, contenido in matches:
        itemlist.append(
            item.clone(action="", title=category, text_color=color3))

        patron = '<div class="c_fichas_image">.*?href="\.([^"]+)".*?src="\.([^"]+)".*?serie="([^"]*)".*?' \
                 '<div class="c_fichas_title">(?:<div class="c_fichas_episode">([^<]+)</div>|)([^<]+)</div>'
        entradas = scrapertools.find_multiple_matches(contenido, patron)
        for scrapedurl, scrapedthumbnail, serie, episodio, scrapedtitle in entradas:
            tipo = "movie"
            scrapedurl = host + scrapedurl
            scrapedthumbnail = host + scrapedthumbnail
            action = "findvideos"
            if __menu_info__:
                action = "menu_info"
            if serie:
                tipo = "tvshow"
            if episodio:
                title = "      %s - %s" % (episodio.replace("X",
                                                            "x"), scrapedtitle)
            else:
                title = "      " + scrapedtitle

            new_item = Item(channel=item.channel,
                            action=action,
                            title=title,
                            url=scrapedurl,
                            thumbnail=scrapedthumbnail,
                            contentTitle=scrapedtitle,
                            contentType=tipo,
                            text_color=color2)
            if new_item.contentType == "tvshow":
                new_item.show = scrapedtitle
                if not __menu_info__:
                    new_item.action = "episodios"

            itemlist.append(new_item)

    return itemlist
示例#35
0
def find_and_set_infoLabels(item):
    """
        función que se llama para buscar y setear los infolabels
        :param item:
        :return: boleano que indica si se ha podido encontrar el 'code'
    """
    global scraper
    scraper = None
    # logger.debug("item:\n" + item.tostring('\n'))

    list_opciones_cuadro = [
        config.get_localized_string(60223),
        config.get_localized_string(60224)
    ]
    # Si se añaden más scrapers hay q declararlos aqui-> "modulo_scraper": "Texto_en_cuadro"
    scrapers_disponibles = {
        'tmdb': config.get_localized_string(60225),
        'tvdb': config.get_localized_string(60226)
    }

    # Obtener el Scraper por defecto de la configuracion segun el tipo de contenido
    if item.contentType == "movie":
        scraper_actual = ['tmdb'][config.get_setting("scraper_movies",
                                                     "videolibrary")]
        tipo_contenido = config.get_localized_string(70283)
        title = item.contentTitle
        # Completar lista de opciones para este tipo de contenido
        list_opciones_cuadro.append(scrapers_disponibles['tmdb'])

    else:
        scraper_actual = ['tmdb',
                          'tvdb'][config.get_setting("scraper_tvshows",
                                                     "videolibrary")]
        tipo_contenido = "serie"
        title = item.contentSerieName
        # Completar lista de opciones para este tipo de contenido
        list_opciones_cuadro.append(scrapers_disponibles['tmdb'])
        list_opciones_cuadro.append(scrapers_disponibles['tvdb'])

    # Importamos el scraper
    try:
        scraper = __import__('core.%s' % scraper_actual,
                             fromlist=["core.%s" % scraper_actual])
    except ImportError:
        exec "import core." + scraper_actual + " as scraper"
    except:
        import traceback
        logger.error(traceback.format_exc())

    while scraper:
        # Llamamos a la funcion find_and_set_infoLabels del scraper seleccionado
        scraper_result = scraper.find_and_set_infoLabels(item)

        # Verificar si existe 'code'
        if scraper_result and item.infoLabels['code']:
            # code correcto
            logger.info("Identificador encontrado: %s" %
                        item.infoLabels['code'])
            scraper.completar_codigos(item)
            return True
        elif scraper_result:
            # Contenido encontrado pero no hay 'code'
            msg = config.get_localized_string(60227) % title
        else:
            # Contenido no encontrado
            msg = config.get_localized_string(60228) % title

        logger.info(msg)
        # Mostrar cuadro con otras opciones:
        if scrapers_disponibles[scraper_actual] in list_opciones_cuadro:
            list_opciones_cuadro.remove(scrapers_disponibles[scraper_actual])
        index = platformtools.dialog_select(msg, list_opciones_cuadro)

        if index < 0:
            logger.debug("Se ha pulsado 'cancelar' en la ventana '%s'" % msg)
            return False

        elif index == 0:
            # Pregunta el titulo
            title = platformtools.dialog_input(
                title,
                config.get_localized_string(60229) % tipo_contenido)
            if title:
                if item.contentType == "movie":
                    item.contentTitle = title
                else:
                    item.contentSerieName = title
            else:
                logger.debug(
                    "he pulsado 'cancelar' en la ventana 'Introduzca el nombre correcto'"
                )
                return False

        elif index == 1:
            # Hay q crear un cuadro de dialogo para introducir los datos
            logger.info("Completar información")
            if cuadro_completar(item):
                # code correcto
                logger.info("Identificador encontrado: %s" %
                            str(item.infoLabels['code']))
                return True
                # raise

        elif list_opciones_cuadro[index] in scrapers_disponibles.values():
            # Obtener el nombre del modulo del scraper
            for k, v in scrapers_disponibles.items():
                if list_opciones_cuadro[index] == v:
                    if scrapers_disponibles[
                            scraper_actual] not in list_opciones_cuadro:
                        list_opciones_cuadro.append(
                            scrapers_disponibles[scraper_actual])
                    # Importamos el scraper k
                    scraper_actual = k
                    try:
                        scraper = None
                        scraper = __import__(
                            'core.%s' % scraper_actual,
                            fromlist=["core.%s" % scraper_actual])
                    except ImportError:
                        exec "import core." + scraper_actual + " as scraper_module"
                    break

    logger.error("Error al importar el modulo scraper %s" % scraper_actual)
示例#36
0
def run(item):
    itemlist = []
    #Muestra el item en el log:
    PrintItems(item)
    
      
    #Control Parental, comprueba si es adulto o no
    if item.action=="mainlist":
      # Parental control
      if channeltools.is_adult(item.channel) and config.get_setting("adult_pin")!="":
        tecleado = platformtools.dialog_input("","PIN para canales de adultos",True)
        if not tecleado==config.get_setting("adult_pin"):
          return

    #Importa el canal para el item, todo item debe tener un canal, sino sale de la función
    if item.channel: channelmodule = ImportarCanal(item)
    
    # If item has no action, stops here
    if item.action == "":
        logger.info("pelisalacarta.platformcode.launcher Item sin accion")
        itemlist = None
        
    #Action Play, para mostrar el menú con las opciones de reproduccion.
    elif item.action=="play":
      logger.info("pelisalacarta.platformcode.launcher play")
      # Si el canal tiene una acción "play" tiene prioridad
      if hasattr(channelmodule, 'play'):
          logger.info("pelisalacarta.platformcode.launcher executing channel 'play' method")
          itemlist = channelmodule.play(item)
          b_favourite = item.isFavourite
          if len(itemlist)>0 and isinstance(itemlist[0], Item):
              item = itemlist[0]
              if b_favourite:
                  item.isFavourite = True
              play_menu(item)
          elif len(itemlist)>0 and isinstance(itemlist[0], list):
              item.video_urls = itemlist
              play_menu(item)
          else:
              platformtools.dialog_ok("plugin", "No hay nada para reproducir")
      else:
          logger.info("pelisalacarta.platformcode.launcher no channel 'play' method, executing core method")
          play_menu(item)
          
      itemlist = None
    
      
    #Action Search, para mostrar el teclado y lanzar la busqueda con el texto indicado. 
    elif item.action=="search":
      logger.info("pelisalacarta.platformcode.launcher search")
      tecleado = platformtools.dialog_input()
      if not tecleado is None:
          itemlist = channelmodule.search(item,tecleado)
      else:
          itemlist = []


    elif item.channel == "channelselector":
      import channelselector
      if item.action =="mainlist":
        itemlist = channelselector.getmainlist("bannermenu")
        
        if config.get_setting("check_for_plugin_updates") == "true":
          logger.info("channelselector.mainlist Verificar actualizaciones activado")
          from core import updater
          try:
            version = updater.checkforupdates()
            
            if version:
              platformtools.dialog_ok("Versión "+version+" disponible","Ya puedes descargar la nueva versión del plugin\ndesde el listado principal")
              itemlist.insert(0,Item(title="Actualizadr pelisalacarta a la versión "+version, version=version, channel="updater", action="update", thumbnail=os.path.join(config.get_runtime_path(),"resources","images","bannermenu","thumb_update.png")))
          except:
            platformtools.dialog_ok("No se puede conectar","No ha sido posible comprobar","si hay actualizaciones")
            logger.info("channelselector.mainlist Fallo al verificar la actualización")

        else:
          logger.info("channelselector.mainlist Verificar actualizaciones desactivado")

      if item.action =="getchanneltypes":
        itemlist = channelselector.getchanneltypes("bannermenu")
      if item.action =="filterchannels":
        itemlist = channelselector.filterchannels(item.channel_type, "bannermenu")
                   
    #Todas las demas las intenta ejecturaren el siguiente orden:
    # 1. En el canal
    # 2. En el launcher
    # 3. Si no existe en el canal ni en el launcher guarda un error en el log
    else:
      #Si existe la funcion en el canal la ejecuta
      if hasattr(channelmodule, item.action):
        logger.info("Ejectuando accion: " + item.channel + "." + item.action + "(item)")
        exec "itemlist = channelmodule." + item.action + "(item)"
        
      #Si existe la funcion en el launcher la ejecuta
      elif hasattr(sys.modules[__name__], item.action):
        logger.info("Ejectuando accion: " + item.action + "(item)")
        exec "itemlist =" + item.action + "(item)"
        
      #Si no existe devuelve un error
      else:
          logger.info("No se ha encontrado la accion ["+ item.action + "] en el canal ["+item.channel+"] ni en el launcher")
          
     
          
    #Llegados a este punto ya tenemos que tener el itemlist con los resultados correspondientes
    #Pueden darse 3 escenarios distintos:
    # 1. la función ha generado resultados y estan en el itemlist
    # 2. la función no ha generado resultados y por tanto el itemlist contiene 0 items, itemlist = []
    # 3. la función realiza alguna accion con la cual no se generan nuevos items, en ese caso el resultado deve ser: itemlist = None para que no modifique el listado
    #A partir de aquí ya se ha ejecutado la funcion en el lugar adecuado, si queremos realizar alguna acción sobre los resultados, este es el lugar.
          
    
     
    #Filtrado de Servers      
    if item.action== "findvideos" and config.get_setting('filter_servers') == 'true': 
      server_white_list, server_black_list = set_server_list() 
      itemlist = filtered_servers(itemlist, server_white_list, server_black_list) 
      
    
    #Si la accion no ha devuelto ningún resultado, añade un item con el texto "No hay elementos para mostrar"              
    if type(itemlist)==list:
      if  len(itemlist) ==0:
        itemlist = [Item(title="No hay elementos para mostrar", thumbnail="http://media.tvalacarta.info/pelisalacarta/thumb_error.png")]
    
      #Imprime en el log el resultado
      PrintItems(itemlist)
      
    #Muestra los resultados en pantalla
    platformtools.render_items(itemlist, item)
def buscartrailer(item):
    logger.info("fusionse.channels.trailertools buscartrailer")

    # Se elimina la opciçon de Buscar Trailer del menú contextual para evitar redundancias
    item.context = item.context.replace("5", "")
    item.text_color = ""
    # Si no se indica el parámetro contextual se entiende que no se ejecuta desde este mení
    if item.contextual == "":
        item.contextual = False

    itemlist = []
    if item.contentTitle != "":
        item.contentTitle = item.contentTitle.strip()
    elif keyboard:
        item.contentTitle = platformtools.dialog_input(heading="Introduce el título a buscar")
        if item.contentTitle is None:
            item.contentTitle = item.fulltitle.strip()
        else:
            item.contentTitle = item.contentTitle.strip()
    else:
        item.contentTitle = item.fulltitle.strip()
        
    item.year = item.infoLabels['year'] if "year" in item.infoLabels else ""
    logger.info("fusionse.channels.trailertools Búsqueda: %s" % item.contentTitle)
    logger.info("fusionse.channels.trailertools Año: %s" % item.year)

    # Lista de acciones si se ejecuta desde el menú contextual
    if item.action == "manual_search":
        itemlist = manual_search(item)
        item.contentTitle = itemlist[0].contentTitle
    elif item.action == "youtube_search":
        itemlist = youtube_search(item)
    elif item.action == "filmaffinity_search":
        itemlist = filmaffinity_search(item)
    elif item.action == "abandomoviez_search":
        itemlist = abandomoviez_search(item)
    elif item.action == "jayhap_search":
        itemlist = jayhap_search(item)
    else:
        if "trailer" in item.infoLabels and item.infoLabels['trailer'] != "":
            url = item.infoLabels['trailer']
            if "youtube" in url:
                url = url.replace("embed/", "watch?v=")
            titulo, url, server = servertools.findvideos(url)[0]
            title = "Trailer por defecto  [" + server + "]"
            itemlist.append(item.clone(title=title, url=url, server=server, action="play"))
        if item.show != "" or ("tvshowtitle" in item.infoLabels and item.infoLabels['tvshowtitle'] != ""):
            type = "tv"
        else:
            type = "movie"
        try:
            itemlist.extend(tmdb_trailers(item, type))
        except:
            import traceback
            logger.error(traceback.format_exc())
        
        title = "[COLOR green]%s[/COLOR]" if item.contextual else "%s"
        itemlist.append(item.clone(title=title % "Búsqueda en Youtube", action="youtube_search",
                                   text_color="green"))
        itemlist.append(item.clone(title=title % "Búsqueda en Filmaffinity",
                                   action="filmaffinity_search", text_color="green"))
        # Si se trata de una serie, no se incluye la opción de buscar en Abandomoviez
        if item.show == "" and ("tvshowtitle" not in item.infoLabels or item.infoLabels['tvshowtitle'] == ""):
            itemlist.append(item.clone(title=title % "Búsqueda en Abandomoviez",
                                       action="abandomoviez_search", text_color="green"))
        itemlist.append(item.clone(title=title % "Búsqueda en Jayhap (Youtube, Vimeo & Dailymotion)",
                                   action="jayhap_search", text_color="green"))

    if item.contextual:
        opciones = []
        if itemlist:
            for video_url in itemlist:
                opciones.append(video_url.title)

            seleccion = platformtools.dialog_select("Buscando: "+item.contentTitle, opciones)
            logger.info("seleccion=%d" % seleccion)
            logger.info("seleccion=%s" % opciones[seleccion])

            if seleccion < 0:
                return
            else:
                item = itemlist[seleccion]
                if "search" in item.action:
                    buscartrailer(item)
                else:
                    if item.action == "play":
                        from platformcode import xbmctools
                        xbmctools.play_video(item)
                    return
    else:
        return itemlist
def addchannel(item):
    from platformcode import platformtools
    import os
    import time
    logger.info()
    
    tecleado = platformtools.dialog_input("", "Inserire l'URL")
    if not tecleado:
        return
    logger.info("url=%s" % tecleado)

    local_folder = config.get_runtime_path()
    if "canal" in item.title:
        local_folder = filetools.join(local_folder, 'channels')
        folder_to_extract = "channels"
        info_accion = "canal"
    else:
        local_folder = filetools.join(local_folder, 'servers')
        folder_to_extract = "servers"
        info_accion = "conector"

    # Detecta si es un enlace a un .py o .xml (pensado sobre todo para enlaces de github)
    try:
        extension = tecleado.rsplit(".", 1)[1]
    except:
        extension = ""

    files = []
    zip = False
    if extension == "py" or extension == "xml":
        filename = tecleado.rsplit("/", 1)[1]
        localfilename = filetools.join(local_folder, filename)
        files.append([tecleado, localfilename, filename])
    else:
        import re
        from core import scrapertools
        # Comprueba si la url apunta a una carpeta completa (channels o servers) de github
        if re.search(r'https://github.com/[^\s]+/'+folder_to_extract, tecleado):
            try:
                data = scrapertools.downloadpage(tecleado)
                matches = scrapertools.find_multiple_matches(data,
                                                             '<td class="content">.*?href="([^"]+)".*?title="([^"]+)"')
                for url, filename in matches:
                    url = "https://raw.githubusercontent.com" + url.replace("/blob/", "/")
                    localfilename = filetools.join(local_folder, filename)
                    files.append([url, localfilename, filename])
            except:
                import traceback
                logger.info("Detalle del error: %s" % traceback.format_exc())
                platformtools.dialog_ok("Errore", "L'URL non è corretto o non disponibile")
                return
        else:
            filename = 'new%s.zip' % info_accion
            localfilename = filetools.join(config.get_data_path(), filename)
            files.append([tecleado, localfilename, filename])
            zip = True

    logger.info("localfilename=%s" % localfilename)
    logger.info("descarga fichero...")
    
    try:
        if len(files) > 1:
            lista_opciones = ["No", "Si", "Si (Sovrascrivere tutto)"]
            overwrite_all = False
        from core import downloadtools
        for url, localfilename, filename in files:
            result = downloadtools.downloadfile(url, localfilename, continuar=False)
            if result == -3:
                if len(files) == 1:
                    dyesno = platformtools.dialog_yesno("Il file esiste già", "%s %s esiste già. "
                                                                                "Vuoi sovrascrivere?" %
                                                        (info_accion, filename))
                else:
                    if not overwrite_all:
                        dyesno = platformtools.dialog_select("Il file %s esiste già, vuoi sovrascrivere?"
                                                             % filename, lista_opciones)
                    else:
                        dyesno = 1
                # Diálogo cancelado
                if dyesno == -1:
                    return
                # Caso de carpeta github, opción sobrescribir todos
                elif dyesno == 2:
                    overwrite_all = True
                elif dyesno:
                    hora_folder = "Backup [%s]" % time.strftime("%d-%m_%H-%M", time.localtime())
                    backup = filetools.join(config.get_data_path(), 'backups', hora_folder, folder_to_extract)
                    if not filetools.exists(backup):
                        os.makedirs(backup)
                    import shutil
                    shutil.copy2(localfilename, filetools.join(backup, filename))
                    downloadtools.downloadfile(url, localfilename, continuar=True)
                else:
                    if len(files) == 1:
                        return
                    else:
                        continue
    except:
        import traceback
        logger.info("Detalle del error: %s" % traceback.format_exc())
        return

    if zip:
        try:
            # Lo descomprime
            logger.info("descomprime fichero...")
            from core import ziptools
            unzipper = ziptools.ziptools()
            logger.info("destpathname=%s" % local_folder)
            unzipper.extract(localfilename, local_folder, folder_to_extract, True, True)
        except:
            import traceback
            logger.error("Detalle del error: %s" % traceback.format_exc())
            # Borra el zip descargado
            filetools.remove(localfilename)
            platformtools.dialog_ok("Errore", "C'è stato un errore nell'estrazione del file")
            return

        # Borra el zip descargado
        logger.info("borra fichero...")
        filetools.remove(localfilename)
        logger.info("...fichero borrado")

    platformtools.dialog_ok("Successo", "Aggiornamento/installazione eseguita correttamente")
def buscartrailer(item, trailers=[]):
    logger.info("streamondemand.channels.trailertools buscartrailer")

    # Lista de acciones si se ejecuta desde el menú contextual
    if item.action == "manual_search" and item.contextual:
        itemlist = manual_search(item)
        item.contentTitle = itemlist[0].contentTitle
    elif 'search' in item.action and item.contextual:
        itemlist = globals()[item.action](item)
    else:
        # Se elimina la opción de Buscar Trailer del menú contextual para evitar redundancias
        if type(item.context) is str and "buscar_trailer" in item.context:
            item.context = item.context.replace("buscar_trailer", "")
        elif type(item.context) is list and "buscar_trailer" in item.context:
            item.context.remove("buscar_trailer")
        
        item.text_color = ""

        itemlist = []
        if item.contentTitle != "":
            item.contentTitle = item.contentTitle.strip()
        elif keyboard:
            fulltitle = re.sub('\[\/*(B|I|COLOR)\s*[^\]]*\]', '', item.fulltitle.strip())
            item.contentTitle = platformtools.dialog_input(default=fulltitle, heading="Scrivi il titolo da cercare")
            if item.contentTitle is None:
                item.contentTitle = fulltitle
            else:
                item.contentTitle = item.contentTitle.strip()
        else:
            fulltitle = re.sub('\[\/*(B|I|COLOR)\s*[^\]]*\]', '', item.fulltitle.strip())
            item.contentTitle = fulltitle
        
        item.year = item.infoLabels['year']

        logger.info("streamondemand.channels.trailertools Búsqueda: %s" % item.contentTitle)
        logger.info("streamondemand.channels.trailertools Año: %s" % item.year)
        if item.infoLabels['trailer'] and not trailers:
            url = item.infoLabels['trailer']
            if "youtube" in url:
                url = url.replace("embed/", "watch?v=")
            titulo, url, server = servertools.findvideos(url)[0]
            title = "Trailer por defecto  [" + server + "]"
            itemlist.append(item.clone(title=title, url=url, server=server, action="play"))
        if item.show or item.infoLabels['tvshowtitle'] or item.contentType != "movie":
            tipo = "tv"
        else:
            tipo = "movie"
        try:
            if not trailers:
                itemlist.extend(tmdb_trailers(item, tipo))
            else:
                for trailer in trailers:
                    title = trailer['name'] + " [" + trailer['size'] + "p] (" + trailer['language'].replace("en", "ING")\
                            .replace("es", "ESP")+")  [tmdb/youtube]"
                    itemlist.append(item.clone(action="play", title=title, url=trailer['url'], server="youtube"))
        except:
            import traceback
            logger.error(traceback.format_exc())
            
        if item.contextual:
            title = "[COLOR green]%s[/COLOR]"
        else:
            title = "%s"
        itemlist.append(item.clone(title=title % "Cerca su YouTube", action="youtube_search",
                                   text_color="green"))
        itemlist.append(item.clone(title=title % "Cerca su Filmaffinity",
                                   action="filmaffinity_search", text_color="green"))
        # Si se trata de una serie, no se incluye la opción de buscar en Abandomoviez
        if not item.show and not item.infoLabels['tvshowtitle']:
            itemlist.append(item.clone(title=title % "Cerca su Abandomoviez",
                                       action="abandomoviez_search", text_color="green"))
        itemlist.append(item.clone(title=title % "Cerca su Jayhap (Youtube, Vimeo & Dailymotion)",
                                   action="jayhap_search", text_color="green"))

    if item.contextual:
        global window_select, result
        select = Select("DialogSelect.xml", config.get_runtime_path(), item=item, itemlist=itemlist, caption="Stai cercando: "+item.contentTitle)
        window_select.append(select)
        select.doModal()

        if item.windowed:
            return result, window_select
    else:
        return itemlist
示例#40
0
def find_and_set_infoLabels(item):
    """
    función que se llama para buscar y setear los infolabels
    :param item:
    :return:
    """

    global scraper_global
    logger.debug("item:\n" + item.tostring('\n'))

    params = {}

    if item.contentType == "movie":
        tipo_contenido = "pelicula"
        title = item.contentTitle
        # get scraper pelis
        scraper = Tmdb()
        # para tmdb
        tipo_busqueda = "movie"

    else:
        tipo_contenido = "serie"
        title = item.contentSerieName
        # get scraper series
        scraper = Tmdb()
        # para tmdb
        tipo_busqueda = "tv"

    # esto ya está en el scraper tmdb
    # title = re.sub('\[\\\?(B|I|COLOR)\s?[^\]]*\]', '', title)

    # Si el titulo incluye el (año) se lo quitamos
    year = scrapertools.find_single_match(title, "^.+?\s*(\(\d{4}\))$")
    if year:
        title = title.replace(year, "").strip()
        item.infoLabels['year'] = year[1:-1]

    scraper_result = None
    results = []
    while not scraper_result:
        # para tmdb
        if isinstance(scraper, Tmdb):
            logger.debug("scraper es Tmbdb")
            params["texto_buscado"] = title
            params["tipo"] = tipo_busqueda
            params["year"] = item.infoLabels['year']

        if not results:
            if not item.infoLabels.get("tmdb_id"):
                if not item.infoLabels.get("imdb_id"):
                    scraper_global = scraper(**params)
                else:
                    logger.info("tiene imdb")
                    # para tmdb
                    if isinstance(scraper, Tmdb):
                        params["external_id"] = item.infoLabels.get("imdb_id")
                        params["external_source"] = "imdb_id"

                    scraper_global = scraper(**params)

            elif not scraper_global or scraper_global.result.get("id") != item.infoLabels['tmdb_id']:
                # para tmdb
                if isinstance(scraper, Tmdb):
                    params["id_Tmdb"] = item.infoLabels['tmdb_id']
                    params["idioma_busqueda"] = "es"

                scraper_global = scraper(**params)

            results = scraper_global.get_list_resultados()

        if len(results) > 1:
            scraper_result = platformtools.show_video_info(results, item=item, scraper=scraper,
                                                           caption="[%s]: Selecciona la %s correcta"
                                                                   % (title, tipo_contenido))

        elif len(results) > 0:
            scraper_result = results[0]

        if scraper_result is None:
            index = -1
            if tipo_contenido == "serie":
                # Si no lo encuentra la serie por si solo, presentamos una lista de opciones
                opciones = ["Introducir otro nombre", "Buscar en TheTvDB.com"]
                index = platformtools.dialog_select("%s no encontrada" % tipo_contenido.capitalize(), opciones)

            elif platformtools.dialog_yesno("Película no encontrada", "No se ha encontrado la película:", title,
                                            '¿Desea introducir otro nombre?'):
                index = 0

            if index < 0:
                logger.debug("he pulsado 'cancelar' en la ventana '%s no encontrada'" % tipo_contenido.capitalize())
                break

            if index == 0: # "Introducir otro nombre"
                # Pregunta el titulo
                it = platformtools.dialog_input(title, "Introduzca el nombre de la %s a buscar" % tipo_contenido)
                if it is not None:
                    title = it
                    item.infoLabels['year'] = ""
                    # reseteamos los resultados
                    results = []
                else:
                    logger.debug("he pulsado 'cancelar' en la ventana 'introduzca el nombre correcto'")
                    break

            if index == 1: # "Buscar en TheTvDB.com"
                results = tvdb_series_by_title(title)

    if isinstance(item.infoLabels, InfoLabels):
        infoLabels = item.infoLabels
    else:
        infoLabels = InfoLabels()

    if scraper_result:
        if 'id' in scraper_result:
            # resultados obtenidos de tmdb
            infoLabels['tmdb_id'] = scraper_result['id']
            infoLabels['url_scraper'] = "https://www.themoviedb.org/tv/%s" % infoLabels['tmdb_id']
            item.infoLabels = infoLabels
            tmdb.set_infoLabels_item(item)

        elif 'tvdb_id' in scraper_result:
            # resultados obtenidos de tvdb
            infoLabels.update(scraper_result)
            item.infoLabels = infoLabels

        # logger.debug("item:\n" + item.tostring('\n'))
        return True
    else:
        item.infoLabels = infoLabels
        return False
示例#41
0
def addchannel(item):
    from platformcode import platformtools

    import time, os

    logger.info("pelisalacarta.channels.configuracion addchannel")

    tecleado = platformtools.dialog_input("", "Introduzca la URL")
    if not tecleado:
        return
    logger.info("pelisalacarta.channels.configuracion url=%s" % tecleado)

    local_folder = config.get_runtime_path()
    if "canal" in item.title:
        local_folder = filetools.join(local_folder, "channels")
        folder_to_extract = "channels"
        info_accion = "canal"
    else:
        local_folder = filetools.join(local_folder, "servers")
        folder_to_extract = "servers"
        info_accion = "conector"

    # Detecta si es un enlace a un .py o .xml (pensado sobre todo para enlaces de github)
    try:
        extension = tecleado.rsplit(".", 1)[1]
    except:
        extension = ""

    files = []
    zip = False
    if extension == "py" or extension == "xml":
        filename = tecleado.rsplit("/", 1)[1]
        localfilename = filetools.join(local_folder, filename)
        files.append([tecleado, localfilename, filename])
    else:
        import re
        from core import scrapertools

        # Comprueba si la url apunta a una carpeta completa (channels o servers) de github
        if re.search(r"https://github.com/[^\s]+/" + folder_to_extract, tecleado):
            try:
                data = scrapertools.downloadpage(tecleado)
                matches = scrapertools.find_multiple_matches(
                    data, '<td class="content">.*?href="([^"]+)".*?title="([^"]+)"'
                )
                for url, filename in matches:
                    url = "https://raw.githubusercontent.com" + url.replace("/blob/", "/")
                    localfilename = filetools.join(local_folder, filename)
                    files.append([url, localfilename, filename])
            except:
                import traceback

                logger.info("Detalle del error: %s" % traceback.format_exc())
                platformtools.dialog_ok("Error", "La url no es correcta o no está disponible")
                return
        else:
            filename = "new%s.zip" % info_accion
            localfilename = filetools.join(config.get_data_path(), filename)
            files.append([tecleado, localfilename, filename])
            zip = True

    logger.info("pelisalacarta.channels.configuracion localfilename=%s" % localfilename)
    logger.info("pelisalacarta.channels.configuracion descarga fichero...")

    try:
        if len(files) > 1:
            lista_opciones = ["No", "Sí", "Sí (Sobrescribir todos)"]
            overwrite_all = False
        from core import downloadtools

        for url, localfilename, filename in files:
            result = downloadtools.downloadfile(url, localfilename, continuar=False)
            if result == -3:
                if len(files) == 1:
                    dyesno = platformtools.dialog_yesno(
                        "El archivo ya existe",
                        "Ya existe el %s %s." " ¿Desea sobrescribirlo?" % (info_accion, filename),
                    )
                else:
                    if not overwrite_all:
                        dyesno = platformtools.dialog_select(
                            "El archivo %s ya existe, ¿desea sobrescribirlo?" % filename, lista_opciones
                        )
                    else:
                        dyesno = 1
                # Diálogo cancelado
                if dyesno == -1:
                    return
                # Caso de carpeta github, opción sobrescribir todos
                elif dyesno == 2:
                    overwrite_all = True
                elif dyesno:
                    hora_folder = "Copia seguridad [%s]" % time.strftime("%d-%m_%H-%M", time.localtime())
                    backup = filetools.join(config.get_data_path(), "backups", hora_folder, folder_to_extract)
                    if not filetools.exists(backup):
                        os.makedirs(backup)
                    import shutil

                    shutil.copy2(localfilename, filetools.join(backup, filename))
                    result = downloadtools.downloadfile(url, localfilename, continuar=True)
                else:
                    if len(files) == 1:
                        return
                    else:
                        continue
    except:
        import traceback

        logger.info("Detalle del error: %s" % traceback.format_exc())
        return

    if zip:
        try:
            # Lo descomprime
            logger.info("pelisalacarta.channels.configuracion descomprime fichero...")
            from core import ziptools

            unzipper = ziptools.ziptools()
            logger.info("pelisalacarta.channels.configuracion destpathname=%s" % local_folder)
            unzipper.extract(localfilename, local_folder, folder_to_extract, True, True)
        except:
            import traceback

            logger.info("Detalle del error: %s" % traceback.format_exc())
            # Borra el zip descargado
            filetools.remove(localfilename)
            platformtools.dialog_ok("Error", "Se ha producido un error extrayendo el archivo")
            return

        # Borra el zip descargado
        logger.info("pelisalacarta.channels.configuracion borra fichero...")
        filetools.remove(localfilename)
        logger.info("pelisalacarta.channels.configuracion ...fichero borrado")

    platformtools.dialog_ok("Éxito", "Actualización/Instalación realizada correctamente")
示例#42
0
        if item.action == 'findvideos':
            if hasattr(canal, item.action):
                itemlist = canal.findvideos(item)
            else:
                itemlist = servertools.find_video_items(item)

            platformtools.play_from_itemlist(itemlist, item)

        else:
            # search pide el texto a buscar antes de llamar a la rutina del canal (pasar item.buscando para no mostrar diálogo)
            if item.action == 'search':
                if item.buscando != '':
                    tecleado = item.buscando
                else:
                    last_search = config.get_last_search(item.search_type)
                    tecleado = platformtools.dialog_input(
                        last_search, 'Texto a buscar')

                if tecleado is not None and tecleado != '':
                    itemlist = canal.search(item, tecleado)
                    if item.buscando == '':
                        config.set_last_search(item.search_type, tecleado)
                else:
                    itemlist = []

            # cualquier otra acción se ejecuta en el canal, y se renderiza si devuelve una lista de items
            else:
                if hasattr(canal, item.action):
                    func = getattr(canal, item.action)
                    itemlist = func(item)
                else:
                    logger.info('Action not found in channel')
def find_and_set_infoLabels(item):
    """
        función que se llama para buscar y setear los infolabels
        :param item:
        :return: boleano que indica si se ha podido encontrar el 'code'
    """
    global scraper
    scraper = None
    logger.debug("item:\n" + item.tostring('\n'))

    list_opciones_cuadro = ["Immettere un altro nome", "Informazioni complete"]
    # Si se añaden más scrapers hay q declararlos aqui-> "modulo_scraper": "Texto_en_cuadro"
    scrapers_disponibles = {'tmdb': "Cerca su TheMovieDB.org",
                            'tvdb': "Cerca su TheTvDB.com"}

    # Obtener el Scraper por defecto de la configuracion segun el tipo de contenido
    if item.contentType == "movie":
        scraper_actual = ['tmdb'][config.get_setting("scraper_movies", "biblioteca")]
        tipo_contenido = "película"
        title = item.contentTitle
        # Completar lista de opciones para este tipo de contenido
        list_opciones_cuadro.append(scrapers_disponibles['tmdb'])

    else:
        scraper_actual = ['tmdb', 'tvdb'][config.get_setting("scraper_tvshows", "biblioteca")]
        tipo_contenido = "serie"
        title = item.contentSerieName
        # Completar lista de opciones para este tipo de contenido
        list_opciones_cuadro.append(scrapers_disponibles['tmdb'])
        list_opciones_cuadro.append(scrapers_disponibles['tvdb'])

    # Importamos el scraper
    try:
        scraper = __import__('core.%s' % scraper_actual, fromlist=["core.%s" % scraper_actual])
    except ImportError:
        exec "import core." + scraper_actual + " as scraper"

    while scraper:
        # Llamamos a la funcion find_and_set_infoLabels del scraper seleccionado
        scraper_result = scraper.find_and_set_infoLabels(item)

        # Verificar si existe 'code'
        if scraper_result and item.infoLabels['code']:
            # code correcto
            logger.info("Identificador encontrado: %s" % item.infoLabels['code'])
            scraper.completar_codigos(item)
            return True
        elif scraper_result:
            # Contenido encontrado pero no hay 'code'
            msg = "ID Non trovato per: %s" % title
        else:
            # Contenido no encontrado
            msg = "Nessuna informazione trovata per: %s" % title

        logger.info(msg)
        # Mostrar cuadro con otras opciones:
        if scrapers_disponibles[scraper_actual] in list_opciones_cuadro:
            list_opciones_cuadro.remove(scrapers_disponibles[scraper_actual])
        index = platformtools.dialog_select(msg, list_opciones_cuadro)

        if index < 0:
            logger.debug("Se ha pulsado 'cancelar' en la ventana '%s'" % msg)
            return False

        elif index == 0:
            # Pregunta el titulo
            title = platformtools.dialog_input(title, "Introduzca el nombre de la %s a buscar" % tipo_contenido)
            if title:
                if item.contentType == "movie":
                    item.contentTitle = title
                else:
                    item.contentSerieName = title
            else:
                logger.debug("he pulsado 'cancelar' en la ventana 'Introduzca el nombre correcto'")
                return False

        elif index == 1:
            # Hay q crear un cuadro de dialogo para introducir los datos
            logger.info("Completar información")
            if cuadro_completar(item):
                # code correcto
                logger.info("Identificador encontrado: %s" % str(item.infoLabels['code']))
                return True
            # raise

        elif list_opciones_cuadro[index] in scrapers_disponibles.values():
            # Obtener el nombre del modulo del scraper
            for k, v in scrapers_disponibles.items():
                if list_opciones_cuadro[index] == v:
                    if scrapers_disponibles[scraper_actual] not in list_opciones_cuadro:
                        list_opciones_cuadro.append(scrapers_disponibles[scraper_actual])
                    # Importamos el scraper k
                    scraper_actual = k
                    try:
                        scraper = None
                        scraper = __import__('core.%s' % scraper_actual, fromlist=["core.%s" % scraper_actual])
                    except ImportError:
                        exec "import core." + scraper_actual + " as scraper_module"
                    break

    logger.error("Error al importar el modulo scraper %s" % scraper_actual)
示例#44
0
def run(item=None):
    # from core.support import dbg;dbg()
    logger.debug()
    if not item:
        # Extract item from sys.argv
        if sys.argv[2]:
            sp = sys.argv[2].split('&')
            url = sp[0]
            item = Item().fromurl(url)
            if len(sp) > 1:
                for e in sp[1:]:
                    key, val = e.split('=')
                    item.__setattr__(key, val)
        # If no item, this is mainlist
        else:
            item = Item(channel="channelselector",
                        action="getmainlist",
                        viewmode="movie")
        if not config.get_setting('show_once'):
            if not config.get_all_settings_addon():
                logger.error('corrupted settings.xml!!')
                settings_xml = os.path.join(config.get_data_path(),
                                            "settings.xml")
                settings_bak = os.path.join(config.get_data_path(),
                                            "settings.bak")
                if filetools.exists(settings_bak):
                    filetools.copy(settings_bak, settings_xml, True)
                    logger.info('restored settings.xml from backup')
                else:
                    filetools.write(settings_xml,
                                    '<settings version="2">\n</settings>'
                                    )  # resetted settings
            else:
                from platformcode import xbmc_videolibrary
                xbmc_videolibrary.ask_set_content(silent=False)
                config.set_setting('show_once', True)

    logger.info(item.tostring())

    try:
        if not config.get_setting('tmdb_active'):
            config.set_setting('tmdb_active', True)

        # If item has no action, stops here
        if item.action == "":
            logger.debug("Item without action")
            return

        # Action for main menu in channelselector
        elif item.action == "getmainlist":
            import channelselector

            itemlist = channelselector.getmainlist()

            platformtools.render_items(itemlist, item)

        # Action for channel types on channelselector: movies, series, etc.
        elif item.action == "getchanneltypes":
            import channelselector
            itemlist = channelselector.getchanneltypes()

            platformtools.render_items(itemlist, item)

        # Action for channel listing on channelselector
        elif item.action == "filterchannels":
            import channelselector
            itemlist = channelselector.filterchannels(item.channel_type)

            platformtools.render_items(itemlist, item)

        # Special action for playing a video from the library
        elif item.action == "play_from_library":
            play_from_library(item)
            return

        elif item.action == "keymap":
            from platformcode import keymaptools
            if item.open:
                return keymaptools.open_shortcut_menu()
            else:
                return keymaptools.set_key()

        elif item.channel == "infoplus":
            from platformcode import infoplus
            return infoplus.Main(item)

        elif item.channel == "backup":
            from platformcode import backup
            return getattr(backup, item.action)(item)

        elif item.channel == "elementum_download":
            from platformcode import elementum_download
            return getattr(elementum_download, item.action)(item)

        elif item.channel == "shortcuts":
            from platformcode import shortcuts
            return getattr(shortcuts, item.action)(item)

        elif item.channel == "autorenumber":
            from platformcode import autorenumber
            return getattr(autorenumber, item.action)(item)

        elif item.action == "delete_key":
            from platformcode import keymaptools
            return keymaptools.delete_key()

        elif item.action == "script":
            from core import tmdb
            if tmdb.drop_bd():
                platformtools.dialog_notification(
                    config.get_localized_string(20000),
                    config.get_localized_string(60011),
                    time=2000,
                    sound=False)
        elif item.action == "itemInfo":
            platformtools.dialog_textviewer('Item info', item.parent)
        elif item.action == "open_browser":
            import webbrowser
            if not webbrowser.open(item.url):
                import xbmc
                if xbmc.getCondVisibility(
                        'system.platform.linux') and xbmc.getCondVisibility(
                            'system.platform.android'):  # android
                    xbmc.executebuiltin(
                        'StartAndroidActivity("", "android.intent.action.VIEW", "", "%s")'
                        % (item.url))
                else:
                    try:
                        import urllib.request as urllib
                    except ImportError:
                        import urllib
                    short = urllib.urlopen(
                        'https://u.nu/api.php?action=shorturl&format=simple&url='
                        + item.url).read().decode('utf-8')
                    platformtools.dialog_ok(
                        config.get_localized_string(20000),
                        config.get_localized_string(70740) % short)
        # Action in certain channel specified in "action" and "channel" parameters
        elif item.action == "check_channels":
            from platformcode import checkhost
            checkhost.check_channels()
        else:
            # Checks if channel exists
            if os.path.isfile(
                    os.path.join(config.get_runtime_path(), 'channels',
                                 item.channel + ".py")):
                CHANNELS = 'channels'
            else:
                CHANNELS = 'specials'

            channel_file = os.path.join(config.get_runtime_path(), CHANNELS,
                                        item.channel + ".py")

            logger.debug("channel_file= " + channel_file + ' - ' + CHANNELS +
                         ' - ' + item.channel)

            channel = None

            if os.path.exists(channel_file):
                try:
                    channel = __import__('%s.%s' % (CHANNELS, item.channel),
                                         None, None,
                                         ['%s.%s' % (CHANNELS, item.channel)])
                except ImportError:
                    exec("import " + CHANNELS + "." + item.channel +
                         " as channel")

            logger.info("Running channel %s | %s" %
                        (channel.__name__, channel.__file__))

            # Special play action
            if item.action == "play":
                # define la info para trakt
                try:
                    from core import trakt_tools
                    trakt_tools.set_trakt_info(item)
                except:
                    pass
                logger.debug("item.action=%s" % item.action.upper())
                # logger.debug("item_toPlay: " + "\n" + item.tostring('\n'))

                # First checks if channel has a "play" function
                if hasattr(channel, 'play'):
                    logger.debug("Executing channel 'play' method")
                    itemlist = channel.play(item)
                    b_favourite = item.isFavourite
                    # Play should return a list of playable URLS
                    if len(itemlist) > 0 and isinstance(itemlist[0], Item):
                        item = itemlist[0]
                        if b_favourite:
                            item.isFavourite = True
                        platformtools.play_video(item)

                    # Permitir varias calidades desde play en el Channel
                    elif len(itemlist) > 0 and isinstance(itemlist[0], list):
                        item.video_urls = itemlist
                        platformtools.play_video(item)

                    # If not, shows user an error message
                    else:
                        platformtools.dialog_ok(
                            config.get_localized_string(20000),
                            config.get_localized_string(60339))

                # If player don't have a "play" function, not uses the standard play from platformtools
                else:
                    logger.debug("Executing core 'play' method")
                    platformtools.play_video(item)

            # Special action for findvideos, where the plugin looks for known urls
            elif item.action == "findvideos":
                from core import servertools

                # First checks if channel has a "findvideos" function
                if hasattr(channel, 'findvideos'):
                    itemlist = getattr(channel, item.action)(item)

                # If not, uses the generic findvideos function
                else:
                    logger.debug("No channel 'findvideos' method, "
                                 "executing core method")
                    itemlist = servertools.find_video_items(item)

                if config.get_setting("max_links", "videolibrary") != 0:
                    itemlist = limit_itemlist(itemlist)

                from platformcode import subtitletools
                subtitletools.saveSubtitleName(item)

                platformtools.render_items(itemlist, item)

            # Special action for adding a movie to the library
            elif item.action == "add_pelicula_to_library":
                from core import videolibrarytools
                videolibrarytools.add_movie(item)

            # Special action for adding a serie to the library
            elif item.action == "add_serie_to_library":
                from core import videolibrarytools
                videolibrarytools.add_tvshow(item, channel)

            # Special action for downloading all episodes from a serie
            elif item.action == "download_all_episodes":
                from specials import downloads
                item.action = item.extra
                del item.extra
                downloads.save_download(item)

            # Special action for searching, first asks for the words then call the "search" function
            elif item.action == "search":
                # from core.support import dbg;dbg()
                if filetools.isfile(temp_search_file) and config.get_setting(
                        'videolibrary_kodi'):
                    itemlist = []
                    f = filetools.read(temp_search_file)
                    strList = f.split(',')
                    if strList[0] == '[V]' and strList[1] == item.channel:
                        for it in strList:
                            if it and it not in ['[V]', item.channel]:
                                itemlist.append(Item().fromurl(it))
                        filetools.write(temp_search_file, f[4:])
                        return platformtools.render_items(itemlist, item)
                    else:
                        filetools.remove(temp_search_file)

                logger.debug("item.action=%s" % item.action.upper())
                from core import channeltools

                if config.get_setting('last_search'):
                    last_search = channeltools.get_channel_setting(
                        'Last_searched', 'search', '')
                else:
                    last_search = ''

                search_text = platformtools.dialog_input(last_search)

                if search_text is not None:
                    channeltools.set_channel_setting('Last_searched',
                                                     search_text, 'search')
                    itemlist = new_search(item.clone(text=search_text),
                                          channel)
                else:
                    return

                platformtools.render_items(itemlist, item)

            # For all other actions
            else:
                # import web_pdb; web_pdb.set_trace()
                logger.debug("Executing channel '%s' method" % item.action)
                itemlist = getattr(channel, item.action)(item)
                if config.get_setting('trakt_sync'):
                    from core import trakt_tools
                    token_auth = config.get_setting("token_trakt", "trakt")
                    if not token_auth:
                        trakt_tools.auth_trakt()
                    else:
                        import xbmc
                        if not xbmc.getCondVisibility(
                                'System.HasAddon(script.trakt)'
                        ) and config.get_setting('install_trakt'):
                            trakt_tools.ask_install_script()
                    itemlist = trakt_tools.trakt_check(itemlist)
                else:
                    config.set_setting('install_trakt', True)

                platformtools.render_items(itemlist, item)

    except WebErrorException as e:
        import traceback
        from core import scrapertools

        logger.error(traceback.format_exc())

        platformtools.dialog_ok(
            config.get_localized_string(59985) % e.channel,
            config.get_localized_string(60013) % e.url)
    except Exception as e:
        import traceback
        from core import scrapertools

        logger.error(traceback.format_exc())

        patron = 'File "' + os.path.join(config.get_runtime_path(), "channels",
                                         "").replace("\\",
                                                     "\\\\") + r'([^.]+)\.py"'
        Channel = scrapertools.find_single_match(traceback.format_exc(),
                                                 patron)

        if Channel or e.__class__ == logger.ChannelScraperException:
            if item.url:
                if platformtools.dialog_yesno(
                        config.get_localized_string(60087) % Channel,
                        config.get_localized_string(60014),
                        nolabel='ok',
                        yeslabel=config.get_localized_string(70739)):
                    run(Item(action="open_browser", url=item.url))
            else:
                platformtools.dialog_ok(
                    config.get_localized_string(60087) % Channel,
                    config.get_localized_string(60014))
        else:
            if platformtools.dialog_yesno(config.get_localized_string(60038),
                                          config.get_localized_string(60015)):
                run(Item(channel="setting", action="report_menu"))
示例#45
0
def addchannel(item):
    import os
    import time
    logger.info()

    tecleado = platformtools.dialog_input("", "Introduzca la URL")
    if not tecleado:
        return
    logger.info("url=%s" % tecleado)

    local_folder = config.get_runtime_path()
    if "canal" in item.title:
        local_folder = filetools.join(local_folder, 'channels')
        folder_to_extract = "channels"
        info_accion = "canal"
    else:
        local_folder = filetools.join(local_folder, 'servers')
        folder_to_extract = "servers"
        info_accion = "conector"

    # Detecta si es un enlace a un .py o .xml (pensado sobre todo para enlaces de github)
    try:
        extension = tecleado.rsplit(".", 1)[1]
    except:
        extension = ""

    files = []
    zip = False
    if extension == "py" or extension == "xml":
        filename = tecleado.rsplit("/", 1)[1]
        localfilename = filetools.join(local_folder, filename)
        files.append([tecleado, localfilename, filename])
    else:
        import re
        from core import scrapertools
        # Comprueba si la url apunta a una carpeta completa (channels o servers) de github
        if re.search(r'https://github.com/[^\s]+/'+folder_to_extract, tecleado):
            try:
                data = scrapertools.downloadpage(tecleado)
                matches = scrapertools.find_multiple_matches(data,
                                                             '<td class="content">.*?href="([^"]+)".*?title="([^"]+)"')
                for url, filename in matches:
                    url = "https://raw.githubusercontent.com" + url.replace("/blob/", "/")
                    localfilename = filetools.join(local_folder, filename)
                    files.append([url, localfilename, filename])
            except:
                import traceback
                logger.error("Detalle del error: %s" % traceback.format_exc())
                platformtools.dialog_ok("Error", "La url no es correcta o no está disponible")
                return
        else:
            filename = 'new%s.zip' % info_accion
            localfilename = filetools.join(config.get_data_path(), filename)
            files.append([tecleado, localfilename, filename])
            zip = True

    logger.info("localfilename=%s" % localfilename)
    logger.info("descarga fichero...")

    try:
        if len(files) > 1:
            lista_opciones = ["No", "Sí", "Sí (Sobrescribir todos)"]
            overwrite_all = False
        from core import downloadtools
        for url, localfilename, filename in files:
            result = downloadtools.downloadfile(url, localfilename, continuar=False, resumir=False)
            if result == -3:
                if len(files) == 1:
                    dyesno = platformtools.dialog_yesno("El archivo ya existe", "Ya existe el %s %s. "
                                                                                "¿Desea sobrescribirlo?" %
                                                        (info_accion, filename))
                else:
                    if not overwrite_all:
                        dyesno = platformtools.dialog_select("El archivo %s ya existe, ¿desea sobrescribirlo?"
                                                             % filename, lista_opciones)
                    else:
                        dyesno = 1
                # Diálogo cancelado
                if dyesno == -1:
                    return
                # Caso de carpeta github, opción sobrescribir todos
                elif dyesno == 2:
                    overwrite_all = True
                elif dyesno:
                    hora_folder = "Copia seguridad [%s]" % time.strftime("%d-%m_%H-%M", time.localtime())
                    backup = filetools.join(config.get_data_path(), 'backups', hora_folder, folder_to_extract)
                    if not filetools.exists(backup):
                        os.makedirs(backup)
                    import shutil
                    shutil.copy2(localfilename, filetools.join(backup, filename))
                    downloadtools.downloadfile(url, localfilename, continuar=True, resumir=False)
                else:
                    if len(files) == 1:
                        return
                    else:
                        continue
    except:
        import traceback
        logger.error("Detalle del error: %s" % traceback.format_exc())
        return

    if zip:
        try:
            # Lo descomprime
            logger.info("descomprime fichero...")
            from core import ziptools
            unzipper = ziptools.ziptools()
            logger.info("destpathname=%s" % local_folder)
            unzipper.extract(localfilename, local_folder, folder_to_extract, True, True)
        except:
            import traceback
            logger.error("Detalle del error: %s" % traceback.format_exc())
            # Borra el zip descargado
            filetools.remove(localfilename)
            platformtools.dialog_ok("Error", "Se ha producido un error extrayendo el archivo")
            return

        # Borra el zip descargado
        logger.info("borra fichero...")
        filetools.remove(localfilename)
        logger.info("...fichero borrado")

    platformtools.dialog_ok("Éxito", "Actualización/Instalación realizada correctamente")
示例#46
0
def btdigg(item):
    if not PY3: from lib.alfaresolver import find_alternative_link
    else: from lib.alfaresolver_py3 import find_alternative_link

    context = [{
        "title": "Copiar a Mis Torrents",
        "action": "copy_file",
        "channel": "url"
    }]
    if item.torrent_params:
        torrent_params = item.torrent_params
        del item.torrent_params
    else:
        torrent_params = {'find_alt_link_next': 0}
    itemlist = []
    find_alt_link_result = []

    if not item.btdigg:
        item.btdigg = platformtools.dialog_input(
            heading=
            'Introduce criterios de búsqueda (ej: all american 720p Cap.102 atomixhq)'
        )

    if item.btdigg:
        torrent_params = find_alternative_link(item,
                                               torrent_params=torrent_params,
                                               cache=True)
        find_alt_link_result = torrent_params['find_alt_link_result']

    for scrapedurl, _scrapedtitle, scrapedsize, scrapedquality, scrapedmagnet in find_alt_link_result:
        item_local = item.clone()
        scrapedtitle = config.decode_var(_scrapedtitle)

        item_local.url = scrapedmagnet
        item_local.server = 'torrent'
        item_local.contentType = 'movie'
        item_local.action = 'play'
        item_local.quality = scrapedquality
        item_local.language = torrent_params['find_alt_link_language']
        item_local.torrent_info = '%s [MAGNET]: %s' % (
            scrapedsize,
            scrapedtitle.replace(
                '[B][COLOR limegreen]BT[/COLOR][COLOR red]Digg[/COLOR][/B] ',
                ''))
        item_local.title = scrapedtitle.replace(
            '[B][COLOR limegreen]BT[/COLOR][COLOR red]Digg[/COLOR][/B] ', '')
        item_local.copytitle = item_local.title
        item_local.contentTitle = '%s / %s' % (item.btdigg, item_local.title)
        item_local.torrents_path = ''
        item_local.infoLabels["tmdb_id"] = "111"
        item_local.context = context
        item_local.btdigg = True

        itemlist.append(item_local)

    if torrent_params['find_alt_link_next'] > 0:
        itemlist.append(
            item.clone(
                action='btdigg',
                title=">> Página siguiente " +
                str(torrent_params['find_alt_link_next'] + 1) + ' de ' +
                str(int(torrent_params['find_alt_link_found'] / 10) + 1),
                torrent_params=torrent_params))
    return itemlist
示例#47
0
def run():
    logger.info("pelisalacarta.platformcode.launcher run")

    # Extract item from sys.argv
    if sys.argv[2]:
        item = Item().fromurl(sys.argv[2])

    # If no item, this is mainlist
    else:
        item = Item(channel="channelselector", action="getmainlist", viewmode="movie")

    logger.info("pelisalacarta.platformcode.launcher "+item.tostring())
    
    try:

        # If item has no action, stops here
        if item.action == "":
            logger.info("pelisalacarta.platformcode.launcher Item sin accion")
            return

        # Action for main menu in channelselector
        if item.action == "getmainlist":
            import channelselector
            itemlist = channelselector.getmainlist()

            # Check for updates only on first screen
            if config.get_setting("updatecheck2") == "true":
                logger.info("pelisalacarta.platformcode.launcher Check for plugin updates enabled")
                from core import updater
                
                try:
                    version = updater.checkforupdates()

                    if version:
                        platformtools.dialog_ok("Versión "+version+" disponible",
                                                "Ya puedes descargar la nueva versión del plugin\n"
                                                "desde el listado principal")

                        itemlist.insert(0, Item(title="Descargar version "+version, version=version, channel="updater",
                                                action="update", thumbnail=channelselector.get_thumbnail_path() +
                                                "Crystal_Clear_action_info.png"))
                except:
                    platformtools.dialog_ok("No se puede conectar", "No ha sido posible comprobar",
                                            "si hay actualizaciones")
                    logger.info("cpelisalacarta.platformcode.launcher Fallo al verificar la actualización")

            else:
                logger.info("pelisalacarta.platformcode.launcher Check for plugin updates disabled")

            platformtools.render_items(itemlist, item)

        # Action for updating plugin
        elif item.action == "update":

            from core import updater
            updater.update(item)
            if config.get_system_platform() != "xbox":
                import xbmc
                xbmc.executebuiltin("Container.Refresh")

        # Action for channel types on channelselector: movies, series, etc.
        elif item.action == "getchanneltypes":
            import channelselector
            itemlist = channelselector.getchanneltypes()

            platformtools.render_items(itemlist, item)

        # Action for channel listing on channelselector
        elif item.action == "filterchannels":
            import channelselector
            itemlist = channelselector.filterchannels(item.channel_type)

            platformtools.render_items(itemlist, item)

        # Special action for playing a video from the library
        elif item.action == "play_from_library":
            play_from_library(item)
            return

        # Action in certain channel specified in "action" and "channel" parameters
        else:

            # Entry point for a channel is the "mainlist" action, so here we check parental control
            if item.action == "mainlist":
                
                # Parental control
                can_open_channel = False

                # If it is an adult channel, and user has configured pin, asks for it
                if channeltools.is_adult(item.channel) and config.get_setting("adult_pin") != "":

                    tecleado = platformtools.dialog_input("", "PIN para canales de adultos", True)
                    if tecleado is not None:
                        if tecleado == config.get_setting("adult_pin"):
                            can_open_channel = True

                # All the other cases can open the channel
                else:
                    can_open_channel = True

                if not can_open_channel:
                    return

            # Checks if channel exists
            channel_file = os.path.join(config.get_runtime_path(), 'channels', item.channel+".py")
            logger.info("pelisalacarta.platformcode.launcher channel_file=%s" % channel_file)

            channel = None

            if item.channel in ["personal", "personal2", "personal3", "personal4", "personal5"]:
                import channels.personal as channel

            elif os.path.exists(channel_file):
                try:
                    channel = __import__('channels.%s' % item.channel, None, None, ["channels.%s" % item.channel])
                except ImportError:
                    exec "import channels."+item.channel+" as channel"

            logger.info("pelisalacarta.platformcode.launcher running channel "+channel.__name__+" "+channel.__file__)

            # Special play action
            if item.action == "play":
                logger.info("pelisalacarta.platformcode.launcher play")
                # logger.debug("item_toPlay: " + "\n" + item.tostring('\n'))

                # First checks if channel has a "play" function
                if hasattr(channel, 'play'):
                    logger.info("pelisalacarta.platformcode.launcher executing channel 'play' method")
                    itemlist = channel.play(item)
                    b_favourite = item.isFavourite
                    # Play should return a list of playable URLS
                    if len(itemlist) > 0:
                        item = itemlist[0]
                        if b_favourite:
                            item.isFavourite = True
                        platformtools.play_video(item)

                    # If not, shows user an error message
                    else:
                        platformtools.dialog_ok("plugin", "No hay nada para reproducir")

                # If player don't have a "play" function, not uses the standard play from platformtools
                else:
                    logger.info("pelisalacarta.platformcode.launcher executing core 'play' method")
                    platformtools.play_video(item)

            # Special action for findvideos, where the plugin looks for known urls
            elif item.action == "findvideos":

                # First checks if channel has a "findvideos" function
                if hasattr(channel, 'findvideos'):
                    itemlist = getattr(channel, item.action)(item)

                # If not, uses the generic findvideos function
                else:
                    logger.info("pelisalacarta.platformcode.launcher no channel 'findvideos' method, "
                                "executing core method")
                    from core import servertools
                    itemlist = servertools.find_video_items(item)

                if config.get_setting('filter_servers') == 'true':
                    itemlist = filtered_servers(itemlist)

                from platformcode import subtitletools
                subtitletools.saveSubtitleName(item)

                platformtools.render_items(itemlist, item)

            # Special action for adding a movie to the library
            elif item.action == "add_pelicula_to_library":
                library.add_pelicula_to_library(item)

            # Special action for adding a serie to the library
            elif item.action == "add_serie_to_library":
                library.add_serie_to_library(item, channel)

            # Special action for downloading all episodes from a serie
            elif item.action == "download_all_episodes":
                from channels import descargas
                item.action = item.extra
                del item.extra
                descargas.save_download(item)

            # Special action for searching, first asks for the words then call the "search" function
            elif item.action == "search":
                logger.info("pelisalacarta.platformcode.launcher search")
                
                tecleado = platformtools.dialog_input("")
                if tecleado is not None:
                    tecleado = tecleado.replace(" ", "+")
                    # TODO revisar 'personal.py' porque no tiene función search y daría problemas
                    itemlist = channel.search(item, tecleado)
                else:
                    itemlist = []
                
                platformtools.render_items(itemlist, item)

            # For all other actions
            else:
                logger.info("pelisalacarta.platformcode.launcher executing channel '"+item.action+"' method")
                itemlist = getattr(channel, item.action)(item)
                platformtools.render_items(itemlist, item)

    except urllib2.URLError, e:
        import traceback
        logger.error("pelisalacarta.platformcode.launcher "+traceback.format_exc())

        # Grab inner and third party errors
        if hasattr(e, 'reason'):
            logger.info("pelisalacarta.platformcode.launcher Razon del error, codigo: "+str(e.reason[0])+", Razon: " +
                        str(e.reason[1]))
            texto = config.get_localized_string(30050)  # "No se puede conectar con el sitio web"
            platformtools.dialog_ok("plugin", texto)

        # Grab server response errors
        elif hasattr(e, 'code'):
            logger.info("pelisalacarta.platformcode.launcher codigo de error HTTP : %d" % e.code)
            # "El sitio web no funciona correctamente (error http %d)"
            platformtools.dialog_ok("plugin", config.get_localized_string(30051) % e.code)