Exemple #1
0
def play_video(item, strm=False):
    logger.info("deportesalacarta.platformcode.platformtools play_video")
    #logger.debug(item.tostring('\n'))

    if item.channel == 'descargas':
        logger.info("Reproducir video local: %s [%s]" % (item.title, item.url))
        playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
        playlist.clear()
        playlist.add(item.url)
        xbmc.Player().play(playlist)
        return

    default_action = config.get_setting("default_action")
    logger.info("default_action=" + default_action)

    # Abre el diálogo de selección para ver las opciones disponibles
    opciones, video_urls, seleccion, salir = get_dialogo_opciones(
        item, default_action, strm)
    if salir:
        return

    # se obtienen la opción predeterminada de la configuración del addon
    seleccion = get_seleccion(default_action, opciones, seleccion, video_urls)
    if seleccion < 0:  # Cuadro cancelado
        return

    logger.info("seleccion=%d" % seleccion)
    logger.info("seleccion=%s" % opciones[seleccion])

    # se ejecuta la opcion disponible, jdwonloader, descarga, favoritos, añadir a la biblioteca... SI NO ES PLAY
    salir = set_opcion(item, seleccion, opciones, video_urls)
    if salir:
        return

    # obtenemos el video seleccionado
    mediaurl, view, mpd = get_video_seleccionado(item, seleccion, video_urls)
    if mediaurl == "":
        return

    # se obtiene la información del video.
    xlistitem = xbmcgui.ListItem(path=mediaurl, thumbnailImage=item.thumbnail)
    set_infolabels(xlistitem, item)

    if mpd:
        xlistitem.setProperty('inputstreamaddon', 'inputstream.adaptive')
        xlistitem.setProperty('inputstream.adaptive.manifest_type', 'mpd')

    # se lanza el reproductor
    info = False
    if "_ventana" in opciones[seleccion]:
        info = True
    set_player(item, xlistitem, mediaurl, view, strm, info)

    # si es un archivo de la biblioteca enviar a marcar como visto
    if strm or item.strm_path:
        from platformcode import library
        library.mark_auto_as_watched(item)
Exemple #2
0
def is_server_enabled(server):
    try:
        server_parameters = get_server_parameters(server)
        if server_parameters["active"] == "true":
            if not config.get_setting("hidepremium")=="true":
                return True
            else:
                if server_parameters["free"] == "true":
                    return True
                if [premium for premium in server_parameters["premium"] if config.get_setting(premium+"premium")=="true"]:
                    return True
                else:
                    return False
        else:
            return False
    except:
        import traceback
        logger.info(traceback.format_exc())
        return False
def start():
    tecla_guardada = config.get_setting("keymap_edit", "editor_keymap")
    nuevakey = KeyListener().record_key()
    if nuevakey and tecla_guardada != nuevakey:
        from resources.lib.httpkir import filetools
        from platformcode import platformtools
        import xbmc
        file_xml = "special://profile/keymaps/deportesalacarta.xml"
        data = '<keymap><global><keyboard><key id="%s">' % nuevakey + 'runplugin(plugin://' \
               'plugin.video.dss/?ewogICAgImFjdGlvbiI6ICJzdGFydCIsIAogICAgImNoYW5uZWwiOiAibWF0Y2hjZ' \
               'W50ZXIiLCAKICAgICJpbmZvTGFiZWxzIjoge30KfQ%3D%3D))</key></keyboard></global></keymap>'
        filetools.write(xbmc.translatePath(file_xml), data)
        platformtools.dialog_notification(
            "Tecla guardada", "Reinicia Kodi para que se apliquen los cambios")

        from resources.lib.httpkir import scrapertools
        config.set_setting("keymap_edit", nuevakey, "editor_keymap")
        file_idioma = filetools.join(config.get_runtime_path(), 'resources',
                                     'language', 'Spanish', 'strings.xml')
        data = filetools.read(file_idioma)
        value_xml = scrapertools.find_single_match(
            data, '<string id="31100">([^<]+)<')
        if "tecla" in value_xml:
            data = data.replace(
                value_xml,
                'Cambiar tecla/botón para abrir la ventana (Guardada: %s)' %
                nuevakey)
        elif "key" in value_xml:
            data = data.replace(
                value_xml,
                'Change key/button to open the window (Saved: %s)' % nuevakey)
        else:
            data = data.replace(
                value_xml,
                'Cambiamento di chiave/pulsante per aprire la finestra (Salvato: %s)'
                % nuevakey)
        filetools.write(file_idioma, data)

    return
