Exemple #1
0
def canal2(item):
    logger.info()
    #url_source = "http://visionperuanatv.com/2013/03/frecuencia-latina-en-vivo.html"
    url_source = "http://www.fulltelevisionhd.net/2013/02/frecuencia-latina-en-vivo-por-internet.html"
    #item.url = server_pxstream("http://canalesenvivo.ucoz.com/Frecuencia_Latina.html")
    item.url = server_playerfs("http://fulltvhd.fi/peru/latina.php")
    platformtools.play_video(item)
Exemple #2
0
def canal5_2(item):
    logger.info()
    data = httptools.downloadpage("https://panamericana.pe/tvenvivo/sd").data
    item.url = scrapertools.find_single_match(
        data, '<iframe frameborder.*?src="([^"]+)')
    item.server = "dailymotion"
    platformtools.play_video(item)
Exemple #3
0
def canalfoxsport3(item):
    logger.info()
    url_source = "http://latino-webtv.com/Fox-Sports-3-en-vivo/"
    item.url = provider_lw(
        "http://embed.latino-webtv.com/channels/Fox-Sports-3.html",
        res=item.res)
    platformtools.play_video(item)
Exemple #4
0
def play_from_library(item):
    """
        Los .strm al reproducirlos desde kodi, este espera que sea un archivo "reproducible" asi que no puede contener
        más items, como mucho se puede colocar un dialogo de seleccion.
        Esto lo solucionamos "engañando a kodi" y haciendole creer que se ha reproducido algo, asi despues mediante
        "Container.Update()" cargamos el strm como si un item desde dentro de pelisalacarta se tratara, quitando todas
        las limitaciones y permitiendo reproducir mediante la funcion general sin tener que crear nuevos métodos para
        la biblioteca.
        @type item: item
        @param item: elemento con información
    """
    logger.info("pelisalacarta.platformcode.launcher play_from_library")
    # logger.debug("item: \n" + item.tostring('\n'))

    import xbmcgui
    import xbmcplugin
    import xbmc
    # Intentamos reproducir una imagen (esto no hace nada y ademas no da error)
    xbmcplugin.setResolvedUrl(int(sys.argv[1]), True,
                              xbmcgui.ListItem(path=os.path.join(config.get_runtime_path(), "icon.png")))

    # Por si acaso la imagen hiciera (en futuras versiones) le damos a stop para detener la reproduccion
    xbmc.Player().stop()

    # modificamos el action (actualmente la biblioteca necesita "findvideos" ya que es donde se buscan las fuentes
    item.action = "findvideos"

    # y volvemos a lanzar kodi
    if xbmc.getCondVisibility('Window.IsMedia'):
        xbmc.executebuiltin("Container.Update(" + sys.argv[0] + "?" + item.tourl() + ")")

    else:
        from channels import biblioteca
        from platformcode import xbmc_library
        p_dialog = platformtools.dialog_progress_bg('pelisalacarta', 'Cargando...')
        p_dialog.update(0, '')

        itemlist = biblioteca.findvideos(item)

        p_dialog.update(50, '')

        if len(itemlist) > 0:
            # El usuario elige el mirror
            opciones = []
            for item in itemlist:
                opciones.append(item.title)

            seleccion = platformtools.dialog_select(config.get_localized_string(30163), opciones)
            if seleccion == -1:
                return

            item =  biblioteca.play(itemlist[seleccion])[0]
            p_dialog.update(100, '')

            platformtools.play_video(item)
            p_dialog.close()
            xbmc_library.mark_auto_as_watched(itemlist[seleccion])
def play_from_library(item):
    """
        Los .strm al reproducirlos desde kodi, este espera que sea un archivo "reproducible" asi que no puede contener
        más items, como mucho se puede colocar un dialogo de seleccion.
        Esto lo solucionamos "engañando a kodi" y haciendole creer que se ha reproducido algo, asi despues mediante
        "Container.Update()" cargamos el strm como si un item desde dentro de pelisalacarta se tratara, quitando todas
        las limitaciones y permitiendo reproducir mediante la funcion general sin tener que crear nuevos métodos para
        la biblioteca.
        @type item: item
        @param item: elemento con información
    """
    logger.info("streamondemand.platformcode.launcher play_from_library")
    # logger.debug("item: \n" + item.tostring('\n'))

    import xbmcgui
    import xbmcplugin
    import xbmc
    # Intentamos reproducir una imagen (esto no hace nada y ademas no da error)
    xbmcplugin.setResolvedUrl(int(sys.argv[1]), True,
                              xbmcgui.ListItem(path=os.path.join(config.get_runtime_path(), "icon.png")))

    # Por si acaso la imagen hiciera (en futuras versiones) le damos a stop para detener la reproduccion
    xbmc.Player().stop()

    # modificamos el action (actualmente la biblioteca necesita "findvideos" ya que es donde se buscan las fuentes
    item.action = "findvideos"

    # y volvemos a lanzar kodi
    if xbmc.getCondVisibility('Window.IsMedia'):
        xbmc.executebuiltin("Container.Update(" + sys.argv[0] + "?" + item.tourl() + ")")

    else:
        from channels import biblioteca
        from platformcode import xbmc_library
        p_dialog = platformtools.dialog_progress_bg('streamondemand', 'Caricamento in corso...')
        p_dialog.update(0, '')

        itemlist = biblioteca.findvideos(item)

        p_dialog.update(50, '')

        if len(itemlist) > 0:
            # El usuario elige el mirror
            opciones = []
            for item in itemlist:
                opciones.append(item.title)

            seleccion = platformtools.dialog_select(config.get_localized_string(30163), opciones)
            if seleccion == -1:
                return

            item = biblioteca.play(itemlist[seleccion])[0]
            p_dialog.update(100, '')

            platformtools.play_video(item)
            p_dialog.close()
            xbmc_library.mark_auto_as_watched(itemlist[seleccion])
Exemple #6
0
def canal4(item):
    logger.info()
    #url_source = "http://visionperuanatv.com/2013/03/frecuencia-latina-en-vivo.html"
    # item.url = server_playerfs("http://tvenvivo.online/americatreve.php")
    # if not item.url:
    # item.url = server_pxstream("http://tvenvivo.online/americatreve.php")
    url_source = "http://www.fulltelevisionhd.li/america-television-en-vivo-por-internet/"
    item.url = server_playerfs("http://www.fulltvhd.fi/peru/america.php")
    platformtools.play_video(item)
Exemple #7
0
def canal9(item):
    logger.info()
    url_channel = "http://tele-on.com/atv_en_vivo.html"
    data = httptools.downloadpage(url_channel).data
    item.url = scrapertools.find_single_match(data, '<video id="player".*?src="([^"]+)"')
    referer = scrapertools.find_single_match(data, '<iframe f.*?src="([^"]+)"')
    host = scrapertoolsV2.get_domain_from_url(item.url)
    item.url += "|Referer=%s" %referer
    item.url += "&Host=%s" %host
    platformtools.play_video(item)
Exemple #8
0
 def onClick(self, control_id):
     setFocus(self)
     if control_id in [TRAILERS]:
         selected = self.getControl(TRAILERS).getSelectedItem()
         platformtools.play_video(Item(title=selected.getProperty('title'), action='play', url=selected.getProperty('url'), server='youtube'))
         while not xbmc.Player().isPlaying():
             xbmc.sleep(100)
         self.close()
         while xbmc.Player().isPlaying():
             xbmc.sleep(100)
         modal()
Exemple #9
0
def canala9(item):
    logger.info()
    url_channel = "http://www.televisionparatodos.tv/canal-9-player/"
    data = httptools.downloadpage(url_channel).data
    item.url = scrapertools.find_single_match(data, '<iframe id=.*?src="([^"]+)')
    data = httptools.downloadpage(item.url).data
    item.url = scrapertools.find_single_match(data, "file: '([^']+)")
    referer = item.url
    host = scrapertoolsV2.get_domain_from_url(item.url)
    item.url += "|Referer=%s" %referer
    item.url += "&Host=%s" %host
    platformtools.play_video(item)
Exemple #10
0
def canala1(item):
    logger.info()
    url_channel = "http://television-internet.com.ar/america-tv.html"
    data = httptools.downloadpage(url_channel).data
    url_stream = scrapertools.find_single_match(data, '<iframe id.*?src="([^"]+)')
    data = httptools.downloadpage(url_stream).data
    url_stream = scrapertools.find_single_match(data, '<iframe src="([^"]+)')
    data = httptools.downloadpage(url_stream).data
    encode = scrapertools.find_single_match(data, 'atob\("([^"]+)"')
    decode = base64.b64decode(encode)
    item.url = scrapertools.find_single_match(decode, 'appPlaylist":"([^"]+)"')
    item.url += "|Referer=%s" %url_stream
    platformtools.play_video(item)
Exemple #11
0
def play_item(item):
    plugintools.log("navigation.play_item Channel code (" + item.channel +
                    "." + item.action + ")")

    try:
        exec "import channels." + item.channel + " as channel"
    except:
        exec "import core." + item.channel + " as channel"

    from platformcode import platformtools

    plugintools.log("navigation.get_next_items play")

    # Si el canal tiene una acción "play" tiene prioridad
    if hasattr(channel, 'play'):
        plugintools.log(
            "navigation.get_next_items play Channel has its own 'play' method")
        itemlist = channel.play(item)
        if len(itemlist) > 0:
            item = itemlist[0]
            plugintools.log("item=" + repr(item))

            try:
                platformtools.play_video(item)
            except:
                import traceback
                plugintools.log(traceback.format_exc())
                import xbmcgui
                ventana_error = xbmcgui.Dialog()
                ok = ventana_error.ok("plugin", "No hay nada para reproducir")

        else:
            import xbmcgui
            ventana_error = xbmcgui.Dialog()
            ok = ventana_error.ok("plugin", "No hay nada para reproducir")
    else:
        plugintools.log(
            "navigation.get_next_items play No channel 'play' method, executing core method"
        )

        # FIXME: Este error ha que tratarlo de otra manera, por al dar a volver sin ver el vídeo falla
        # Mejor hacer el play desde la ventana
        try:
            platformtools.play_video(item)
        except:
            import traceback
            plugintools.log(traceback.format_exc())
            import xbmcgui
            ventana_error = xbmcgui.Dialog()
            ok = ventana_error.ok("plugin", "No hay nada para reproducir")
Exemple #12
0
 def onClick(self, control_id):
     setFocus(self)
     if control_id == COMMANDS:
         from platformcode.launcher import run
         pos = self.getControl(COMMANDS).getSelectedPosition()
         if self.commands[pos].action == 'save_download' and self.commands[
                 pos].contentType == 'tvshow':
             actions = [
                 self.commands[-1].clone(),
                 self.commands[-1].clone(download='season')
             ]
             options = [
                 config.get_localized_string(60355),
                 config.get_localized_string(60357)
             ]
             run(actions[platformtools.dialog_select(
                 config.get_localized_string(60498), options)])
         else:
             run(self.commands[pos])
     else:
         action = self.getControl(RECOMANDED).getSelectedItem().getProperty(
             'action')
         channel = self.getControl(
             RECOMANDED).getSelectedItem().getProperty('channel')
         url = self.getControl(RECOMANDED).getSelectedItem().getProperty(
             'url')
         item = Item(channel=channel, action=action, url=url)
         if action == 'play':
             item.server = self.getControl(
                 RECOMANDED).getSelectedItem().getProperty('server')
             self.close()
             platformtools.play_video(item)
             xbmc.sleep(500)
             while xbmc.Player().isPlaying():
                 xbmc.sleep(500)
             modal()
         elif config.get_setting('autoplay'):
             item.quality = self.getControl(
                 RECOMANDED).getSelectedItem().getProperty('quality')
             getattr(self.channel, item.action)(item)
             self.close()
             xbmc.sleep(500)
             while xbmc.Player().isPlaying():
                 xbmc.sleep(500)
             modal()
         else:
             pos = self.getControl(RECOMANDED).getSelectedPosition()
             self.close()
             if self.itemlist[pos].mode: remove()
             Search(self.itemlist[pos])
Exemple #13
0
def p2p(item):
    if "Sopcast" in item.title:
        texto = dialog_input(default='sop://broker.sopcast.com:3912/', heading="Introduce la url de sopcast")
        titulo = "[Sopcast]"
    else:
        texto = dialog_input(default='acestream://', heading="Introduce la url de acestream")
        titulo = "[Acestream]"
    if texto != "":
        url = texto + "|" + titulo
        from platformcode import platformtools
        item_play = item.clone()
        item_play.url = url
        item_play.server = "p2p"
        platformtools.play_video(item_play)
Exemple #14
0
def halfplayer(item):
    support.log()

    url = item.url

    # Correggo il link con il lin del POST
    url = url.replace("/v/", "/api/source/").replace("/p/", "/api/source/")

    postData = urllib.urlencode({
        "r": "",
        "d": "modolunatico.tk",
    })

    block = httptools.downloadpage(url, post=postData).data

    patron = r'"file":".*?\/(r[^"]+)'
    matches = re.compile(patron, re.DOTALL).findall(block)

    for scrapedurl in matches:
        item.url = "https://fvs.io/" + scrapedurl
        item.server = ""
        itemlist = platformtools.play_video(item,
                                            force_direct=True,
                                            autoplay=True)

        return itemlist
Exemple #15
0
def menu(item):
    logger.info()

    # Opciones disponibles para el menu
    op = ["Descargar", "Eliminar de la lista", "Reiniciar descarga", "Descargar desde...", "Reproducir"]

    opciones = []

    # Opciones para el menu
    if item.downloadStatus == 0:  # Sin descargar
        opciones.append(op[0])  # Descargar
        opciones.append(op[3])  # Descargar desde...
        opciones.append(op[1])  # Eliminar de la lista

    if item.downloadStatus == 1:  # descarga parcial
        opciones.append(op[0])  # Descargar
        opciones.append(op[2])  # Reiniciar descarga
        opciones.append(op[1])  # Eliminar de la lista

    if item.downloadStatus == 2:  # descarga completada
        opciones.append(op[4])  # Reproducir
        opciones.append(op[1])  # Eliminar de la lista
        opciones.append(op[2])  # Reiniciar descarga

    if item.downloadStatus == 3:  # descarga con error
        opciones.append(op[2])  # Reiniciar descarga
        opciones.append(op[1])  # Eliminar de la lista

    # Mostramos el dialogo
    seleccion = platformtools.dialog_select("Scegliere un'opzione", opciones)

    # -1 es cancelar
    if seleccion == -1: return

    logger.info("opcion=%s" % (opciones[seleccion]))
    # Opcion Eliminar
    if opciones[seleccion] == op[1]:
        filetools.remove(item.path)

    # Opcion inicaiar descarga
    if opciones[seleccion] == op[0]:
        start_download(item)

    # Opcion inicaiar descarga desde...
    if opciones[seleccion] == op[3]:
        start_download(item, ask=True)

    # Reiniciar descarga
    if opciones[seleccion] == op[2]:
        if filetools.isfile(os.path.join(config.get_setting("downloadpath"), item.downloadFilename)):
            filetools.remove(os.path.join(config.get_setting("downloadpath"), item.downloadFilename))

        update_json(item.path, {"downloadStatus": STATUS_CODES.stoped, "downloadComplete": 0, "downloadProgress": 0})

    # Reproducir
    if opciones[seleccion] == op[4]:
        item.url = filetools.join(DOWNLOAD_PATH, item.downloadFilename)
        return platformtools.play_video(item)

    platformtools.itemlist_refresh()
Exemple #16
0
def canaltoros2(item):
    logger.info()
    url_source = "http://latelete.tv/canal-plus-toros-en-directo-gratis-por-internet/"
    url_channel = "http://verdirectotv.com/tv/digitales2/plustoros.html"
    data = httptools.downloadpage(url_channel).data
    url = scrapertools.find_single_match(data, '<iframe scrolling.*?src="([^"]+)')
    headers = [
    ["Referer", url_channel],
    ["host", scrapertoolsV2.get_domain_from_url(url)],
    ]
    data = httptools.downloadpage(url, headers = headers).data
    url = scrapertools.find_single_match(data, "source: '([^']+)")
    host = scrapertoolsV2.get_domain_from_url(url)
    item.url  = url + "|Referer=%s" %url
    item.url += "&Host=%s" %host
    item.url += "&User-Agent=%s" %_useragent
    platformtools.play_video(item)