Exemple #4
0
def run():
    logger.info("dss.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")

    if item.action != "actualiza":
        logger.info("dss.platformcode.launcher " + item.tostring())

    try:
        if item.action == "editor_keymap":
            from platformcode import editor_keymap
            return editor_keymap.start()

        # If item has no action, stops here
        if item.action == "":
            logger.info("dss.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("updatecheck") == "true":
                logger.info("Check for plugin updates enabled")
                from core import updater

                try:
                    update, version_publicada, message, url_repo, serv = updater.check(
                    )

                    if update:
                        new_item = Item(
                            title="Descargar versión " + version_publicada,
                            channel="updater",
                            action="actualiza",
                            thumbnail=channelselector.get_thumbnail_path() +
                            "Crystal_Clear_action_info.png",
                            version=version_publicada,
                            url=url_repo,
                            server=serv)
                        if config.get_setting("updateauto") == "true":
                            updater.actualiza(new_item)
                            new_item = Item(
                                title=
                                "Info para ver los cambios en la nueva versión instalada",
                                plot=message,
                                action="",
                                channel="",
                                thumbnail=channelselector.get_thumbnail_path()
                                + "Crystal_Clear_action_info.png",
                                text_color="red")
                            itemlist.insert(0, new_item)
                        else:
                            platformtools.dialog_ok(
                                "Versión " + version_publicada + " disponible",
                                message)

                            itemlist.insert(0, new_item)
                except:
                    import traceback
                    logger.info(traceback.format_exc())
                    logger.info(
                        "dss.platformcode.launcher Fallo al verificar la actualización"
                    )

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

            if not config.get_setting("primer_uso_matchcenter"):
                config.set_setting("primer_uso_matchcenter", "true")
                platformtools.dialog_ok(
                    "MatchCenter activado",
                    "Reinicia Kodi para usarlo (pulsar tecla U)",
                    "La tecla, botones y otras opciones pueden cambiarse en Configuración -> Preferencias -> MatchCenter"
                )

            file_keyboard = xbmc.translatePath(
                "special://profile/keymaps/deportesalacarta.xml")
            if config.get_setting(
                    "matchcenter_enabled"
            ) == "true" and not os.path.exists(file_keyboard):
                tecla = "61525"
                tecla_guardada = config.get_setting("keymap_edit",
                                                    "editor_keymap")
                if tecla_guardada:
                    tecla = tecla_guardada
                from core import filetools
                data = '<keymap><global><keyboard><key id="%s">' % tecla + 'runplugin(plugin://plugin.video.dss/?ewogICAgImFjdGlvbiI6ICJzdGFydCIsIAogICAgImNoYW5uZWwiOiAibWF0Y2hjZW50ZXIiLCAKICAgICJpbmZvTGFiZWxzIjoge30KfQ%3D%3D))</key></keyboard></global></keymap>'
                filetools.write(file_keyboard, data)
            elif config.get_setting(
                    "matchcenter_enabled") == "false" and os.path.exists(
                        file_keyboard):
                from core import filetools
                try:
                    filetools.remove(file_keyboard)
                except:
                    pass

            platformtools.render_items(itemlist, item)

        # Action for updating plugin
        elif item.action == "actualiza":
            from core import updater
            updater.actualiza(item)
            xbmc.executebuiltin("Container.Refresh")

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

            platformtools.render_items(itemlist, item)

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

            # Checks if channel exists
            channel_file = os.path.join(config.get_runtime_path(), 'channels',
                                        item.channel + ".py")
            logger.info("dss.platformcode.launcher 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(
                "deportesalacarta.platformcode.launcher running channel " +
                channel.__name__ + " " + channel.__file__)

            # Special play action
            if item.action == "play":
                logger.info("dss.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(
                        "dss.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 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",
                                                "There is nothing to play")

                # If player don't have a "play" function, not uses the standard play from platformtools
                else:
                    logger.info(
                        "dss.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(
                        "dss.platformcode.launcher no channel 'findvideos' method, "
                        "executing core method")
                    from core import servertools
                    itemlist = servertools.find_video_items(item)

                platformtools.render_items(itemlist, item)

            # Special action for searching, first asks for the words then call the "search" function
            elif item.action == "search":
                logger.info("dss.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("dss.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("dss.platformcode.launcher " + traceback.format_exc())

        # Grab inner and third party errors
        if hasattr(e, 'reason'):
            logger.info("dss.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("dss.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)
Exemple #5
0
def play(url, xlistitem={}, is_view=None, subtitle=""):

    allocate = True
    try:
        import platform
        xbmc.log(
            "XXX KODI XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
        )
        xbmc.log("OS platform: %s %s" %
                 (platform.system(), platform.release()))
        xbmc.log("xbmc/kodi version: %s" %
                 xbmc.getInfoLabel("System.BuildVersion"))
        xbmc_version = int(xbmc.getInfoLabel("System.BuildVersion")[:2])
        xbmc.log("xbmc/kodi version number: %s" % xbmc_version)
        xbmc.log(
            "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX KODI XXXX"
        )

        _platform = get_platform()
        if str(_platform['system']) in [
                "android_armv7", "linux_armv6", "linux_armv7"
        ]:
            allocate = False
        # -- log ------------------------------------------------
        xbmc.log(
            "XXX platform XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
        )
        xbmc.log("_platform['system']: %s" % _platform['system'])
        xbmc.log("allocate: %s" % allocate)
        xbmc.log(
            "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX platform XXXX"
        )
        # -- ----------------------------------------------------
    except:
        pass

    DOWNLOAD_PATH = config.get_setting("downloadpath")

    # -- adfly: ------------------------------------
    if url.startswith("http://adf.ly/"):
        try:
            data = scrapertools.downloadpage(url)
            url = decode_adfly(data)
        except:
            ddd = xbmcgui.Dialog()
            ddd.ok(
                "pelisalacarta-MCT: Sin soporte adf.ly",
                "El script no tiene soporte para el acortador de urls adf.ly.",
                "", "url: " + url)
            return

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

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

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

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

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

    # -- log ----------------------------------------------------
    xbmc.log("### Init session ########")
    xbmc.log(lt.version)
    xbmc.log("#########################")
    # -- --------------------------------------------------------

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

    trackers = [
        "udp://tracker.openbittorrent.com:80/announce",
        "http://tracker.torrentbay.to:6969/announce",
        "http://tracker.pow7.com/announce",
        "udp://tracker.ccc.de:80/announce",
        "udp://open.demonii.com:1337",
        "http://9.rarbg.com:2710/announce",
        "http://bt.careland.com.cn:6969/announce",
        "http://explodie.org:6969/announce",
        "http://mgtracker.org:2710/announce",
        "http://tracker.best-torrents.net:6969/announce",
        "http://tracker.tfile.me/announce",
        "http://tracker1.wasabii.com.tw:6969/announce",
        "udp://9.rarbg.com:2710/announce",
        "udp://9.rarbg.me:2710/announce",
        "udp://coppersurfer.tk:6969/announce",
        "http://www.spanishtracker.com:2710/announce",
        "http://www.todotorrents.com:2710/announce",
    ]

    video_file = ""
    # -- magnet2torrent -----------------------------------------
    if torrent_file.startswith("magnet"):
        try:
            import zlib
            btih = hex(
                zlib.crc32(
                    scrapertools.get_match(
                        torrent_file,
                        'magnet:\?xt=urn:(?:[A-z0-9:]+|)([A-z0-9]{32})'))
                & 0xffffffff)
            files = [
                f for f in os.listdir(save_path_torrents)
                if os.path.isfile(os.path.join(save_path_torrents, f))
            ]
            for file in files:
                if btih in os.path.basename(file):
                    torrent_file = os.path.join(save_path_torrents, file)
        except:
            pass

    if torrent_file.startswith("magnet"):
        try:
            tempdir = tempfile.mkdtemp()
        except IOError:
            tempdir = os.path.join(save_path_torrents, "temp")
            if not os.path.exists(tempdir):
                os.mkdir(tempdir)
        params = {
            'save_path': tempdir,
            'trackers': trackers,
            'storage_mode': lt.storage_mode_t.storage_mode_allocate,
            'paused': False,
            'auto_managed': True,
            'duplicate_is_error': True
        }
        h = lt.add_magnet_uri(ses, torrent_file, params)
        dp = xbmcgui.DialogProgress()
        dp.create('pelisalacarta-MCT')
        while not h.has_metadata():
            message, porcent, msg_file, s, download = getProgress(
                h, "Creando torrent desde magnet")
            dp.update(porcent, message, msg_file)
            if s.state == 1: download = 1
            if dp.iscanceled():
                dp.close()
                remove_files(download, torrent_file, video_file, ses, h)
                return
            h.force_dht_announce()
            xbmc.sleep(1000)

        dp.close()
        info = h.get_torrent_info()
        data = lt.bencode(lt.create_torrent(info).generate())

        torrent_file = os.path.join(
            save_path_torrents,
            unicode(info.name() + "-" + btih, "'utf-8'", errors="replace") +
            ".torrent")
        f = open(torrent_file, 'wb')
        f.write(data)
        f.close()
        ses.remove_torrent(h)
        shutil.rmtree(tempdir)
    # -----------------------------------------------------------

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

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

    # -- Prioritarizar/Seleccionar archivo-----------------------
    _index, video_file, video_size, len_files = get_video_files_sizes(info)
    if len_files == 0:
        dp = xbmcgui.Dialog().ok(
            "No se puede reproducir",
            "El torrent no contiene ningún archivo de vídeo")

    if _index == -1:
        _index = _index_file
        video_file = _video_file
        video_size = _size_file

    _video_file_ext = os.path.splitext(_video_file)[1]
    xbmc.log("##### _video_file_ext ## %s ##" % _video_file_ext)
    if (_video_file_ext == ".avi" or _video_file_ext == ".mp4") and allocate:
        xbmc.log("##### storage_mode_t.storage_mode_allocate (" +
                 _video_file_ext + ") #####")
        h = ses.add_torrent({
            'ti':
            info,
            'save_path':
            save_path_videos,
            'trackers':
            trackers,
            'storage_mode':
            lt.storage_mode_t.storage_mode_allocate
        })
    else:
        xbmc.log("##### storage_mode_t.storage_mode_sparse (" +
                 _video_file_ext + ") #####")
        h = ses.add_torrent({
            'ti':
            info,
            'save_path':
            save_path_videos,
            'trackers':
            trackers,
            'storage_mode':
            lt.storage_mode_t.storage_mode_sparse
        })
        allocate = True
    # -----------------------------------------------------------

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

    h.force_reannounce()
    h.force_dht_announce()

    # -- Inicio de variables para 'pause' automático cuando el  -
    # -- el vídeo se acerca a una pieza sin completar           -
    is_greater_num_pieces = False
    is_greater_num_pieces_plus = False
    is_greater_num_pieces_pause = False

    porcent4first_pieces = int(video_size * 0.000000005)
    if porcent4first_pieces < 10: porcent4first_pieces = 10
    if porcent4first_pieces > 100: porcent4first_pieces = 100
    porcent4last_pieces = int(porcent4first_pieces / 2)

    num_pieces_to_resume = int(video_size * 0.0000000025)
    if num_pieces_to_resume < 5: num_pieces_to_resume = 5
    if num_pieces_to_resume > 25: num_pieces_to_resume = 25

    xbmc.log("##### porcent4first_pieces ## %s ##" % porcent4first_pieces)
    xbmc.log("##### porcent4last_pieces ## %s ##" % porcent4last_pieces)
    xbmc.log("##### num_pieces_to_resume ## %s ##" % num_pieces_to_resume)

    # -- Prioritarizar o seleccionar las piezas del archivo que -
    # -- se desea reproducir con 'file_priorities'              -
    piece_set = set_priority_pieces(h, _index, video_file, video_size,
                                    porcent4first_pieces, porcent4last_pieces,
                                    allocate)

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

    _pieces_info = {}

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

        xbmc.sleep(100)

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

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

        # -- Player - play --------------------------------------
        # -- Comprobar si se han completado las piezas para el  -
        # -- inicio del vídeo                                   -
        first_pieces = True

        _c = 0
        for i in range(piece_set[0], piece_set[porcent4first_pieces]):
            first_pieces &= h.have_piece(i)
            if h.have_piece(i): _c += 1
        _pieces_info = {
            'current': 0,
            'continuous': "%s/%s" % (_c, porcent4first_pieces),
            'continuous2': "",
            'have': h.status().num_pieces,
            'len': len(piece_set)
        }

        last_pieces = True
        if not allocate:
            _c = len(piece_set) - 1
            _cc = 0
            for i in range(
                    len(piece_set) - porcent4last_pieces, len(piece_set)):
                last_pieces &= h.have_piece(i)
                if h.have_piece(i):
                    _c -= 1
                    _cc += 1
            _pieces_info['continuous2'] = "[%s/%s] " % (_cc,
                                                        porcent4last_pieces)

        if is_view != "Ok" and first_pieces and last_pieces:
            _pieces_info['continuous2'] = ""
            xbmc.log("##### porcent [%.2f%%]" % (s.progress * 100))
            is_view = "Ok"
            dp.close()

            # -- Player - Ver el vídeo --------------------------
            playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
            playlist.clear()

            ren_video_file = os.path.join(save_path_videos, video_file)
            try:
                playlist.add(ren_video_file, xlistitem)
            except:
                playlist.add(ren_video_file)

            if xbmc_version < 17:
                player = play_video(xbmc.PLAYER_CORE_AUTO)
            else:
                player = play_video()
            player.play(playlist)

            # -- Contador de cancelaciones para la ventana de   -
            # -- 'pause' automático                             -
            is_greater_num_pieces_canceled = 0
            continuous_pieces = 0
            porcent_time = 0.00
            current_piece = 0
            set_next_continuous_pieces = porcent4first_pieces

            # -- Impedir que kodi haga 'resume' a un archivo ----
            # -- que se reprodujo con anterioridad y que se     -
            # -- eliminó para impedir que intente la reprucción -
            # -- en una pieza que aún no se ha completado y se  -
            # -- active 'pause' automático                      -
            not_resume = True

            # -- Bandera subTítulos
            _sub = False

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

                # -- Añadir subTítulos
                if subtitle != "" and not _sub:
                    _sub = True
                    player.setSubtitles(subtitle)

                # -- Impedir que kodi haga 'resume' al inicio ---
                # -- de la descarga de un archivo conocido      -
                if not_resume:
                    player.seekTime(0)
                    not_resume = False

                # -- Control 'pause' automático                 -
                continuous_pieces = count_completed_continuous_pieces(
                    h, piece_set)

                if xbmc.Player().isPlaying():

                    # -- Porcentage del progreso del vídeo ------
                    player_getTime = player.getTime()
                    player_getTotalTime = player.getTotalTime()
                    porcent_time = player_getTime / player_getTotalTime * 100

                    # -- Pieza que se está reproduciendo --------
                    current_piece = int(porcent_time / 100 * len(piece_set))

                    # -- Banderas de control --------------------
                    is_greater_num_pieces = (
                        current_piece >
                        continuous_pieces - num_pieces_to_resume)
                    is_greater_num_pieces_plus = (
                        current_piece + porcent4first_pieces >
                        continuous_pieces)
                    is_greater_num_pieces_finished = (
                        current_piece + porcent4first_pieces >= len(piece_set))

                    # -- Activa 'pause' automático --------------
                    if is_greater_num_pieces and not player.paused and not is_greater_num_pieces_finished:
                        is_greater_num_pieces_pause = True
                        player.pause()

                    if continuous_pieces >= set_next_continuous_pieces:
                        set_next_continuous_pieces = continuous_pieces + num_pieces_to_resume
                    next_continuous_pieces = str(
                        continuous_pieces -
                        current_piece) + "/" + str(set_next_continuous_pieces -
                                                   current_piece)
                    _pieces_info = {
                        'current': current_piece,
                        'continuous': next_continuous_pieces,
                        'continuous2': _pieces_info['continuous2'],
                        'have': h.status().num_pieces,
                        'len': len(piece_set)
                    }

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

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

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

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

                    # -- Se canceló el progreso en el visionado -
                    # -- en la ventana de 'pause' automático.   -
                    # -- Parar si el contador llega a 3         -
                    if dp.iscanceled() and is_greater_num_pieces_pause:
                        is_greater_num_pieces_canceled += 1
                        if is_greater_num_pieces_canceled == 3:
                            player.stop()

                    # -- Desactiva 'pause' automático y ---------
                    # -- reinicia el contador de cancelaciones  -
                    if not dp.iscanceled(
                    ) and not is_greater_num_pieces_plus and is_greater_num_pieces_pause:
                        dp.close()
                        player.pause()
                        is_greater_num_pieces_pause = False
                        is_greater_num_pieces_canceled = 0

                    # -- El usuario cancelo el visionado --------
                    # -- Terminar                               -
                    if player.ended:
                        # -- Diálogo eliminar archivos ----------
                        remove_files(download, torrent_file, video_file, ses,
                                     h)
                        return

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

            if info.num_files() == 1:
                # -- Diálogo continuar o terminar ---------------
                d = xbmcgui.Dialog()
                ok = d.yesno('pelisalacarta-MCT', 'XBMC-Kodi Cerró el vídeo.',
                             '¿Continuar con la sesión?')
            else:
                ok = False
            # -- SI ---------------------------------------------
            if ok:
                # -- Continuar: ---------------------------------
                is_view = None
            else:
                # -- Terminar: ----------------------------------
                # -- Comprobar si el vídeo pertenece a una ------
                # -- lista de archivos                          -
                _index, video_file, video_size, len_files = get_video_files_sizes(
                    info)
                if _index == -1 or len_files == 1:
                    # -- Diálogo eliminar archivos --------------
                    remove_files(download, torrent_file, video_file, ses, h)
                    return
                else:
                    # -- Lista de archivos. Diálogo de opciones -
                    piece_set = set_priority_pieces(h, _index, video_file,
                                                    video_size,
                                                    porcent4first_pieces,
                                                    porcent4last_pieces,
                                                    allocate)
                    is_view = None
                    dp = xbmcgui.DialogProgress()
                    dp.create('pelisalacarta-MCT')

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

        # -- Se canceló el progreso antes del visionado ---------
        # -- Terminar                                           -
        if dp.iscanceled():
            dp.close()
            # -- Comprobar si el vídeo pertenece a una lista de -
            # -- archivos                                       -
            _index, video_file, video_size, len_files = get_video_files_sizes(
                info)
            if _index == -1 or len_files == 1:
                # -- Diálogo eliminar archivos ------------------
                remove_files(download, torrent_file, video_file, ses, h)
                return
            else:
                # -- Lista de archivos. Diálogo de opciones -----
                piece_set = set_priority_pieces(h, _index, video_file,
                                                video_size,
                                                porcent4first_pieces,
                                                porcent4last_pieces, allocate)
                is_view = None
                dp = xbmcgui.DialogProgress()
                dp.create('pelisalacarta-MCT')

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

    return
Exemple #6
0
    def onInit(self):
        self.getControl(10004).setEnabled(False)
        self.getControl(10005).setEnabled(False)
        self.getControl(10006).setEnabled(False)
        self.ok_enabled = False
        self.default_enabled = False
        
        if xbmcgui.__version__ == "1.2":
            self.setCoordinateResolution(1)
        else:
            self.setCoordinateResolution(5)

        # Ponemos el título
        self.getControl(10002).setLabel(self.title)
        
        

        if self.custom_button is not None:
            if self.custom_button['visible']:
                self.getControl(10006).setLabel(self.custom_button['label'])
            else:
                self.getControl(10006).setVisible(False)
                self.getControl(10004).setPosition(self.getControl(10004).getPosition()[0] + 80,
                                                   self.getControl(10004).getPosition()[1])
                self.getControl(10005).setPosition(self.getControl(10005).getPosition()[0] + 80,
                                                   self.getControl(10005).getPosition()[1])

        # Obtenemos las dimensiones del area de controles
        self.controls_width = self.getControl(10007).getWidth() - 20
        self.controls_height = self.getControl(10007).getHeight()
        self.controls_pos_x = self.getControl(10007).getPosition()[0] + self.getControl(10001).getPosition()[0] + 10
        self.controls_pos_y = self.getControl(10007).getPosition()[1] + self.getControl(10001).getPosition()[1]
        self.height_control = 35
        self.font = "font12"

        # En versiones antiguas: creamos 5 controles, de lo conrtario al hacer click al segundo control,
        # automaticamente cambia el label del tercero a "Short By: Name" no se porque...
        if xbmcgui.ControlEdit == ControlEdit:
            for x in range(5):
                control = xbmcgui.ControlRadioButton(-500, 0, 0, 0, "")
                self.addControl(control)


        for c in self.list_controls:
            # Saltamos controles que no tengan los valores adecuados
            if "type" not in c:
                continue
            if "label" not in c:
                continue
            if c["type"] != "label" and "id" not in c:
                continue
            if c["type"] == "list" and "lvalues" not in c:
                continue
            if c["type"] == "list" and not type(c["lvalues"]) == list:
                continue
            if c["type"] == "list" and not len(c["lvalues"]) > 0:
                continue
            if c["type"] != "label" and len([control.get("id") for control in self.list_controls if c["id"] == control.get("id")]) > 1:
                continue

            # Translation label y lvalues
            if c['label'].startswith('@') and unicode(c['label'][1:]).isnumeric():
                c['label'] = config.get_localized_string(int(c['label'][1:]))
            if c['type'] == 'list':
                lvalues = []
                for li in c['lvalues']:
                    if li.startswith('@') and unicode(li[1:]).isnumeric():
                        lvalues.append(config.get_localized_string(int(li[1:])))
                    else:
                        lvalues.append(li)
                c['lvalues'] = lvalues

            # Valores por defecto en caso de que el control no disponga de ellos
            if c["type"] == "bool" and "default" not in c:
                c["default"] = False
            if c["type"] == "text" and "default" not in c:
                c["default"] = ""
            if c["type"] == "text" and "hidden" not in c:
                c["hidden"] = False
            if c["type"] == "list" and "default" not in c:
                c["default"] = 0
            if c["type"] == "label" and "id" not in c:
                c["id"] = None
            if "color" not in c:
                c["color"] = "0xFF0066CC"
            if "visible" not in c:
                c["visible"] = True
            if "enabled" not in c:
                c["enabled"] = True

                
            if c["type"] == "text" and not type(c["hidden"]) == bool:
                if c["hidden"].lower() == 'true':
                    c["hidden"] = True
                else:
                    c["hidden"] = False

            # Decidimos si usar el valor por defecto o el valor guardado
            if c["type"] in ["bool", "text", "list"]:
                if id not in self.values:
                    if not self.callback:
                        self.values[c["id"]] = config.get_setting(c["id"], self.channel)
                    else:
                        self.values[c["id"]] = c["default"]

            if c["type"] == "bool":
                c["default"] = bool(c["default"])
                self.values[c["id"]] = bool(self.values[c["id"]])

            
            if c["type"] == "bool":
                self.add_control_bool(c)
                
            elif c["type"] == 'text':
                self.add_control_text(c)
                
            elif c["type"] == 'list':
                self.add_control_list(c)
                
            elif c["type"] == 'label':
                self.add_control_label(c)

        self.list_controls = [c for c in self.list_controls if "control" in c]
        
        self.evaluate_conditions()
        self.index = -1
        self.dispose_controls(0)
        self.getControl(100010).setVisible(False)
        self.getControl(10004).setEnabled(True)
        self.getControl(10005).setEnabled(True)
        self.getControl(10006).setEnabled(True)
        self.ok_enabled = True
        self.default_enabled = True
        self.check_default()
        self.check_ok(self.values)
Exemple #7
0
def resolve_video_urls_for_playing(server,url,video_password="",muestra_dialogo=False,encode=False):
    if not encode:
        logger.info("deportesalacarta.core.servertools resolve_video_urls_for_playing, server="+server+", url="+url)
    video_urls = []
    torrent = False
        
    server = server.lower()

    # Si el vídeo es "directo", no hay que buscar más
    if server=="directo" or server=="local":
        logger.info("deportesalacarta.core.servertools server=directo, la url es la buena")

        try:
            import urlparse
            parsed_url = urlparse.urlparse(url)
            logger.info("parsed_url="+str(parsed_url))
            extension = parsed_url.path[-4:]
        except:
            extension = url[-4:]

        video_urls = [[ "%s [%s]" % (extension,server) , url ]]
        return video_urls,True,""

    # Averigua las URL de los vídeos
    else:

        # Carga el conector
        try:
            if encode: 
                return [base64.b64decode(url)], True, ""
            # Muestra un diágo de progreso
            if muestra_dialogo:
                from platformcode import platformtools
                progreso = platformtools.dialog_progress( "pelisalacarta" , "Conectando con "+server)
            server_parameters = get_server_parameters(server)

            #Cuenta las opciones disponibles, para calcular el porcentaje
            opciones = []
            if server_parameters["free"] == "true":
              opciones.append("free")
            opciones.extend([premium for premium in server_parameters["premium"] if config.get_setting(premium+"premium")=="true"])
            logger.info("deportesalacarta.core.servertools opciones disponibles para " + server + ": " + str(len(opciones)) + " "+str(opciones))

            # Sustituye el código por otro "Plex compatible"
            #exec "from servers import "+server+" as server_connector"
            servers_module = __import__("servers."+server)
            server_connector = getattr(servers_module,server)
            if not encode:
                logger.info("deportesalacarta.core.servertools servidor de "+server+" importado")

            # Si tiene una función para ver si el vídeo existe, lo comprueba ahora
            if hasattr(server_connector, 'test_video_exists'):
                logger.info("deportesalacarta.core.servertools invocando a "+server+".test_video_exists")
                puedes,motivo = server_connector.test_video_exists( page_url=url )

                # Si la funcion dice que no existe, fin
                if not puedes:
                    logger.info("deportesalacarta.core.servertools test_video_exists dice que el video no existe")
                    if muestra_dialogo: progreso.close()
                    return video_urls,puedes,motivo
                else:
                    logger.info("deportesalacarta.core.servertools test_video_exists dice que el video SI existe")

            # Obtiene enlaces free
            if server_parameters["free"]=="true":
                if muestra_dialogo:
                  progreso.update((100 / len(opciones)) * opciones.index("free")  , "Conectando con "+server)
                logger.info("deportesalacarta.core.servertools invocando a "+server+".get_video_url")
                video_urls = server_connector.get_video_url( page_url=url , video_password=video_password )

                # Si no se encuentran vídeos en modo free, es porque el vídeo no existe
                if len(video_urls)==0:
                    if muestra_dialogo: progreso.close()
                    return video_urls,False,"No se puede encontrar el vídeo en "+server

            # Obtiene enlaces para las diferentes opciones premium
            error_message = []
            for premium in server_parameters["premium"]:
              if config.get_setting(premium+"premium")=="true":
                if muestra_dialogo:
                  progreso.update((100 / len(opciones)) * opciones.index(premium)  , "Conectando con "+premium)
                exec "from servers import "+premium+" as premium_conector"
                if premium == "realdebrid":
                    debrid_urls = premium_conector.get_video_url( page_url=url , premium=True , video_password=video_password )
                    if not "REAL-DEBRID:" in debrid_urls[0][0]:
                        video_urls.extend(debrid_urls)
                    else:
                        error_message.append(debrid_urls[0][0])
                elif premium == "alldebrid":
                    alldebrid_urls = premium_conector.get_video_url( page_url=url , premium=True , user=config.get_setting(premium+"user") , password=config.get_setting(premium+"password"), video_password=video_password )
                    if not "Alldebrid:" in alldebrid_urls[0][0]:
                        video_urls.extend(alldebrid_urls)
                    else:
                        error_message.append(alldebrid_urls[0][0])
                else:
                    video_urls.extend(premium_conector.get_video_url( page_url=url , premium=True , user=config.get_setting(premium+"user") , password=config.get_setting(premium+"password"), video_password=video_password ))

            if not video_urls and error_message:
                return video_urls, False, " || ".join(error_message)

            if muestra_dialogo:
                progreso.update( 100 , "Proceso finalizado")

            # Cierra el diálogo de progreso
            if muestra_dialogo: progreso.close()

            # Llegas hasta aquí y no tienes ningún enlace para ver, así que no vas a poder ver el vídeo
            if len(video_urls)==0:
                # ¿Cual es el motivo?

                # 1) No existe -> Ya está controlado
                # 2) No tienes alguna de las cuentas premium compatibles

                # Lista de las cuentas que soportan este servidor
                listapremium = []
                for premium in server_parameters["premium"]:
                  listapremium.append(get_server_parameters(premium)["name"])

                return video_urls,False,"Para ver un vídeo en "+server+" necesitas<br/>una cuenta en "+" o ".join(listapremium)

        except:
            if muestra_dialogo: progreso.close()
            import traceback
            logger.info(traceback.format_exc())
            return video_urls,False,"Se ha producido un error en<br/>el conector con "+server

    return video_urls,True,""
Exemple #8
0
def render_items(itemlist, parent_item):
    """
    Función encargada de mostrar el itemlist en kodi, se pasa como parametros el itemlist y el item del que procede
    @type itemlist: list
    @param itemlist: lista de elementos a mostrar

    @type parent_item: item
    @param parent_item: elemento padre
    """
    # Si el itemlist no es un list salimos
    if not type(itemlist) == list:
        if config.get_platform() == "boxee":
            xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=True)
        return

    # Si no hay ningun item, mostramos un aviso
    if not len(itemlist):
        itemlist.append(Item(title="There are no items to show"))

    # Recorremos el itemlist
    for item in itemlist:

        # Si el item no contiene categoria,le ponemos la del item padre
        if item.category == "":
            item.category = parent_item.category

        # Si el item no contiene fanart,le ponemos la del item padre
        if item.fanart == "":
            item.fanart = parent_item.fanart

        # Formatear titulo
        if item.text_color:
            item.title = '[COLOR %s]%s[/COLOR]' % (item.text_color, item.title)
        if item.text_blod:
            item.title = '[B]%s[/B]' % item.title
        if item.text_italic:
            item.title = '[I]%s[/I]' % item.title

        # IconImage para folder y video
        if item.folder:
            icon_image = "DefaultFolder.png"
        else:
            icon_image = "DefaultVideo.png"

        # Creamos el listitem
        listitem = xbmcgui.ListItem(item.title,
                                    iconImage=icon_image,
                                    thumbnailImage=item.thumbnail)

        # Ponemos el fanart
        if item.fanart:
            listitem.setProperty('fanart_image', item.fanart)
        else:
            listitem.setProperty(
                'fanart_image',
                os.path.join(config.get_runtime_path(), "fanart.jpg"))

        # TODO: ¿Se puede eliminar esta linea? yo no he visto que haga ningun efecto.
        xbmcplugin.setPluginFanart(
            int(sys.argv[1]),
            os.path.join(config.get_runtime_path(), "fanart.jpg"))

        # Añadimos los infoLabels
        set_infolabels(listitem, item)

        # Montamos el menu contextual
        context_commands = set_context_commands(item, parent_item)

        # Añadimos el item
        if config.get_platform() == "boxee":
            xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),
                                        url='%s?%s' %
                                        (sys.argv[0], item.tourl()),
                                        listitem=listitem,
                                        isFolder=item.folder)
        else:
            listitem.addContextMenuItems(context_commands, replaceItems=True)

            if not item.totalItems: item.totalItems = 0
            xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),
                                        url='%s?%s' %
                                        (sys.argv[0], item.tourl()),
                                        listitem=listitem,
                                        isFolder=item.folder,
                                        totalItems=item.totalItems)

    # Vista 5x3 hasta llegar al listado de canales
    if parent_item.channel not in ["channelselector", ""]:
        xbmcplugin.setContent(int(sys.argv[1]), "movies")

    # Fijamos el "breadcrumb"
    xbmcplugin.setPluginCategory(handle=int(sys.argv[1]),
                                 category=parent_item.category.capitalize())

    # No ordenar items
    xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                             sortMethod=xbmcplugin.SORT_METHOD_NONE)

    # Viewmodes:
    # Creo que es mas lógico que al item se le especifique que vista tendra al abrirlo.
    # El cambio puede provocar que algun canal no muestre los items en la vista deseada, pero es mejor ir corrigiendolo
    # que arrastrar algo que no tiene sentido
    if config.get_setting("forceview") == "true":
        if parent_item.viewmode == "list":
            xbmc.executebuiltin("Container.SetViewMode(50)")
        elif parent_item.viewmode == "movie_with_plot":
            xbmc.executebuiltin("Container.SetViewMode(503)")
        elif parent_item.viewmode == "movie":
            xbmc.executebuiltin("Container.SetViewMode(500)")

    # Cerramos el directorio
    xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=True)