Exemple #17
0
def canalhistory2(item):
    logger.info()
    url_source = "http://www.tutv-gratis.com"
    url_channel = "http://www.tv-en-vivo.org/history/"
    data = httptools.downloadpage(url_channel).data
    url = scrapertools.find_single_match(data, 'source: "([^"]+)"')
    host = scrapertoolsV2.get_domain_from_url(url)
    if item.HD == True:
        quality = '05'
    else:
        quality = '02'
    url = url.replace("index.m3u8", "Stream(%s)/index.m3u8" % quality)
    item.url = url + "|Referer=%s" % url
    item.url += "&Host=%s" % host
    item.url += "&User-Agent=%s" % _useragent
    headers = [["Referer", url], ["Host", host]]
    platformtools.play_video(item)
    def onAction(self, action):
        if action.getId(
        ) == ACTION_SELECT_ITEM and not controlId() == OPTIONS_OK:
            xbmc.executebuiltin('xbmc.PlayMedia(Stop)')
            self.list = self.getControl(6)
            selecitem = self.list.getSelectedItem()
            url = selecitem.getProperty("url")
            data = scrapertools.cache_page(url)
            url = servertools.findvideosbyserver(data, "p2p")
            if url:
                url = url[0][1]
            #Creamos el item para platformtools
            item = Item()
            item.fulltitle = self.fulltitle
            item.url = url + "|" + item.fulltitle
            item.server = "p2p"
            self.close()
            check_skin = xbmc.getSkinDir()

            if not "confluence" in check_skin:
                xbmc.sleep(300)
                xbmc.executebuiltin('Action(PreviousMenu)')
                xbmc.sleep(300)

            platformtools.play_video(item)
            self.close()
            check_skin = xbmc.getSkinDir()

            if "confluence" in check_skin:
                if xbmc.Player().isPlayingVideo():
                    #xbmc.sleep(300)
                    xbmc.executebuiltin('Action(PreviousMenu)')
                else:
                    xbmc.executebuiltin('Action(PreviousMenu)')
            else:
                xbmc.executebuiltin('Action(PreviousMenu)')
        elif action.getId() == ACTION_PREVIOUS_MENU or action.getId(
        ) == ACTION_MOUSE_RIGHT_CLICK or action == 92:

            self.close()
            xbmc.sleep(300)
            xbmc.executebuiltin('Action(PreviousMenu)')
    def onClick(self, controlId):
        if controlId == OPTION_PANEL:
            xbmc.executebuiltin('xbmc.PlayMedia(Stop)')
            self.list = self.getControl(6)
            selecitem = self.list.getSelectedItem()
            url = selecitem.getProperty("url")
            data = scrapertools.cache_page(url)
            url = servertools.findvideosbyserver(data, "p2p")
            if url:
                url = url[0][1]
            #Creamos el item para platformtools
            item = Item()
            item.fulltitle = self.fulltitle
            item.url = url + "|" + item.fulltitle
            item.server = "p2p"
            self.close()
            check_skin = xbmc.getSkinDir()

            if not "confluence" in check_skin:
                xbmc.sleep(300)
                xbmc.executebuiltin('Action(PreviousMenu)')
                xbmc.sleep(300)

            platformtools.play_video(item)
            check_skin = xbmc.getSkinDir()

            if "confluence" in check_skin:
                if xbmc.Player().isPlayingVideo():
                    #xbmc.sleep(300)
                    xbmc.executebuiltin('Action(PreviousMenu)')
                else:
                    xbmc.executebuiltin('Action(PreviousMenu)')
            else:
                xbmc.executebuiltin('Action(PreviousMenu)')

        elif controlId == OPTIONS_OK:
            self.close()
            TESTPYDESTFILE = xbmc.translatePath(
                'special://skin/720p/DialogSelect2.xml')
            xbmc.sleep(300)
            xbmc.executebuiltin('Action(PreviousMenu)')
Exemple #20
0
def play(item):
    channel = importChannel(item)

    # define info for trakt
    try:
        from core import trakt_tools
        trakt_tools.set_trakt_info(item)
    except:
        pass
    logger.debug('item.action=', item.action.upper())

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

        # Allow several qualities from Play in 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)
Exemple #21
0
        def onAction(self, action):
            global window_select, result
            if action == 92 or action == 110:
                self.result = "no_video"
                result = "no_video"
                self.close()
                window_select.pop()
                if not window_select:
                    if not self.item.windowed:
                        del window_select
                else:
                    window_select[-1].doModal()

            try:
                if (action == 7 or action == 100) and self.getFocusId() == 6:
                    selectitem = self.control_list.getSelectedItem()
                    item = Item().fromurl(selectitem.getProperty("item_copy"))
                    if item.action == "play" and self.item.windowed:
                        video_urls, puede, motivo = servertools.resolve_video_urls_for_playing(
                            item.server, item.url)
                        self.close()
                        xbmc.sleep(200)
                        if puede:
                            result = video_urls[-1][1]
                            self.result = video_urls[-1][1]
                        else:
                            result = None
                            self.result = None

                    elif item.action == "play" and not self.item.windowed:
                        for window in window_select:
                            window.close()
                        retorna = platformtools.play_video(item,
                                                           force_direct=True)
                        if not retorna:
                            while True:
                                xbmc.sleep(1000)
                                if not xbmc.Player().isPlaying():
                                    break
                        window_select[-1].doModal()
                    else:
                        self.close()
                        buscartrailer(item)
            except:
                import traceback
                logger.error(traceback.format_exc())
        def onAction(self,action):
            global window_select, result
            if action == 92 or action == 110:
                self.result = "no_video"
                result = "no_video"
                self.close()
                window_select.pop()
                if not window_select:
                    if not self.item.windowed:
                        del window_select
                else:
                    window_select[-1].doModal()

            try:
                if (action == 7 or action == 100) and self.getFocusId() == 6:
                    selectitem = self.control_list.getSelectedItem()
                    item = Item().fromurl(selectitem.getProperty("item_copy"))
                    if item.action == "play" and self.item.windowed:
                        video_urls, puede, motivo = servertools.resolve_video_urls_for_playing(item.server, item.url)
                        self.close()
                        xbmc.sleep(200)
                        if puede:
                            result = video_urls[-1][1]
                            self.result = video_urls[-1][1]
                        else:
                            result = None
                            self.result = None
                            
                    elif item.action == "play" and not self.item.windowed:
                        for window in window_select:
                            window.close()
                        retorna = platformtools.play_video(item)
                        if not retorna:
                            while True:
                                xbmc.sleep(1000)
                                if not xbmc.Player().isPlaying():
                                    break
                        window_select[-1].doModal()
                    else:
                        self.close()
                        buscartrailer(item)
            except:
                import traceback
                logger.info(traceback.format_exc())
Exemple #23
0
def play_from_library(item):
    """
        Los .strm al reproducirlos desde kodi, este espera que sea un archivo "reproducible" asi que no puede contener
        más items, como mucho se puede colocar un dialogo de seleccion.
        Esto lo solucionamos "engañando a kodi" y haciendole creer que se ha reproducido algo, asi despues mediante
        "Container.Update()" cargamos el strm como si un item desde dentro del addon se tratara, quitando todas
        las limitaciones y permitiendo reproducir mediante la funcion general sin tener que crear nuevos métodos para
        la videoteca.
        @type item: item
        @param item: elemento con información
    """
    logger.info()
    # logger.debug("item: \n" + item.tostring('\n'))

    import xbmcgui
    import xbmcplugin
    import xbmc
    # Intentamos reproducir una imagen (esto no hace nada y ademas no da error)
    xbmcplugin.setResolvedUrl(
        int(sys.argv[1]), True,
        xbmcgui.ListItem(path=os.path.join(config.get_runtime_path(),
                                           "resources", "subtitle.mp4")))

    # Por si acaso la imagen hiciera (en futuras versiones) le damos a stop para detener la reproduccion
    xbmc.Player().stop()

    # modificamos el action (actualmente la videoteca necesita "findvideos" ya que es donde se buscan las fuentes
    item.action = "findvideos"

    window_type = config.get_setting("window_type", "videolibrary")

    # y volvemos a lanzar kodi
    if xbmc.getCondVisibility('Window.IsMedia') and not window_type == 1:
        # Ventana convencional
        xbmc.executebuiltin("Container.Update(" + sys.argv[0] + "?" +
                            item.tourl() + ")")

    else:
        # Ventana emergente
        from channels import videolibrary
        p_dialog = platformtools.dialog_progress_bg('alfa', 'Cargando...')
        p_dialog.update(0, '')

        itemlist = videolibrary.findvideos(item)

        while platformtools.is_playing():
            # Ventana convencional
            from time import sleep
            sleep(5)
        p_dialog.update(50, '')
        '''# Se filtran los enlaces segun la lista negra
        if config.get_setting('filter_servers', "servers"):
            itemlist = servertools.filter_servers(itemlist)'''

        # Se limita la cantidad de enlaces a mostrar
        if config.get_setting("max_links", "videolibrary") != 0:
            itemlist = limit_itemlist(itemlist)

        # Se "limpia" ligeramente la lista de enlaces
        if config.get_setting("replace_VD", "videolibrary") == 1:
            itemlist = reorder_itemlist(itemlist)

        p_dialog.update(100, '')
        xbmc.sleep(500)
        p_dialog.close()

        if len(itemlist) > 0:
            # El usuario elige el mirror
            opciones = []
            for item in itemlist:
                opciones.append(item.title)

            # Se abre la ventana de seleccion
            if (item.contentSerieName != "" and item.contentSeason != ""
                    and item.contentEpisodeNumber != ""):
                cabecera = ("%s - %sx%s -- %s" %
                            (item.contentSerieName, item.contentSeason,
                             item.contentEpisodeNumber,
                             config.get_localized_string(30163)))
            else:
                cabecera = config.get_localized_string(30163)

            seleccion = platformtools.dialog_select(cabecera, opciones)

            if seleccion == -1:
                return
            else:
                item = videolibrary.play(itemlist[seleccion])[0]
                platformtools.play_video(item)
Exemple #24
0
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)
Exemple #25
0
def start(itemlist, item):
    '''
    Metodo principal desde donde se reproduce automaticamente los enlaces
    - En caso la opcion de personalizar activa utilizara las opciones definidas por el usuario.
    - En caso contrario intentara reproducir cualquier enlace que cuente con el idioma preferido.

    :param itemlist: list (lista de items listos para reproducir, o sea con action='play')
    :param item: item (el item principal del canal)
    :return: intenta autoreproducir, en caso de fallar devuelve el itemlist que recibio en un principio
    '''
    logger.info()
    global autoplay_node

    if not config.is_xbmc():
        platformtools.dialog_notification('AutoPlay ERROR',
                                          'Sólo disponible para XBMC/Kodi')
        return itemlist
    else:
        if not autoplay_node:
            # Obtiene el nodo AUTOPLAY desde el json
            autoplay_node = jsontools.get_node_from_data_json(
                'autoplay', 'AUTOPLAY')

        # Agrega servidores y calidades que no estaban listados a autoplay_node
        new_options = check_value(item.channel, itemlist)

        # Obtiene el nodo del canal desde autoplay_node
        channel_node = autoplay_node.get(item.channel, {})
        # Obtiene los ajustes des autoplay para este canal
        settings_node = channel_node.get('settings', {})

        if settings_node['active']:
            url_list_valid = []
            autoplay_list = []
            favorite_servers = []
            favorite_quality = []

            # Guarda el valor actual de "Accion al seleccionar vídeo:" en preferencias
            user_config_setting = config.get_setting("default_action")
            # Habilita la accion "Ver en calidad alta" (si el servidor devuelve más de una calidad p.e. gdrive)
            if user_config_setting != 2:
                config.set_setting("default_action", 2)

            # Informa que AutoPlay esta activo
            platformtools.dialog_notification('AutoPlay Activo',
                                              '',
                                              sound=False)

            # Prioridades a la hora de ordenar itemlist:
            #       0: Servidores y calidades
            #       1: Calidades y servidores
            #       2: Solo servidores
            #       3: Solo calidades
            #       4: No ordenar
            if settings_node['custom_servers'] and settings_node[
                    'custom_quality']:
                priority = settings_node[
                    'priority']  # 0: Servidores y calidades o 1: Calidades y servidores
            elif settings_node['custom_servers']:
                priority = 2  # Solo servidores
            elif settings_node['custom_quality']:
                priority = 3  # Solo calidades
            else:
                priority = 4  # No ordenar

            # Obtiene las listas servidores, calidades disponibles desde el nodo del json de AutoPlay
            server_list = channel_node.get('servers', [])
            quality_list = channel_node.get('quality', [])

            # Se guardan los textos de cada servidor y calidad en listas p.e. favorite_servers = ['openload',
            # 'streamcloud']
            for num in range(1, 4):
                favorite_servers.append(
                    channel_node['servers'][settings_node['server_%s' % num]])
                favorite_quality.append(
                    channel_node['quality'][settings_node['quality_%s' % num]])

            # Se filtran los enlaces de itemlist y que se correspondan con los valores de autoplay
            for item in itemlist:
                autoplay_elem = dict()

                # Comprobamos q se trata de un item de video
                if 'server' not in item:
                    continue

                # Agrega la opcion configurar AutoPlay al menu contextual
                if 'context' not in item:
                    item.context = list()
                if not filter(lambda x: x['action'] == 'autoplay_config',
                              context):
                    item.context.append({
                        "title": "Configurar AutoPlay",
                        "action": "autoplay_config",
                        "channel": "autoplay",
                        "from_channel": item.channel
                    })

                # Si no tiene calidad definida le asigna calidad 'default'
                if item.quality == '':
                    item.quality = 'default'

                # Se crea la lista para configuracion personalizada
                if priority < 2:  # 0: Servidores y calidades o 1: Calidades y servidores

                    # si el servidor y la calidad no se encuentran en las listas de favoritos o la url esta repetida,
                    # descartamos el item
                    if item.server not in favorite_servers or item.quality not in favorite_quality \
                            or item.url in url_list_valid:
                        continue
                    autoplay_elem["indice_server"] = favorite_servers.index(
                        item.server)
                    autoplay_elem["indice_quality"] = favorite_quality.index(
                        item.quality)

                elif priority == 2:  # Solo servidores

                    # si el servidor no se encuentra en la lista de favoritos o la url esta repetida,
                    # descartamos el item
                    if item.server not in favorite_servers or item.url in url_list_valid:
                        continue
                    autoplay_elem["indice_server"] = favorite_servers.index(
                        item.server)

                elif priority == 3:  # Solo calidades

                    # si la calidad no se encuentra en la lista de favoritos o la url esta repetida,
                    # descartamos el item
                    if item.quality not in favorite_quality or item.url in url_list_valid:
                        continue
                    autoplay_elem["indice_quality"] = favorite_quality.index(
                        item.quality)

                else:  # No ordenar

                    # si la url esta repetida, descartamos el item
                    if item.url in url_list_valid:
                        continue

                # Si el item llega hasta aqui lo añadimos al listado de urls validas y a autoplay_list
                url_list_valid.append(item.url)
                autoplay_elem['videoitem'] = item
                #autoplay_elem['server'] = item.server
                #autoplay_elem['quality'] = item.quality
                autoplay_list.append(autoplay_elem)

            # Ordenamos segun la prioridad
            if priority == 0:  # Servidores y calidades
                autoplay_list.sort(key=lambda orden: (orden['indice_server'],
                                                      orden['indice_quality']))

            elif priority == 1:  # Calidades y servidores
                autoplay_list.sort(key=lambda orden: (orden['indice_quality'],
                                                      orden['indice_server']))

            elif priority == 2:  # Solo servidores
                autoplay_list.sort(key=lambda orden: orden['indice_server'])

            elif priority == 3:  # Solo calidades
                autoplay_list.sort(key=lambda orden: orden['indice_quality'])

            # Si hay elementos en la lista de autoplay se intenta reproducir cada elemento, hasta encontrar uno
            # funcional o fallen todos
            if autoplay_list:
                played = False
                max_intentos = 5
                max_intentos_servers = {}

                # Si se esta reproduciendo algo detiene la reproduccion
                if platformtools.is_playing():
                    platformtools.stop_video()

                for autoplay_elem in autoplay_list:
                    if not platformtools.is_playing() and not played:
                        videoitem = autoplay_elem['videoitem']

                        if videoitem.server not in max_intentos_servers:
                            max_intentos_servers[
                                videoitem.server] = max_intentos

                        # Si se han alcanzado el numero maximo de intentos de este servidor saltamos al siguiente
                        if max_intentos_servers[videoitem.server] == 0:
                            continue

                        lang = " "
                        if hasattr(videoitem,
                                   'language') and videoitem.language != "":
                            lang = " '%s' " % videoitem.language

                        platformtools.dialog_notification(
                            "AutoPlay",
                            "%s%s%s" % (videoitem.server.upper(), lang,
                                        videoitem.quality.upper()),
                            sound=False)
                        #TODO videoitem.server es el id del server, pero podria no ser el nombre!!!

                        # Intenta reproducir los enlaces
                        # Si el canal tiene metodo play propio lo utiliza
                        channel = __import__('channels.%s' % item.channel,
                                             None, None,
                                             ["channels.%s" % item.channel])
                        if hasattr(channel, 'play'):
                            resolved_item = getattr(channel, 'play')(videoitem)
                            if len(resolved_item) > 0:
                                if isinstance(resolved_item[0], list):
                                    videoitem.video_urls = resolved_item
                                else:
                                    videoitem = resolved_item[0]

                        # si no directamente reproduce
                        platformtools.play_video(videoitem)

                        try:
                            if platformtools.is_playing():
                                played = True
                                break
                        except:  # TODO evitar el informe de que el conector fallo o el video no se encuentra
                            logger.debug(str(len(autoplay_list)))

                        # Si hemos llegado hasta aqui es por q no se ha podido reproducir
                        max_intentos_servers[videoitem.server] -= 1

                        # Si se han alcanzado el numero maximo de intentos de este servidor
                        # preguntar si queremos seguir probando o lo ignoramos
                        if max_intentos_servers[videoitem.server] == 0:
                            text = "Parece que los enlaces de %s no estan funcionando." % videoitem.server.upper(
                            )
                            if not platformtools.dialog_yesno(
                                    "AutoPlay", text,
                                    "¿Desea ignorar todos los enlaces de este servidor?"
                            ):
                                max_intentos_servers[
                                    videoitem.server] = max_intentos

            else:
                platformtools.dialog_notification('AutoPlay No Fue Posible',
                                                  'No Hubo Coincidencias')
            if new_options:
                platformtools.dialog_notification(
                    "AutoPlay", "Nueva Calidad/Servidor disponible en la "
                    "configuracion",
                    sound=False)

            # Restaura si es necesario el valor previo de "Accion al seleccionar vídeo:" en preferencias
            if user_config_setting != 2:
                config.set_setting("default_action", user_config_setting)

        # devuelve la lista de enlaces para la eleccion manual
        return itemlist