Exemple #9
0
def play_torrent(item, xlistitem, mediaurl):
    logger.info("platformtools play_torrent")
    # Opciones disponibles para Reproducir torrents
    torrent_options = list()
    torrent_options.append(["Cliente interno (necesario libtorrent)"])
    torrent_options.append(["Cliente interno MCT (necesario libtorrent)"])

    # Plugins externos se pueden añadir otros
    if xbmc.getCondVisibility('System.HasAddon("plugin.video.xbmctorrent")'):
        torrent_options.append([
            "Plugin externo: xbmctorrent",
            "plugin://plugin.video.xbmctorrent/play/%s"
        ])
    if xbmc.getCondVisibility('System.HasAddon("plugin.video.pulsar")'):
        torrent_options.append([
            "Plugin externo: pulsar",
            "plugin://plugin.video.pulsar/play?uri=%s"
        ])
    if xbmc.getCondVisibility('System.HasAddon("plugin.video.quasar")'):
        torrent_options.append([
            "Plugin externo: quasar",
            "plugin://plugin.video.quasar/play?uri=%s"
        ])
    if xbmc.getCondVisibility('System.HasAddon("plugin.video.stream")'):
        torrent_options.append(
            ["Plugin externo: stream", "plugin://plugin.video.stream/play/%s"])
    if xbmc.getCondVisibility('System.HasAddon("plugin.video.torrenter")'):
        torrent_options.append([
            "Plugin externo: torrenter",
            "plugin://plugin.video.torrenter/?action=playSTRM&url=%s"
        ])
    if xbmc.getCondVisibility('System.HasAddon("plugin.video.torrentin")'):
        torrent_options.append([
            "Plugin externo: torrentin",
            "plugin://plugin.video.torrentin/?uri=%s&image="
        ])

    if len(torrent_options) > 1:
        seleccion = dialog_select("Abrir torrent con...",
                                  [opcion[0] for opcion in torrent_options])
    else:
        seleccion = 0

    # Plugins externos
    if seleccion > 1:
        mediaurl = urllib.quote_plus(item.url)
        xbmc.executebuiltin("PlayMedia(" +
                            torrent_options[seleccion][1] % mediaurl + ")")

    if seleccion == 1:
        from platformcode import mct
        mct.play(mediaurl, xlistitem, subtitle=item.subtitle)

    # Reproductor propio (libtorrent)
    if seleccion == 0:
        import time
        played = False
        debug = (config.get_setting("debug") == "true")

        # Importamos el cliente
        from btserver import Client

        # Iniciamos el cliente:
        c = Client(url=mediaurl,
                   is_playing_fnc=xbmc.Player().isPlaying,
                   wait_time=None,
                   timeout=10,
                   temp_path=os.path.join(config.get_data_path(), "torrent"),
                   print_status=debug)

        # Mostramos el progreso
        progreso = dialog_progress("Pelisalacarta - Torrent", "Iniciando...")

        # Mientras el progreso no sea cancelado ni el cliente cerrado
        while not c.closed:
            try:
                # Obtenemos el estado del torrent
                s = c.status
                if debug:
                    # Montamos las tres lineas con la info del torrent
                    txt = '%.2f%% de %.1fMB %s | %.1f kB/s' % \
                          (s.progress_file, s.file_size, s.str_state, s._download_rate)
                    txt2 = 'S: %d(%d) P: %d(%d) | DHT:%s (%d) | Trakers: %d' % \
                           (s.num_seeds, s.num_complete, s.num_peers, s.num_incomplete, s.dht_state, s.dht_nodes,
                            s.trackers)
                    txt3 = 'Origen Peers TRK: %d DHT: %d PEX: %d LSD %d ' % \
                           (s.trk_peers, s.dht_peers, s.pex_peers, s.lsd_peers)
                else:
                    txt = '%.2f%% de %.1fMB %s | %.1f kB/s' % \
                          (s.progress_file, s.file_size, s.str_state, s._download_rate)
                    txt2 = 'S: %d(%d) P: %d(%d)' % (
                        s.num_seeds, s.num_complete, s.num_peers,
                        s.num_incomplete)
                    try:
                        txt3 = 'Deteniendo automaticamente en: %ss' % (int(
                            s.timeout))
                    except:
                        txt3 = ''

                progreso.update(s.buffer, txt, txt2, txt3)
                time.sleep(0.5)

                if progreso.iscanceled():
                    progreso.close()
                    if s.buffer == 100:
                        if dialog_yesno("Pelisalacarta - Torrent",
                                        "¿Deseas iniciar la reproduccion?"):
                            played = False
                            progreso = dialog_progress(
                                "Pelisalacarta - Torrent", "")
                            progreso.update(s.buffer, txt, txt2, txt3)
                        else:
                            progreso = dialog_progress(
                                "Pelisalacarta - Torrent", "")
                            break

                    else:
                        if dialog_yesno("Pelisalacarta - Torrent",
                                        "¿Deseas cancelar el proceso?"):
                            progreso = dialog_progress(
                                "Pelisalacarta - Torrent", "")
                            break

                        else:
                            progreso = dialog_progress(
                                "Pelisalacarta - Torrent", "")
                            progreso.update(s.buffer, txt, txt2, txt3)

                # Si el buffer se ha llenado y la reproduccion no ha sido iniciada, se inicia
                if s.buffer == 100 and not played:
                    # Cerramos el progreso
                    progreso.close()

                    # Obtenemos el playlist del torrent
                    videourl = c.get_play_list()

                    # Iniciamos el reproductor
                    playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
                    playlist.clear()
                    playlist.add(videourl, xlistitem)
                    xbmc_player = xbmc.Player()
                    xbmc_player.play(playlist)

                    # Marcamos como reproducido para que no se vuelva a iniciar
                    played = True

                    # Y esperamos a que el reproductor se cierre
                    while xbmc.Player().isPlaying():
                        time.sleep(1)

                    # Cuando este cerrado,  Volvemos a mostrar el dialogo
                    progreso = dialog_progress("Pelisalacarta - Torrent", "")
                    progreso.update(s.buffer, txt, txt2, txt3)

            except:
                import traceback
                logger.info(traceback.format_exc())
                break

        progreso.update(100, "Terminando y eliminando datos", " ", " ")

        # Detenemos el cliente
        if not c.closed:
            c.stop()

        # Y cerramos el progreso
        progreso.close()
Exemple #10
0
def set_player(item, xlistitem, mediaurl, view, strm, info):
    logger.info("platformtools set_player")
    logger.debug("item:\n" + item.tostring('\n'))

    # Movido del conector "torrent" aqui
    if item.server == "torrent":
        play_torrent(item, xlistitem, mediaurl)
        return

    # Si es un fichero strm no hace falta el play
    elif strm:
        xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, xlistitem)
        if item.subtitle != "":
            xbmc.sleep(2000)
            xbmc.Player().setSubtitles(item.subtitle)

    else:
        logger.info("player_mode=" + config.get_setting("player_mode"))
        logger.info("mediaurl=" + mediaurl)
        if item.server == "p2p" and info:
            from platformcode import windowinfo
            return windowinfo.start(item, xlistitem, mediaurl)
        elif config.get_setting(
                "player_mode") == "3" or "megacrypter.com" in mediaurl:
            import download_and_play
            download_and_play.download_and_play(
                mediaurl, "download_and_play.tmp",
                config.get_setting("downloadpath"))
            return

        elif config.get_setting("player_mode") == "0" or \
                (config.get_setting("player_mode") == "3" and mediaurl.startswith("rtmp")):
            # Añadimos el listitem a una lista de reproducción (playlist)
            playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
            playlist.clear()
            playlist.add(mediaurl, xlistitem)

            # Reproduce
            playersettings = config.get_setting('player_type')
            logger.info(
                "deportesalacarta.platformcode.platformstools playersettings="
                + playersettings)

            if config.get_system_platform() == "xbox":
                player_type = xbmc.PLAYER_CORE_AUTO
                if playersettings == "0":
                    player_type = xbmc.PLAYER_CORE_AUTO
                    logger.info(
                        "deportesalacarta.platformcode.platformstools PLAYER_CORE_AUTO"
                    )
                elif playersettings == "1":
                    player_type = xbmc.PLAYER_CORE_MPLAYER
                    logger.info(
                        "deportesalacarta.platformcode.platformstools PLAYER_CORE_MPLAYER"
                    )
                elif playersettings == "2":
                    player_type = xbmc.PLAYER_CORE_DVDPLAYER
                    logger.info(
                        "deportesalacarta.platformcode.platformstools PLAYER_CORE_DVDPLAYER"
                    )

                xbmc_player = xbmc.Player(player_type)
            else:
                xbmc_player = xbmc.Player()

            xbmc_player.play(playlist, xlistitem)

        elif config.get_setting("player_mode") == "1":
            logger.info("mediaurl :" + mediaurl)
            logger.info("Tras setResolvedUrl")
            xbmcplugin.setResolvedUrl(int(sys.argv[1]), True,
                                      xbmcgui.ListItem(path=mediaurl))

        elif config.get_setting("player_mode") == "2":
            xbmc.executebuiltin("PlayMedia(" + mediaurl + ")")

    # TODO MIRAR DE QUITAR VIEW
    if item.subtitle != "" and view:
        logger.info("Subtítulos externos: " + item.subtitle)
        xbmc.sleep(2000)
        xbmc.Player().setSubtitles(item.subtitle)