def findvideos(item):
    logger.info()
    # logger.debug("item:\n" + item.tostring('\n'))

    itemlist = []
    list_canales = {}
    item_local = None

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

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

    if item.contentType == 'movie':
        item.strm_path = filetools.join(library.MOVIES_PATH, item.strm_path.strip('\/'))

        path_dir = os.path.dirname(item.strm_path)
        item.nfo = filetools.join(path_dir, os.path.basename(path_dir) + ".nfo")
    else:
        item.strm_path = filetools.join(library.TVSHOWS_PATH, item.strm_path.strip('\/'))
        path_dir = os.path.dirname(item.strm_path)
        item.nfo = filetools.join(path_dir, 'tvshow.nfo')

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

    num_canales = len(list_canales)
    if 'descargas' in list_canales:
        json_path = list_canales['descargas']
        item_json = Item().fromjson(filetools.read(json_path))
        del list_canales['descargas']

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

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

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

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

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

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

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

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

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

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

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

            server.contentChannel = server.channel
            server.channel = "biblioteca"
            server.nfo = item.nfo
            server.strm_path = item.strm_path
            server.title = "%s: %s" % (nom_canal.capitalize(), server.title)

            server.infoLabels = item_json.infoLabels

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

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

    # return sorted(itemlist, key=lambda it: it.title.lower())
    return itemlist
def play_video(item):
    platformtools.play_video(item)