Exemple #11
0
def set_opcion(item, seleccion, opciones, video_urls):
    logger.info("platformtools set_opcion")
    # logger.debug(item.tostring('\n'))
    salir = False
    # No ha elegido nada, lo más probable porque haya dado al ESC
    # TODO revisar
    if seleccion == -1:
        # Para evitar el error "Uno o más elementos fallaron" al cancelar la selección desde fichero strm
        listitem = xbmcgui.ListItem(item.title,
                                    iconImage="DefaultVideo.png",
                                    thumbnailImage=item.thumbnail)
        xbmcplugin.setResolvedUrl(int(sys.argv[1]), False, listitem)

    # "Enviar a JDownloader"
    if opciones[seleccion] == config.get_localized_string(30158):
        from core import scrapertools

        # TODO comprobar que devuelve 'data'
        if item.subtitle != "":
            data = scrapertools.cachePage(
                config.get_setting("jdownloader") +
                "/action/add/links/grabber0/start1/web=" + item.url + " " +
                item.thumbnail + " " + item.subtitle)
        else:
            data = scrapertools.cachePage(
                config.get_setting("jdownloader") +
                "/action/add/links/grabber0/start1/web=" + item.url + " " +
                item.thumbnail)
        salir = True

    elif opciones[seleccion] == config.get_localized_string(
            30164):  # Borrar archivo en descargas
        # En "extra" está el nombre del fichero en favoritos
        os.remove(item.url)
        xbmc.executebuiltin("Container.Refresh")
        salir = True

    # Descargar
    elif opciones[seleccion] == config.get_localized_string(
            30153):  # "Descargar"

        download_title = item.fulltitle
        if item.hasContentDetails == "true":
            download_title = item.contentTitle

        # El vídeo de más calidad es el último
        mediaurl = video_urls[len(video_urls) - 1][1]

        from core import downloadtools
        keyboard = xbmc.Keyboard(download_title)
        keyboard.doModal()
        if (keyboard.isConfirmed()):
            download_title = keyboard.getText()
            devuelve = downloadtools.downloadbest(video_urls, download_title)

            if devuelve == 0:
                advertencia = xbmcgui.Dialog()
                resultado = advertencia.ok("plugin", "Descargado con éxito")
            elif devuelve == -1:
                advertencia = xbmcgui.Dialog()
                resultado = advertencia.ok("plugin", "Descarga abortada")
            else:
                advertencia = xbmcgui.Dialog()
                resultado = advertencia.ok("plugin", "Error en la descarga")
        salir = True

    elif opciones[seleccion] == config.get_localized_string(
            30159):  #"Borrar descarga definitivamente"
        from channels import descargas
        descargas.delete_error_bookmark(urllib.unquote_plus(item.extra))

        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(
            config.get_localized_string(30101), item.title,
            config.get_localized_string(30106))  # 'Se ha quitado de la lista'
        xbmc.executebuiltin("Container.Refresh")
        salir = True

    elif opciones[seleccion] == config.get_localized_string(
            30160):  #"Pasar de nuevo a lista de descargas":
        from channels import descargas
        descargas.mover_descarga_error_a_pendiente(
            urllib.unquote_plus(item.extra))

        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(
            config.get_localized_string(30101), item.title,
            config.get_localized_string(
                30107))  # 'Ha pasado de nuevo a la lista de descargas'
        salir = True

    # "Quitar de favoritos"
    elif opciones[seleccion] == config.get_localized_string(30154):
        from channels import favoritos
        favoritos.delFavourite(item)
        salir = True

    # "Añadir a favoritos":
    elif opciones[seleccion] == config.get_localized_string(30155):
        from channels import favoritos
        item.from_channel = "favoritos"
        favoritos.addFavourite(item)
        salir = True

    elif opciones[seleccion] == config.get_localized_string(
            30156):  #"Quitar de lista de descargas":
        # La categoría es el nombre del fichero en la lista de descargas
        from channels import descargas
        descargas.deletebookmark((urllib.unquote_plus(item.extra)))

        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(
            config.get_localized_string(30101), item.title,
            config.get_localized_string(
                30106))  # 'Se ha quitado de lista de descargas'

        xbmc.executebuiltin("Container.Refresh")
        salir = True

    elif opciones[seleccion] == config.get_localized_string(
            30157):  #"Añadir a lista de descargas":
        from core import downloadtools

        download_title = item.fulltitle
        download_thumbnail = item.thumbnail
        download_plot = item.plot

        if item.hasContentDetails == "true":
            download_title = item.contentTitle
            download_thumbnail = item.contentThumbnail
            download_plot = item.contentPlot

        keyboard = xbmc.Keyboard(
            downloadtools.limpia_nombre_excepto_1(download_title))
        keyboard.doModal()
        if keyboard.isConfirmed():
            download_title = keyboard.getText()

            from channels import descargas
            descargas.savebookmark(titulo=download_title,
                                   url=item.url,
                                   thumbnail=download_thumbnail,
                                   server=item.server,
                                   plot=download_plot,
                                   fulltitle=download_title)

            advertencia = xbmcgui.Dialog()
            resultado = advertencia.ok(
                config.get_localized_string(30101), download_title,
                config.get_localized_string(
                    30109))  # 'se ha añadido a la lista de descargas'
        salir = True

    return salir