Exemple #28
0
def start(itemlist, item):
    '''
    Main method from which the links are automatically reproduced
    - In case the option to activate it will use the options defined by the user.
    - Otherwise it will try to reproduce any link that has the preferred language.

    :param itemlist: list (list of items ready to play, ie with action = 'play')
    :param item: item (the main item of the channel)
    :return: try to auto-reproduce, in case of failure it returns the itemlist that it received in the beginning
    '''

    if item.global_search:
        return itemlist
    logger.debug()

    global PLAYED
    PLAYED = False

    base_item = item

    if not config.is_xbmc():
        return itemlist

    if config.get_setting('autoplay'):
        url_list_valid = []
        autoplay_list = []
        autoplay_b = []
        favorite_quality = []
        favorite_servers = []
        blacklisted_servers = config.get_setting("black_list",
                                                 server='servers')
        if not blacklisted_servers: blacklisted_servers = []

        from core import servertools
        servers_list = list(servertools.get_servers_list().items())
        for server, server_parameters in servers_list:
            if config.get_setting('favorites_servers_list', server=server):
                favorite_servers.append(server.lower())

        if not favorite_servers:
            config.set_setting('favorites_servers_list', [], server='servers')
            favorite_servers = []
        else:
            favorite_servers = list(
                set(favorite_servers) - set(blacklisted_servers))

        # Save the current value of "Action and Player Mode" in preferences
        user_config_setting_action = config.get_setting("default_action")
        # user_config_setting_player = config.get_setting("player_mode")

        # Enable the "View in high quality" action (if the server returns more than one quality, eg gdrive)
        if not user_config_setting_action:
            config.set_setting("default_action", 2)

        # if user_config_setting_player != 0: config.set_setting("player_mode", 0)

        # Priorities when ordering itemlist:
        #       0: Servers and qualities
        #       1: Qualities and servers
        #       2: Servers only
        #       3: Only qualities
        #       4: Do not order
        if config.get_setting('favorites_servers'
                              ) and favorite_servers and config.get_setting(
                                  'default_action'):
            priority = 0  # 0: Servers and qualities or 1: Qualities and servers
        elif config.get_setting('favorites_servers') and favorite_servers:
            priority = 2  # Servers only
        elif config.get_setting('default_action'):
            priority = 3  # Only qualities
        else:
            priority = 4  # Do not order

        if config.get_setting('default_action') == 1:
            quality_list.reverse()
        favorite_quality = quality_list

        for item in itemlist:
            autoplay_elem = dict()
            b_dict = dict()

            # We check that it is a video item
            if 'server' not in item:
                continue

            if item.server.lower() in blacklisted_servers:
                continue

            # If it does not have a defined quality, it assigns a 'default' quality.
            if item.quality.lower() not in quality_list:
                item.quality = 'default'
            # The list for custom settings is created

            if priority < 2:  # 0: Servers and qualities or 1: Qualities and servers

                # if the server and the quality are not in the favorites lists or the url is repeated, we discard the item
                if item.server.lower(
                ) not in favorite_servers or item.quality.lower(
                ) not in favorite_quality or item.url in url_list_valid:
                    item.type_b = True
                    item.play_from = base_item.play_from
                    b_dict['videoitem'] = item
                    autoplay_b.append(b_dict)
                    continue
                autoplay_elem["indice_server"] = favorite_servers.index(
                    item.server.lower())
                autoplay_elem["indice_quality"] = favorite_quality.index(
                    item.quality.lower())

            elif priority == 2:  # Servers only

                # if the server is not in the favorites list or the url is repeated, we discard the item
                if item.server.lower(
                ) not in favorite_servers or item.url in url_list_valid:
                    item.type_b = True
                    item.play_from = base_item.play_from
                    b_dict['videoitem'] = item
                    autoplay_b.append(b_dict)
                    continue
                autoplay_elem["indice_server"] = favorite_servers.index(
                    item.server.lower())

            elif priority == 3:  # Only qualities

                # if the quality is not in the favorites list or the url is repeated, we discard the item
                if item.quality.lower(
                ) not in favorite_quality or item.url in url_list_valid:
                    item.type_b = True
                    item.play_from = base_item.play_from
                    b_dict['videoitem'] = item
                    autoplay_b.append(b_dict)
                    continue
                autoplay_elem["indice_quality"] = favorite_quality.index(
                    item.quality.lower())

            else:  # Do not order

                # if the url is repeated, we discard the item
                item.play_from = base_item.play_from
                if item.url in url_list_valid:
                    continue

            # If the item reaches here we add it to the list of valid urls and to autoplay_list
            url_list_valid.append(item.url)
            item.plan_b = True
            item.play_from = base_item.play_from
            autoplay_elem['videoitem'] = item
            autoplay_list.append(autoplay_elem)

        # We order according to priority
        if priority == 0:
            autoplay_list.sort(key=lambda orden: (
                (orden['indice_server'], orden['indice_quality']))
                               )  # Servers and qualities
        elif priority == 1:
            autoplay_list.sort(key=lambda orden:
                               (orden['indice_quality'], orden['indice_server']
                                ))  # Qualities and servers
        elif priority == 2:
            autoplay_list.sort(key=lambda orden:
                               (orden['indice_server']))  # Servers only
        elif priority == 3:
            autoplay_list.sort(key=lambda orden:
                               (orden['indice_quality']))  # Only qualities

        logger.debug('PRIORITY', priority, autoplay_list)

        # if quality priority is active
        if priority == 0 and config.get_setting('quality_priority'):
            max_quality = autoplay_list[0][
                "indice_quality"] if autoplay_list and "indice_quality" in autoplay_list[
                    0] else 0
            for n, item in enumerate(itemlist):
                if 'server' not in item:
                    continue

                if item.server.lower() in blacklisted_servers:
                    continue

                # If it does not have a defined quality, it assigns a 'default' quality.
                if item.quality == '':
                    item.quality = 'default'

                if favorite_quality.index(item.quality.lower()) < max_quality:
                    item.type_b = False
                    autoplay_elem["indice_server"] = n
                    autoplay_elem["indice_quality"] = favorite_quality.index(
                        item.quality.lower())
                    autoplay_elem['videoitem'] = item
                    autoplay_list.append(autoplay_elem)
            autoplay_list.sort(key=lambda orden: (orden['indice_quality'],
                                                  orden['indice_server']))

        # Plan b is prepared, in case it is active the non-favorite elements are added at the end
        # try: plan_b = settings_node['plan_b']
        # except:
        plan_b = True
        text_b = ''
        if plan_b: autoplay_list.extend(autoplay_b)
        # If there are elements in the autoplay list, an attempt is made to reproduce each element, until one is found or all fail.

        if autoplay_list or (plan_b and autoplay_b):

            max_intentos = 5
            max_intentos_servers = {}

            # If something is playing it stops playing
            if platformtools.is_playing():
                platformtools.stop_video()

            for autoplay_elem in autoplay_list:
                play_item = Item
                channel_id = autoplay_elem['videoitem'].channel
                if autoplay_elem['videoitem'].channel == 'videolibrary':
                    channel_id = autoplay_elem['videoitem'].contentChannel

                # If it is not a favorite element if you add the text plan b
                if autoplay_elem['videoitem'].type_b:
                    text_b = '(Plan B)'
                if not platformtools.is_playing() and not PLAYED:
                    videoitem = autoplay_elem['videoitem']
                    if videoitem.server.lower() not in max_intentos_servers:
                        max_intentos_servers[
                            videoitem.server.lower()] = max_intentos

                    # If the maximum number of attempts of this server have been reached, we jump to the next
                    if max_intentos_servers[videoitem.server.lower()] == 0:
                        continue

                    lang = " "
                    if hasattr(videoitem,
                               'language') and videoitem.language != "":
                        lang = " '%s' " % videoitem.language
                    name = servername(videoitem.server)
                    platformtools.dialog_notification(
                        "AutoPlay %s" % text_b,
                        "%s%s%s" % (name, lang, videoitem.quality.upper()),
                        sound=False)

                    # Try to play the links If the channel has its own play method, use it
                    try:
                        channel = __import__('channels.%s' % channel_id, None,
                                             None,
                                             ["channels.%s" % channel_id])
                    except:
                        channel = __import__('specials.%s' % channel_id, None,
                                             None,
                                             ["specials.%s" % channel_id])
                    if hasattr(channel, 'play'):
                        resolved_item = getattr(channel, 'play')(videoitem)
                        if len(resolved_item) > 0:
                            if isinstance(resolved_item[0], list):
                                videoitem.video_urls = resolved_item
                            else:
                                videoitem = resolved_item[0]

                    play_item.autoplay = True
                    # If not directly reproduce and mark as seen
                    # Check if the item comes from the video library
                    try:
                        if base_item.contentChannel == 'videolibrary' or base_item.nfo:
                            # Fill the video with the data of the main item and play
                            play_item = base_item.clone(**videoitem.__dict__)
                            platformtools.play_video(play_item, autoplay=True)
                        else:
                            # If it doesn't come from the video library, just play
                            platformtools.play_video(videoitem, autoplay=True)
                    except:
                        pass
                    sleep(3)
                    try:
                        if platformtools.is_playing():
                            PLAYED = True
                            break
                    except:
                        logger.debug(str(len(autoplay_list)))

                    # If we have come this far, it is because it could not be reproduced
                    max_intentos_servers[videoitem.server.lower()] -= 1

                    # If the maximum number of attempts of this server has been reached, ask if we want to continue testing or ignore it.
                    if max_intentos_servers[videoitem.server.lower()] == 0:
                        text = config.get_localized_string(60072) % name
                        if not platformtools.dialog_yesno(
                                "AutoPlay", text,
                                config.get_localized_string(60073)):
                            max_intentos_servers[
                                videoitem.server.lower()] = max_intentos

                    # If there are no items in the list, it is reported
                    if autoplay_elem == autoplay_list[-1]:
                        platformtools.dialog_notification(
                            'AutoPlay',
                            config.get_localized_string(60072) % name)

        else:
            platformtools.dialog_notification(
                config.get_localized_string(60074),
                config.get_localized_string(60075))

        # Restore if necessary the previous value of "Action and Player Mode" in preferences
        if not user_config_setting_action:
            config.set_setting("default_action", user_config_setting_action)
        # if user_config_setting_player != 0: config.set_setting("player_mode", user_config_setting_player)

    return itemlist
Exemple #29
0
def get_next_items( item ):

    plugintools.log("navigation.get_next_items item="+item.tostring())

    try:
        # ----------------------------------------------------------------
        #  Main menu
        # ----------------------------------------------------------------
        if item.channel=="navigation":

            if item.action=="mainlist":
                plugintools.log("navigation.get_next_items Main menu")
                itemlist = channelselector.getmainlist("bannermenu")

        elif item.channel=="channelselector":

            if item.action=="channeltypes":
                plugintools.log("navigation.get_next_items Channel types menu")
                itemlist = channelselector.getchanneltypes("bannermenu")

            elif item.action=="listchannels":
                plugintools.log("navigation.get_next_items Channel list menu")
                itemlist = channelselector.filterchannels(item.category,"bannermenu")

        else:

            if item.action=="":
                item.action="mainlist"

            plugintools.log("navigation.get_next_items Channel code ("+item.channel+"."+item.action+")")

            try:
                exec "import channels."+item.channel+" as channel"
            except:
                exec "import core."+item.channel+" as channel"

            from platformcode import platformtools

            if item.action=="play":
                plugintools.log("navigation.get_next_items play")

                # Si el canal tiene una acción "play" tiene prioridad
                if hasattr(channel, 'play'):
                    plugintools.log("navigation.get_next_items play Channel has its own 'play' method")
                    itemlist = channel.play(item)
                    if len(itemlist)>0:
                        item = itemlist[0]

                        # FIXME: Este error ha que tratarlo de otra manera, al dar a volver sin ver el vídeo falla
                        try:
                            platformtools.play_video(item)
                        except:
                            pass

                    else:
                        import xbmcgui
                        ventana_error = xbmcgui.Dialog()
                        ok = ventana_error.ok ("plugin", "No hay nada para reproducir")
                else:
                    plugintools.log("navigation.get_next_items play No channel 'play' method, executing core method")

                    # FIXME: Este error ha que tratarlo de otra manera, por al dar a volver sin ver el vídeo falla
                    # Mejor hacer el play desde la ventana
                    try:
                        platformtools.play_video(item)
                    except:
                        import traceback
                        plugintools.log(traceback.format_exc())
                        pass

                return []

            elif item.action=="findvideos":
                plugintools.log("navigation.get_next_items findvideos")

                # Si el canal tiene una acción "findvideos" tiene prioridad
                if hasattr(channel, 'findvideos'):
                    plugintools.log("navigation.get_next_items play Channel has its own 'findvideos' method")
                    itemlist = channel.findvideos(item)
                else:
                    itemlist = []

                if len(itemlist)==0:
                    from core import servertools
                    itemlist = servertools.find_video_items(item)

                if len(itemlist)==0:
                    itemlist = [ Item(title="No se han encontrado vídeos", thumbnail="http://media.tvalacarta.info/pelisalacarta/thumb_error.png") ]

            else:

                if item.action=="search":
                    tecleado = plugintools.keyboard_input()
                    if tecleado!="":
                        tecleado = tecleado.replace(" ", "+")
                        itemlist = channel.search(item,tecleado)
                elif item.channel=="novedades" and item.action=="mainlist":
                    itemlist = channel.mainlist(item,"bannermenu")
                elif item.channel=="buscador" and item.action=="mainlist":
                    itemlist = channel.mainlist(item,"bannermenu")
                else:
                    exec "itemlist = channel."+item.action+"(item)"

                for loaded_item in itemlist:

                    if loaded_item.thumbnail=="":
                        if loaded_item.folder:
                            loaded_item.thumbnail = "http://media.tvalacarta.info/pelisalacarta/thumb_folder.png"
                        else:
                            loaded_item.thumbnail = "http://media.tvalacarta.info/pelisalacarta/thumb_nofolder.png"

                if len(itemlist)==0:
                    itemlist = [ Item(title="No hay elementos para mostrar", thumbnail="http://media.tvalacarta.info/pelisalacarta/thumb_error.png" ) ]

    except:
        import traceback
        plugintools.log("navigation.get_next_items "+traceback.format_exc())
        itemlist = [ Item(title="Se ha producido un error", thumbnail="http://media.tvalacarta.info/pelisalacarta/thumb_error.png") ]


    return itemlist
def play_from_library(item):
    """
        Los .strm al reproducirlos desde kodi, este espera que sea un archivo "reproducible" asi que no puede contener
        más items, como mucho se puede colocar un dialogo de seleccion.
        Esto lo solucionamos "engañando a kodi" y haciendole creer que se ha reproducido algo, asi despues mediante
        "Container.Update()" cargamos el strm como si un item desde dentro de pelisalacarta se tratara, quitando todas
        las limitaciones y permitiendo reproducir mediante la funcion general sin tener que crear nuevos métodos para
        la biblioteca.
        @type item: item
        @param item: elemento con información
    """
    logger.info()
    # logger.debug("item: \n" + item.tostring('\n'))

    import xbmcgui
    import xbmcplugin
    import xbmc
    # Intentamos reproducir una imagen (esto no hace nada y ademas no da error)
    xbmcplugin.setResolvedUrl(int(sys.argv[1]), True,
                              xbmcgui.ListItem(path=os.path.join(config.get_runtime_path(), "icon.png")))

    # Por si acaso la imagen hiciera (en futuras versiones) le damos a stop para detener la reproduccion
    xbmc.Player().stop()

    # modificamos el action (actualmente la biblioteca necesita "findvideos" ya que es donde se buscan las fuentes
    item.action = "findvideos"

    window_type = config.get_setting("window_type", "biblioteca")
    
    # y volvemos a lanzar kodi
    if xbmc.getCondVisibility('Window.IsMedia') and not window_type == 1:
        # Ventana convencional
        xbmc.executebuiltin("Container.Update(" + sys.argv[0] + "?" + item.tourl() + ")")

    else:
        # Ventana emergente
        from channels import biblioteca
        p_dialog = platformtools.dialog_progress_bg('streamondemand', 'Caricamento in corso...')
        p_dialog.update(0, '')

        itemlist = biblioteca.findvideos(item)

        p_dialog.update(50, '')

        # Se filtran los enlaces segun la lista blanca y negra
        if config.get_setting('filter_servers') == 'true':
            itemlist = filtered_servers(itemlist)

        # Se limita la cantidad de enlaces a mostrar
        if config.get_setting("max_links", "biblioteca") != 0:
            itemlist = limit_itemlist(itemlist)

        # Se "limpia" ligeramente la lista de enlaces
        if config.get_setting("replace_VD", "biblioteca") == 1:
            itemlist = reorder_itemlist(itemlist)

        p_dialog.update(100, '')
        xbmc.sleep(500)
        p_dialog.close()

        if len(itemlist) > 0:
            # El usuario elige el mirror
            opciones = []
            for item in itemlist:
                opciones.append(item.title)

            # Se abre la ventana de seleccion
            if (item.contentSerieName != "" and
                    item.contentSeason != "" and
                    item.contentEpisodeNumber != ""):
                cabecera = ("%s - %sx%s -- %s" %
                            (item.contentSerieName,
                             item.contentSeason,
                             item.contentEpisodeNumber,
                             config.get_localized_string(30163)))
            else:
                cabecera = config.get_localized_string(30163)

            seleccion = platformtools.dialog_select(cabecera, opciones)
            if seleccion == -1:
                return

            else:
                item = biblioteca.play(itemlist[seleccion])[0]
                platformtools.play_video(item)