Exemple #12
0
def get_dialogo_opciones(item, default_action, strm):
    logger.info("platformtools get_dialogo_opciones")
    #logger.debug(item.tostring('\n'))
    from core import servertools

    opciones = []
    error = False

    try:
        item.server = item.server.lower()
    except AttributeError:
        item.server = ""

    if item.server == "":
        item.server = "directo"

    # Si no es el modo normal, no muestra el diálogo porque cuelga XBMC
    muestra_dialogo = (config.get_setting("player_mode") == "0" and not strm)

    # Extrae las URL de los vídeos, y si no puedes verlo te dice el motivo
    #Permitir varias calidades para server "directo"
    if item.video_urls:
        video_urls, puedes, motivo = item.video_urls, True, ""
    else:
        video_urls, puedes, motivo = servertools.resolve_video_urls_for_playing(
            item.server, item.url, item.password, muestra_dialogo)

    seleccion = 0
    # Si puedes ver el vídeo, presenta las opciones
    if puedes:
        for video_url in video_urls:
            opciones.append(
                config.get_localized_string(30151) + " " + video_url[0])

        if item.server == "local":
            opciones.append(config.get_localized_string(30164))
        else:
            opcion = config.get_localized_string(30153)
            opciones.append(opcion)  # "Descargar"

            if item.channel == "favoritos":
                opciones.append(config.get_localized_string(
                    30154))  # "Quitar de favoritos"
            else:
                opciones.append(
                    config.get_localized_string(30155))  # "Añadir a favoritos"

            if item.channel != "descargas":
                opciones.append(config.get_localized_string(30157))
            else:
                if item.category == "errores":
                    opciones.append(config.get_localized_string(
                        30159))  # "Borrar descarga definitivamente"
                    opciones.append(config.get_localized_string(
                        30160))  # "Pasar de nuevo a lista de descargas"
                else:
                    opciones.append(config.get_localized_string(
                        30156))  # "Quitar de lista de descargas"

            if config.get_setting("jdownloader_enabled") == "true":
                # "Enviar a JDownloader"
                opciones.append(config.get_localized_string(30158))

        if default_action == "3":
            seleccion = len(opciones) - 1

    # Si no puedes ver el vídeo te informa
    else:
        if item.server != "":
            if "<br/>" in motivo:
                dialog_ok("No puedes ver ese vídeo porque...",
                          motivo.split("<br/>")[0],
                          motivo.split("<br/>")[1], item.url)
            else:
                dialog_ok("No puedes ver ese vídeo porque...", motivo,
                          item.url)
        else:
            dialog_ok("No puedes ver ese vídeo porque...",
                      "El servidor donde está alojado no está",
                      "soportado en pelisalacarta todavía", item.url)

        if item.channel == "favoritos":
            opciones.append(
                config.get_localized_string(30154))  # "Quitar de favoritos"

        if len(opciones) == 0:
            error = True

    return opciones, video_urls, seleccion, error
Exemple #13
0
# version 2.0
# ------------------------------------------------------------

import re
import os
import sys
import urllib

import xbmc
import xbmcgui
import xbmcplugin
from resources.lib.httpkir import config
from resources.lib.httpkir import logger
from resources.lib.httpkir.item import Item

DEBUG = config.get_setting("debug")


def dialog_ok(heading, line1, line2="", line3=""):
    dialog = xbmcgui.Dialog()
    return dialog.ok(heading, line1, line2, line3)


def dialog_notification(heading, message, icon=0, time=5000, sound=True):
    dialog = xbmcgui.Dialog()
    l_icono = xbmcgui.NOTIFICATION_INFO, xbmcgui.NOTIFICATION_WARNING, xbmcgui.NOTIFICATION_ERROR
    dialog.notification(heading, message, l_icono[icon], time, sound)


def dialog_yesno(heading,
                 line1,