Exemple #31
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"))
def buscartrailer(item):
    logger.info("pelisalacarta.channels.trailertools buscartrailer")

    # Se elimina la opciçon 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 = ""
    # 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:
        fulltitle = re.sub('\[\/*(B|I|COLOR)\s*[^\]]*\]', '', item.fulltitle.strip())
        item.contentTitle = platformtools.dialog_input(default=fulltitle, heading="Introduce el título a buscar")
        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

    if "year" in item.infoLabels:    
        item.year = item.infoLabels['year']
    else:
        item.year = ""
      
    logger.info("pelisalacarta.channels.trailertools Búsqueda: %s" % item.contentTitle)
    logger.info("pelisalacarta.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 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'] != ""):
            tipo = "tv"
        else:
            tipo = "movie"
        try:
            itemlist.extend(tmdb_trailers(item, tipo))
        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 % "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":
                        platformtools.play_video(item)
                    return
    else:
        return itemlist
Exemple #33
0
def play_video(item):
    platformtools.play_video(item) 
Exemple #34
0
def findvideos(item):
    logger.info()
    # logger.debug("item:\n" + item.tostring('\n'))

    itemlist = []
    list_canales = {}
    item_local = None

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

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

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

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

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

        del list_canales['downloads']

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

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

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

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

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

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

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

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

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

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

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

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

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

            server.infoLabels = item_json.infoLabels

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

            # logger.debug("server:\n%s" % server.tostring('\n'))
            itemlist.append(server)
Exemple #35
0
def run(item=None):
    logger.info()

    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:
            if config.get_setting("start_page"):

                if not config.get_setting("custom_start"):

                    category = config.get_setting("category")

                    if isinstance(category, int):
                        category = config.get_localized_string(
                            config.get_setting("category")).lower()

                    item = Item(channel="news",
                                action="news",
                                news=category.lower(),
                                startpage=True)
                else:
                    from channels import side_menu
                    item = Item()
                    item = side_menu.check_user_home(item)
                    item.startpage = True
            else:
                item = Item(channel="channelselector",
                            action="getmainlist",
                            viewmode="movie")
        if not config.get_setting('show_once'):
            from platformcode import configurator
            configurator.show_window()

    logger.info(item.tostring())

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

    # Cleans infoLabels["playcount"] if set by generictools
    if item.video_path:
        item.infoLabels["playcount"] = 1
        del item.infoLabels["playcount"]

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

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

        elif item.channel == 'channelselector':
            import channelselector

            # Action for addon install on channelselector
            if item.action == "install_alfa":
                channelselector.install_alfa()

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

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

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

                platformtools.render_items(itemlist, item)

        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(
                    config.get_localized_string(20000),
                    config.get_localized_string(60011),
                    time=2000,
                    sound=False)

        elif item.action == "function":
            """
            {
                "action": "function",
                "folder": "lib",
                "function": "alfa_assistant",
                "method": "install_alfa_assistant",
                "options": "auto"
            }
            """
            # Checks if function file exists
            function_file = os.path.join(config.get_runtime_path(),
                                         item.folder, item.function + ".py")
            logger.info("function_file=%s" % function_file)

            function = None

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

                logger.info(
                    "Running function %s(%s) | %s" %
                    (function.__name__, item.options, function.__file__))

                getattr(function, item.method)(item.options)

            else:
                logger.error(
                    "ERROR Running function %s(%s) | %s" %
                    (function.__name__, item.options, function.__file__))

        # 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(
                        "", config.get_localized_string(60334), 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__))

            if item.channel == "test" and item.contentChannel:
                if item.parameters == "test_channel":
                    getattr(channel, item.action)(item.contentChannel)

            # Calls redirection if Alfavorites findvideos, episodios, seasons
            if item.context and 'alfavorites' in str(item.context) \
                            and item.action in ['findvideos', 'episodios', 'seasons', 'play']:
                try:
                    from lib import generictools
                    item, it, overwrite = generictools.redirect_clone_newpct1(
                        item)
                except:
                    import traceback
                    logger.error(traceback.format_exc())

            # 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(
                            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.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

                last_search = channeltools.get_channel_setting(
                    'Last_searched', 'search', '')

                tecleado = platformtools.dialog_input(last_search)

                if tecleado is not None:
                    if "http" not in tecleado:
                        channeltools.set_channel_setting(
                            'Last_searched', tecleado, 'search')
                    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)
                elif not config.get_setting('install_trakt'):
                    config.set_setting('install_trakt', True)

                platformtools.render_items(itemlist, item)

    except urllib2.URLError as 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)
    except WebErrorException as e:
        import traceback
        logger.error(traceback.format_exc())

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

        platformtools.dialog_ok(
            config.get_localized_string(59985) + canal,
            config.get_localized_string(60013) % (e))
    except:
        import traceback
        logger.error(traceback.format_exc())

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

        try:
            if config.get_platform(True)['num_version'] < 14:
                log_name = "xbmc.log"
            else:
                log_name = "kodi.log"
            log_message = config.get_localized_string(
                50004) + config.translatePath("special://logpath") + log_name
        except:
            log_message = ""

        if canal:
            platformtools.dialog_ok(
                config.get_localized_string(60087) % canal,
                config.get_localized_string(60014), log_message)
        else:
            platformtools.dialog_ok(config.get_localized_string(60038),
                                    config.get_localized_string(60015),
                                    log_message)
Exemple #36
0
def findvideos(item):
    from core import autoplay
    logger.info()
    # logger.debug("item:\n" + item.tostring('\n'))
    videolibrarytools.check_renumber_options(item)
    itemlist = []
    list_canales = {}
    item_local = None

    # Disable autoplay
    # autoplay.set_status(False)

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

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

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

    num_canales = len(list_canales)

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

        del list_canales['downloads']

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

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

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

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

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

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

        item_canal = Item()

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

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

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

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

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

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

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

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

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

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

    add_download_items(item, itemlist)
    return itemlist
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)
Exemple #38
0
def play_from_library(item):
    """
        The .strm files when played from kodi, this expects it to be a "playable" file so it cannot contain
        more items, at most a selection dialog can be placed.
        We solve this by "cheating kodi" and making him believe that something has been reproduced, so later by
        "Container.Update ()" we load the strm as if an item from inside the addon were treated, removing all
        the limitations and allowing to reproduce through the general function without having to create new methods to
        the video library.
        @type item: item
        @param item: item with information
    """
    def get_played_time(item):
        if item.contentType == 'movie': nfo_path = item.nfo
        else: nfo_path = item.strm_path.replace('strm', 'nfo')
        if nfo_path and filetools.isfile(nfo_path):
            from core import videolibrarytools
            head_nfo, item_nfo = videolibrarytools.read_nfo(nfo_path)
            sleep(1)
            played_time = platformtools.get_played_time(item_nfo)
        else:
            played_time = 0
        return played_time

    import xbmcgui, xbmcplugin, xbmc
    from time import sleep

    # logger.debug("item: \n" + item.tostring('\n'))
    platformtools.prevent_busy(item)

    itemlist = []
    item.fromLibrary = True
    item.window = True
    logger.debug()

    # Modify the action (currently the video library needs "findvideos" since this is where the sources are searched
    item.action = "findvideos"

    window_type = config.get_setting("window_type", "videolibrary")
    # and launch kodi again
    if xbmc.getCondVisibility('Window.IsMedia') and not window_type == 1:
        xbmc.executebuiltin("Container.Update(" + sys.argv[0] + "?" +
                            item.tourl() + ")")

    else:
        # Pop-up window
        from specials import videolibrary
        p_dialog = platformtools.dialog_progress_bg(
            config.get_localized_string(20000),
            config.get_localized_string(60683))
        p_dialog.update(0, '')
        item.play_from = 'window'
        itemlist = videolibrary.findvideos(item)
        p_dialog.update(100, '')
        sleep(0.5)
        p_dialog.close()
        played = False

        # The number of links to show is limited
        if config.get_setting("max_links", "videolibrary") != 0:
            itemlist = limit_itemlist(itemlist)
        # The list of links is slightly "cleaned"
        if config.get_setting("replace_VD", "videolibrary") == 1:
            itemlist = reorder_itemlist(itemlist)
        # from core.support import dbg;dbg()
        if len(itemlist) > 0:
            reopen = False
            while not xbmc.Monitor().abortRequested():
                played = True
                # The user chooses the mirror
                if not platformtools.is_playing():
                    # from core.support import dbg;dbg()
                    if config.get_setting('autoplay') or reopen:
                        played_time = get_played_time(item)
                        if not played_time and played:
                            return
                    options = []
                    selection_implementation = 0
                    for item in itemlist:
                        item.thumbnail = config.get_online_server_thumb(
                            item.server)
                        quality = '[B][' + item.quality + '][/B]' if item.quality else ''
                        if item.server:
                            path = filetools.join(
                                config.get_runtime_path(), 'servers',
                                item.server.lower() + '.json')
                            name = jsontools.load(open(path,
                                                       "r").read())['name']
                            if name.startswith('@'):
                                name = config.get_localized_string(
                                    int(name.replace('@', '')))
                            it = xbmcgui.ListItem(
                                '\n[B]%s[/B] %s - %s' %
                                (name, quality, item.contentTitle))
                            it.setArt({'thumb': item.thumbnail})
                            options.append(it)
                        else:
                            selection_implementation += 1
                    # The selection window opens
                    if (item.contentSerieName and item.contentSeason
                            and item.contentEpisodeNumber):
                        head = ("%s - %sx%s | %s" %
                                (item.contentSerieName, item.contentSeason,
                                 item.contentEpisodeNumber,
                                 config.get_localized_string(30163)))
                    else:
                        head = config.get_localized_string(30163)
                    selection = platformtools.dialog_select(head,
                                                            options,
                                                            preselect=-1,
                                                            useDetails=True)
                    if selection == -1:
                        return
                    else:
                        item = videolibrary.play(
                            itemlist[selection + selection_implementation])[0]
                        platformtools.play_video(item)
                        reopen = True
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)