def set_player(item, xlistitem, mediaurl, view, strm): logger.info() logger.debug("item:\n" + item.tostring('\n')) # Movido del conector "torrent" aqui if item.server == "torrent": play_torrent(item, xlistitem, mediaurl) return # Si es un fichero strm no hace falta el play elif strm: xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, xlistitem) if item.subtitle != "": xbmc.sleep(2000) xbmc.Player().setSubtitles(item.subtitle) else: logger.info("player_mode=%s" % config.get_setting("player_mode")) logger.info("mediaurl=" + mediaurl) if config.get_setting( "player_mode") == 3 or "megacrypter.com" in mediaurl: import download_and_play download_and_play.download_and_play( mediaurl, "download_and_play.tmp", config.get_setting("downloadpath")) return elif config.get_setting("player_mode") == 0 or \ (config.get_setting("player_mode") == 3 and mediaurl.startswith("rtmp")): # Añadimos el listitem a una lista de reproducción (playlist) playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO) playlist.clear() playlist.add(mediaurl, xlistitem) # Reproduce xbmc_player = xbmc.Player() xbmc_player.play(playlist, xlistitem) # elif config.get_setting("player_mode") == 1 or item.isPlayable: elif config.get_setting("player_mode") == 1: logger.info("mediaurl :" + mediaurl) logger.info("Tras setResolvedUrl") # si es un archivo de la videoteca enviar a marcar como visto if strm or item.strm_path: from platformcode import xbmc_videolibrary xbmc_videolibrary.mark_auto_as_watched(item) xlistitem.setPath(mediaurl) xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, xlistitem) elif config.get_setting("player_mode") == 2: xbmc.executebuiltin("PlayMedia(" + mediaurl + ")") # TODO MIRAR DE QUITAR VIEW if item.subtitle != "" and view: logger.info("Subtítulos externos: " + item.subtitle) xbmc.sleep(2000) xbmc.Player().setSubtitles(item.subtitle) # si es un archivo de la videoteca enviar a marcar como visto if strm or item.strm_path: from platformcode import xbmc_videolibrary xbmc_videolibrary.mark_auto_as_watched(item)
def play_torrent(item, xlistitem, mediaurl): logger.info() # Opciones disponibles para Reproducir torrents torrent_options = list() torrent_options.append(["Cliente interno (necesario libtorrent)"]) torrent_options.append(["Cliente interno MCT (necesario libtorrent)"]) torrent_options.extend(torrent_client_installed(show_tuple=True)) torrent_client = config.get_setting("torrent_client", server="torrent") if torrent_client and torrent_client - 1 <= len(torrent_options): if torrent_client == 0: seleccion = dialog_select( "Abrir torrent con...", [opcion[0] for opcion in torrent_options]) else: seleccion = torrent_client - 1 else: if len(torrent_options) > 1: seleccion = dialog_select( "Abrir torrent con...", [opcion[0] for opcion in torrent_options]) else: seleccion = 0 # Plugins externos if seleccion > 1: mediaurl = urllib.quote_plus(item.url) xbmc.executebuiltin("PlayMedia(" + torrent_options[seleccion][1] % mediaurl + ")") if seleccion == 1: from platformcode import mct mct.play(mediaurl, xlistitem, subtitle=item.subtitle, item=item) # Reproductor propio (libtorrent) if seleccion == 0: import time played = False debug = (config.get_setting("debug") == True) # Importamos el cliente from btserver import Client client_tmp_path = config.get_setting("downloadpath") if not client_tmp_path: client_tmp_path = config.get_data_path() # Iniciamos el cliente: c = Client(url=mediaurl, is_playing_fnc=xbmc.Player().isPlaying, wait_time=None, timeout=10, temp_path=os.path.join(client_tmp_path, "alfa-torrent"), print_status=debug) # Mostramos el progreso progreso = dialog_progress("Alfa - Torrent", "Iniciando...") # Mientras el progreso no sea cancelado ni el cliente cerrado while not c.closed: try: # Obtenemos el estado del torrent s = c.status if debug: # Montamos las tres lineas con la info del torrent txt = '%.2f%% de %.1fMB %s | %.1f kB/s' % \ (s.progress_file, s.file_size, s.str_state, s._download_rate) txt2 = 'S: %d(%d) P: %d(%d) | DHT:%s (%d) | Trakers: %d' % \ (s.num_seeds, s.num_complete, s.num_peers, s.num_incomplete, s.dht_state, s.dht_nodes, s.trackers) txt3 = 'Origen Peers TRK: %d DHT: %d PEX: %d LSD %d ' % \ (s.trk_peers, s.dht_peers, s.pex_peers, s.lsd_peers) else: txt = '%.2f%% de %.1fMB %s | %.1f kB/s' % \ (s.progress_file, s.file_size, s.str_state, s._download_rate) txt2 = 'S: %d(%d) P: %d(%d)' % ( s.num_seeds, s.num_complete, s.num_peers, s.num_incomplete) try: txt3 = 'Deteniendo automaticamente en: %ss' % (int( s.timeout)) except: txt3 = '' progreso.update(s.buffer, txt, txt2, txt3) time.sleep(0.5) if progreso.iscanceled(): progreso.close() if s.buffer == 100: if dialog_yesno("Alfa - Torrent", "¿Deseas iniciar la reproduccion?"): played = False progreso = dialog_progress("Alfa - Torrent", "") progreso.update(s.buffer, txt, txt2, txt3) else: progreso = dialog_progress("Alfa - Torrent", "") break else: if dialog_yesno("Alfa - Torrent", "¿Deseas cancelar el proceso?"): progreso = dialog_progress("Alfa - Torrent", "") break else: progreso = dialog_progress("Alfa - Torrent", "") progreso.update(s.buffer, txt, txt2, txt3) # Si el buffer se ha llenado y la reproduccion no ha sido iniciada, se inicia if s.buffer == 100 and not played: # Cerramos el progreso progreso.close() # Obtenemos el playlist del torrent videourl = c.get_play_list() # Iniciamos el reproductor playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO) playlist.clear() playlist.add(videourl, xlistitem) xbmc_player = xbmc.Player() xbmc_player.play(playlist) # Marcamos como reproducido para que no se vuelva a iniciar played = True # si es un archivo de la videoteca enviar a marcar como visto if item.strm_path: from platformcode import xbmc_videolibrary xbmc_videolibrary.mark_auto_as_watched(item) # Y esperamos a que el reproductor se cierre while xbmc.Player().isPlaying(): time.sleep(1) # Cuando este cerrado, Volvemos a mostrar el dialogo progreso = dialog_progress("Alfa - Torrent", "") progreso.update(s.buffer, txt, txt2, txt3) except: import traceback logger.error(traceback.format_exc()) break progreso.update(100, "Terminando y eliminando datos", " ", " ") # Detenemos el cliente if not c.closed: c.stop() # Y cerramos el progreso progreso.close()
def play(url, xlistitem={}, is_view=None, subtitle="", item=None): allocate = True try: import platform xbmc.log( "XXX KODI XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ) xbmc.log("OS platform: %s %s" % (platform.system(), platform.release())) xbmc.log("xbmc/kodi version: %s" % xbmc.getInfoLabel("System.BuildVersion")) xbmc_version = int(xbmc.getInfoLabel("System.BuildVersion")[:2]) xbmc.log("xbmc/kodi version number: %s" % xbmc_version) xbmc.log( "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX KODI XXXX" ) _platform = get_platform() if str(_platform['system']) in [ "android_armv7", "linux_armv6", "linux_armv7" ]: allocate = False # -- log ------------------------------------------------ xbmc.log( "XXX platform XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ) xbmc.log("_platform['system']: %s" % _platform['system']) xbmc.log("allocate: %s" % allocate) xbmc.log( "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX platform XXXX" ) # -- ---------------------------------------------------- except: pass DOWNLOAD_PATH = config.get_setting("downloadpath") # -- adfly: ------------------------------------ if url.startswith("http://adf.ly/"): try: data = httptools.downloadpage(url).data url = decode_adfly(data) except: ddd = xbmcgui.Dialog() ddd.ok( "alfa-MCT: Sin soporte adf.ly", "El script no tiene soporte para el acortador de urls adf.ly.", "", "url: " + url) return # -- Necesario para algunas webs ---------------------------- if not url.endswith(".torrent") and not url.startswith("magnet"): t_file = scrapertools.get_header_from_response( url, header_to_get="location") if len(t_file) > 0: url = t_file t_file = scrapertools.get_header_from_response( url, header_to_get="location") if len(t_file) > 0: url = t_file # -- Crear dos carpetas en descargas para los archivos ------ save_path_videos = os.path.join(DOWNLOAD_PATH, "torrent-videos") save_path_torrents = os.path.join(DOWNLOAD_PATH, "torrent-torrents") if not os.path.exists(save_path_torrents): os.mkdir(save_path_torrents) # -- Usar - archivo torrent desde web, magnet o HD --------- if not os.path.isfile(url) and not url.startswith("magnet"): # -- http - crear archivo torrent ----------------------- data = url_get(url) # -- El nombre del torrent será el que contiene en los -- # -- datos. - re_name = urllib.unquote( scrapertools.scrapertools.find_single_match( data, ':name\d+:(.*?)\d+:')) torrent_file = filetools.join(save_path_torrents, filetools.encode(re_name + '.torrent')) f = open(torrent_file, 'wb') f.write(data) f.close() elif os.path.isfile(url): # -- file - para usar torrens desde el HD --------------- torrent_file = url else: # -- magnet --------------------------------------------- torrent_file = url # ----------------------------------------------------------- # -- MCT - MiniClienteTorrent ------------------------------- ses = lt.session() # -- log ---------------------------------------------------- xbmc.log("### Init session ########") xbmc.log(lt.version) xbmc.log("#########################") # -- -------------------------------------------------------- ses.add_dht_router("router.bittorrent.com", 6881) ses.add_dht_router("router.utorrent.com", 6881) ses.add_dht_router("dht.transmissionbt.com", 6881) trackers = [ "udp://tracker.openbittorrent.com:80/announce", "http://tracker.torrentbay.to:6969/announce", "http://tracker.pow7.com/announce", "udp://tracker.ccc.de:80/announce", "udp://open.demonii.com:1337", "http://9.rarbg.com:2710/announce", "http://bt.careland.com.cn:6969/announce", "http://explodie.org:6969/announce", "http://mgtracker.org:2710/announce", "http://tracker.best-torrents.net:6969/announce", "http://tracker.tfile.me/announce", "http://tracker1.wasabii.com.tw:6969/announce", "udp://9.rarbg.com:2710/announce", "udp://9.rarbg.me:2710/announce", "udp://coppersurfer.tk:6969/announce", "http://www.spanishtracker.com:2710/announce", "http://www.todotorrents.com:2710/announce", ] video_file = "" # -- magnet2torrent ----------------------------------------- if torrent_file.startswith("magnet"): try: import zlib btih = hex( zlib.crc32( scrapertools.scrapertools.find_single_match( torrent_file, 'magnet:\?xt=urn:(?:[A-z0-9:]+|)([A-z0-9]{32})')) & 0xffffffff) files = [ f for f in os.listdir(save_path_torrents) if os.path.isfile(os.path.join(save_path_torrents, f)) ] for file in files: if btih in os.path.basename(file): torrent_file = os.path.join(save_path_torrents, file) except: pass if torrent_file.startswith("magnet"): try: tempdir = tempfile.mkdtemp() except IOError: tempdir = os.path.join(save_path_torrents, "temp") if not os.path.exists(tempdir): os.mkdir(tempdir) params = { 'save_path': tempdir, 'trackers': trackers, 'storage_mode': lt.storage_mode_t.storage_mode_allocate, 'paused': False, 'auto_managed': True, 'duplicate_is_error': True } h = lt.add_magnet_uri(ses, torrent_file, params) dp = xbmcgui.DialogProgress() dp.create('alfa-MCT') while not h.has_metadata(): message, porcent, msg_file, s, download = getProgress( h, "Creando torrent desde magnet") dp.update(porcent, message, msg_file) if s.state == 1: download = 1 if dp.iscanceled(): dp.close() remove_files(download, torrent_file, video_file, ses, h) return h.force_dht_announce() xbmc.sleep(1000) dp.close() info = h.get_torrent_info() data = lt.bencode(lt.create_torrent(info).generate()) torrent_file = os.path.join( save_path_torrents, unicode(info.name() + "-" + btih, "'utf-8'", errors="replace") + ".torrent") f = open(torrent_file, 'wb') f.write(data) f.close() ses.remove_torrent(h) shutil.rmtree(tempdir) # ----------------------------------------------------------- # -- Archivos torrent --------------------------------------- e = lt.bdecode(open(torrent_file, 'rb').read()) info = lt.torrent_info(e) # -- El más gordo o uno de los más gordo se entiende que es - # -- el vídeo o es el vídeo que se usará como referencia - # -- para el tipo de archivo - xbmc.log("##### Archivos ## %s ##" % len(info.files())) _index_file, _video_file, _size_file = get_video_file(info) # -- Prioritarizar/Seleccionar archivo----------------------- _index, video_file, video_size, len_files = get_video_files_sizes(info) if len_files == 0: dp = xbmcgui.Dialog().ok( "No se puede reproducir", "El torrent no contiene ningún archivo de vídeo") if _index == -1: _index = _index_file video_file = _video_file video_size = _size_file _video_file_ext = os.path.splitext(_video_file)[1] xbmc.log("##### _video_file_ext ## %s ##" % _video_file_ext) if (_video_file_ext == ".avi" or _video_file_ext == ".mp4") and allocate: xbmc.log("##### storage_mode_t.storage_mode_allocate (" + _video_file_ext + ") #####") h = ses.add_torrent({ 'ti': info, 'save_path': save_path_videos, 'trackers': trackers, 'storage_mode': lt.storage_mode_t.storage_mode_allocate }) else: xbmc.log("##### storage_mode_t.storage_mode_sparse (" + _video_file_ext + ") #####") h = ses.add_torrent({ 'ti': info, 'save_path': save_path_videos, 'trackers': trackers, 'storage_mode': lt.storage_mode_t.storage_mode_sparse }) allocate = True # ----------------------------------------------------------- # -- Descarga secuencial - trozo 1, trozo 2, ... ------------ h.set_sequential_download(True) h.force_reannounce() h.force_dht_announce() # -- Inicio de variables para 'pause' automático cuando el - # -- el vídeo se acerca a una pieza sin completar - is_greater_num_pieces = False is_greater_num_pieces_plus = False is_greater_num_pieces_pause = False porcent4first_pieces = int(video_size * 0.000000005) if porcent4first_pieces < 10: porcent4first_pieces = 10 if porcent4first_pieces > 100: porcent4first_pieces = 100 porcent4last_pieces = int(porcent4first_pieces / 2) num_pieces_to_resume = int(video_size * 0.0000000025) if num_pieces_to_resume < 5: num_pieces_to_resume = 5 if num_pieces_to_resume > 25: num_pieces_to_resume = 25 xbmc.log("##### porcent4first_pieces ## %s ##" % porcent4first_pieces) xbmc.log("##### porcent4last_pieces ## %s ##" % porcent4last_pieces) xbmc.log("##### num_pieces_to_resume ## %s ##" % num_pieces_to_resume) # -- Prioritarizar o seleccionar las piezas del archivo que - # -- se desea reproducir con 'file_priorities' - piece_set = set_priority_pieces(h, _index, video_file, video_size, porcent4first_pieces, porcent4last_pieces, allocate) # -- Crear diálogo de progreso para el primer bucle --------- dp = xbmcgui.DialogProgress() dp.create('alfa-MCT') _pieces_info = {} # -- Doble bucle anidado ------------------------------------ # -- Descarga - Primer bucle - while not h.is_seed(): s = h.status() xbmc.sleep(100) # -- Recuperar los datos del progreso ------------------- message, porcent, msg_file, s, download = getProgress(h, video_file, _pf=_pieces_info) # -- Si hace 'checking' existe descarga ----------------- # -- 'download' Se usará para saber si hay datos - # -- descargados para el diálogo de 'remove_files' - if s.state == 1: download = 1 # -- Player - play -------------------------------------- # -- Comprobar si se han completado las piezas para el - # -- inicio del vídeo - first_pieces = True _c = 0 for i in range(piece_set[0], piece_set[porcent4first_pieces]): first_pieces &= h.have_piece(i) if h.have_piece(i): _c += 1 _pieces_info = { 'current': 0, 'continuous': "%s/%s" % (_c, porcent4first_pieces), 'continuous2': "", 'have': h.status().num_pieces, 'len': len(piece_set) } last_pieces = True if not allocate: _c = len(piece_set) - 1 _cc = 0 for i in range( len(piece_set) - porcent4last_pieces, len(piece_set)): last_pieces &= h.have_piece(i) if h.have_piece(i): _c -= 1 _cc += 1 _pieces_info['continuous2'] = "[%s/%s] " % (_cc, porcent4last_pieces) if is_view != "Ok" and first_pieces and last_pieces: _pieces_info['continuous2'] = "" xbmc.log("##### porcent [%.2f%%]" % (s.progress * 100)) is_view = "Ok" dp.close() # -- Player - Ver el vídeo -------------------------- playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO) playlist.clear() ren_video_file = os.path.join(save_path_videos, video_file) try: playlist.add(ren_video_file, xlistitem) except: playlist.add(ren_video_file) if xbmc_version < 17: player = play_video(xbmc.PLAYER_CORE_AUTO) else: player = play_video() player.play(playlist) # -- Contador de cancelaciones para la ventana de - # -- 'pause' automático - is_greater_num_pieces_canceled = 0 continuous_pieces = 0 porcent_time = 0.00 current_piece = 0 set_next_continuous_pieces = porcent4first_pieces # -- Impedir que kodi haga 'resume' a un archivo ---- # -- que se reprodujo con anterioridad y que se - # -- eliminó para impedir que intente la reprucción - # -- en una pieza que aún no se ha completado y se - # -- active 'pause' automático - not_resume = True # -- Bandera subTítulos _sub = False # -- Segundo bucle - Player - Control de eventos ---- while player.isPlaying(): xbmc.sleep(100) # -- Añadir subTítulos if subtitle != "" and not _sub: _sub = True player.setSubtitles(subtitle) # -- Impedir que kodi haga 'resume' al inicio --- # -- de la descarga de un archivo conocido - if not_resume: player.seekTime(0) not_resume = False # -- Control 'pause' automático - continuous_pieces = count_completed_continuous_pieces( h, piece_set) if xbmc.Player().isPlaying(): # -- Porcentage del progreso del vídeo ------ player_getTime = player.getTime() player_getTotalTime = player.getTotalTime() porcent_time = player_getTime / player_getTotalTime * 100 # -- Pieza que se está reproduciendo -------- current_piece = int(porcent_time / 100 * len(piece_set)) # -- Banderas de control -------------------- is_greater_num_pieces = ( current_piece > continuous_pieces - num_pieces_to_resume) is_greater_num_pieces_plus = ( current_piece + porcent4first_pieces > continuous_pieces) is_greater_num_pieces_finished = ( current_piece + porcent4first_pieces >= len(piece_set)) # -- Activa 'pause' automático -------------- if is_greater_num_pieces and not player.paused and not is_greater_num_pieces_finished: is_greater_num_pieces_pause = True player.pause() if continuous_pieces >= set_next_continuous_pieces: set_next_continuous_pieces = continuous_pieces + num_pieces_to_resume next_continuous_pieces = str( continuous_pieces - current_piece) + "/" + str(set_next_continuous_pieces - current_piece) _pieces_info = { 'current': current_piece, 'continuous': next_continuous_pieces, 'continuous2': _pieces_info['continuous2'], 'have': h.status().num_pieces, 'len': len(piece_set) } # si es un archivo de la videoteca enviar a marcar como visto if item.strm_path: from platformcode import xbmc_videolibrary xbmc_videolibrary.mark_auto_as_watched(item) # -- Cerrar el diálogo de progreso -------------- if player.resumed: dp.close() # -- Mostrar el diálogo de progreso ------------- if player.paused: # -- Crear diálogo si no existe ------------- if not player.statusDialogoProgress: dp = xbmcgui.DialogProgress() dp.create('alfa-MCT') player.setDialogoProgress() # -- Diálogos de estado en el visionado ----- if not h.is_seed(): # -- Recuperar los datos del progreso --- message, porcent, msg_file, s, download = getProgress( h, video_file, _pf=_pieces_info) dp.update(porcent, message, msg_file) else: dp.update(100, "Descarga completa: " + video_file) # -- Se canceló el progreso en el visionado - # -- Continuar - if dp.iscanceled(): dp.close() player.pause() # -- Se canceló el progreso en el visionado - # -- en la ventana de 'pause' automático. - # -- Parar si el contador llega a 3 - if dp.iscanceled() and is_greater_num_pieces_pause: is_greater_num_pieces_canceled += 1 if is_greater_num_pieces_canceled == 3: player.stop() # -- Desactiva 'pause' automático y --------- # -- reinicia el contador de cancelaciones - if not dp.iscanceled( ) and not is_greater_num_pieces_plus and is_greater_num_pieces_pause: dp.close() player.pause() is_greater_num_pieces_pause = False is_greater_num_pieces_canceled = 0 # -- El usuario cancelo el visionado -------- # -- Terminar - if player.ended: # -- Diálogo eliminar archivos ---------- remove_files(download, torrent_file, video_file, ses, h) return # -- Kodi - Se cerró el visionado ----------------------- # -- Continuar | Terminar - if is_view == "Ok" and not xbmc.Player().isPlaying(): if info.num_files() == 1: # -- Diálogo continuar o terminar --------------- d = xbmcgui.Dialog() ok = d.yesno('alfa-MCT', 'XBMC-Kodi Cerró el vídeo.', '¿Continuar con la sesión?') else: ok = False # -- SI --------------------------------------------- if ok: # -- Continuar: --------------------------------- is_view = None else: # -- Terminar: ---------------------------------- # -- Comprobar si el vídeo pertenece a una ------ # -- lista de archivos - _index, video_file, video_size, len_files = get_video_files_sizes( info) if _index == -1 or len_files == 1: # -- Diálogo eliminar archivos -------------- remove_files(download, torrent_file, video_file, ses, h) return else: # -- Lista de archivos. Diálogo de opciones - piece_set = set_priority_pieces(h, _index, video_file, video_size, porcent4first_pieces, porcent4last_pieces, allocate) is_view = None dp = xbmcgui.DialogProgress() dp.create('alfa-MCT') # -- Mostar progeso antes del visionado ----------------- if is_view != "Ok": dp.update(porcent, message, msg_file) # -- Se canceló el progreso antes del visionado --------- # -- Terminar - if dp.iscanceled(): dp.close() # -- Comprobar si el vídeo pertenece a una lista de - # -- archivos - _index, video_file, video_size, len_files = get_video_files_sizes( info) if _index == -1 or len_files == 1: # -- Diálogo eliminar archivos ------------------ remove_files(download, torrent_file, video_file, ses, h) return else: # -- Lista de archivos. Diálogo de opciones ----- piece_set = set_priority_pieces(h, _index, video_file, video_size, porcent4first_pieces, porcent4last_pieces, allocate) is_view = None dp = xbmcgui.DialogProgress() dp.create('alfa-MCT') # -- Kodi - Error? - No debería llegar aquí ----------------- if is_view == "Ok" and not xbmc.Player().isPlaying(): dp.close() # -- Diálogo eliminar archivos -------------------------- remove_files(download, torrent_file, video_file, ses, h) return
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 PLAYED global autoplay_node PLAYED = False base_item = item if not config.is_xbmc(): #platformtools.dialog_notification('AutoPlay ERROR', 'Sólo disponible para XBMC/Kodi') return itemlist if not autoplay_node: # Obtiene el nodo AUTOPLAY desde el json autoplay_node = jsontools.get_node_from_file('autoplay', 'AUTOPLAY') channel_id = item.channel if item.channel == 'videolibrary': autoplay_node = jsontools.get_node_from_file('autoplay', 'AUTOPLAY') channel_id = item.contentChannel try: active = autoplay_node['status'] except: active = is_active(item.channel) if not channel_id in autoplay_node or not active: return itemlist # Agrega servidores y calidades que no estaban listados a autoplay_node new_options = check_value(channel_id, itemlist) # Obtiene el nodo del canal desde autoplay_node channel_node = autoplay_node.get(channel_id, {}) # Obtiene los ajustes des autoplay para este canal settings_node = channel_node.get('settings', {}) if get_setting('autoplay') or settings_node['active']: url_list_valid = [] autoplay_list = [] autoplay_b = [] favorite_servers = [] favorite_quality = [] # Guarda el valor actual de "Accion y Player Mode" en preferencias user_config_setting_action = config.get_setting("default_action") user_config_setting_player = config.get_setting("player_mode") # Habilita la accion "Ver en calidad alta" (si el servidor devuelve más de una calidad p.e. gdrive) if user_config_setting_action != 2: config.set_setting("default_action", 2) if user_config_setting_player != 0: config.set_setting("player_mode", 0) # 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', []) for server in server_list: server = server.lower() quality_list = channel_node.get('quality', []) # Si no se definen calidades la se asigna default como calidad unica if len(quality_list) == 0: quality_list =['default'] # 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]].lower()) 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() b_dict = 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": config.get_localized_string(60071), "action": "autoplay_config", "channel": "autoplay", "from_channel": channel_id}) # 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.lower() not in favorite_servers or item.quality not in favorite_quality \ or item.url in url_list_valid: item.type_b = True 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) 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.lower() not in favorite_servers or item.url in url_list_valid: item.type_b = True b_dict['videoitem'] = item autoplay_b.append(b_dict) continue autoplay_elem["indice_server"] = favorite_servers.index(item.server.lower()) 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: item.type_b = True b_dict['videoitem'] = item autoplay_b.append(b_dict) 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) item.plan_b=True 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']) # Se prepara el plan b, en caso de estar activo se agregan los elementos no favoritos al final try: plan_b = settings_node['plan_b'] except: plan_b = True text_b = '' if plan_b: autoplay_list.extend(autoplay_b) # Si hay elementos en la lista de autoplay se intenta reproducir cada elemento, hasta encontrar uno # funcional o fallen todos if autoplay_list or (plan_b and autoplay_b): #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: play_item = Item # Si no es un elemento favorito si agrega el texto 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 # Si se han alcanzado el numero maximo de intentos de este servidor saltamos al siguiente if max_intentos_servers[videoitem.server.lower()] == 0: continue lang = " " if hasattr(videoitem, 'language') and videoitem.language != "": lang = " '%s' " % videoitem.language platformtools.dialog_notification("AutoPlay %s" %text_b, "%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' % channel_id, None, None, ["channels.%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] # Si no directamente reproduce y marca como visto # Verifica si el item viene de la videoteca try: if base_item.contentChannel =='videolibrary': # Marca como visto from platformcode import xbmc_videolibrary xbmc_videolibrary.mark_auto_as_watched(base_item) # Rellena el video con los datos del item principal y reproduce play_item = base_item.clone(url=videoitem) platformtools.play_video(play_item.url, autoplay=True) else: # Si no viene de la videoteca solo reproduce platformtools.play_video(videoitem, autoplay=True) except: pass sleep(3) try: if platformtools.is_playing(): PLAYED = True old_frequency = channeltools.get_channel_setting("frequency", channel_id, 0) channeltools.set_channel_setting('frequency', old_frequency + 1, channel_id) logger.debug('autoplay sumar frecuencia') break except: logger.debug(str(len(autoplay_list))) # Si hemos llegado hasta aqui es por q no se ha podido reproducir max_intentos_servers[videoitem.server.lower()] -= 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.lower()] == 0: text = config.get_localized_string(60072) % videoitem.server.upper() if not platformtools.dialog_yesno("AutoPlay", text, config.get_localized_string(60073)): max_intentos_servers[videoitem.server.lower()] = max_intentos # Si no quedan elementos en la lista se informa if autoplay_elem == autoplay_list[-1]: platformtools.dialog_notification('AutoPlay', config.get_localized_string(60072) % videoitem.server.upper()) else: platformtools.dialog_notification(config.get_localized_string(60074), config.get_localized_string(60075)) if new_options: platformtools.dialog_notification("AutoPlay", config.get_localized_string(60076), sound=False) # Restaura si es necesario el valor previo de "Accion y Player Mode" en preferencias if user_config_setting_action != 2: 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
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() for videoitem in itemlist: #Nos dice de donde viene si del addon o videolibrary if item.contentChannel == 'videolibrary': videoitem.contentEpisodeNumber = item.contentEpisodeNumber videoitem.contentPlot = item.contentPlot videoitem.contentSeason = item.contentSeason videoitem.contentSerieName = item.contentSerieName videoitem.contentTitle = item.contentTitle videoitem.contentType = item.contentType videoitem.episode_id = item.episode_id #videoitem.infoLabels=item.infoLabels videoitem.thumbnail = item.thumbnail #videoitem.title=item.title if not config.is_xbmc(): #platformtools.dialog_notification('AutoPlay ERROR', 'Sólo disponible para XBMC/Kodi') return itemlist global autoplay_node if not autoplay_node: # Obtiene el nodo AUTOPLAY desde el json autoplay_node = jsontools.get_node_from_file('autoplay', 'AUTOPLAY') if not item.channel in autoplay_node: return itemlist # 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 y Player Mode" en preferencias user_config_setting_action = config.get_setting("default_action") user_config_setting_player = config.get_setting("player_mode") # Habilita la accion "Ver en calidad alta" (si el servidor devuelve más de una calidad p.e. gdrive) if user_config_setting_action != 2: config.set_setting("default_action", 2) if user_config_setting_player != 0: config.set_setting("player_mode", 0) # 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', []) # Si no se definen calidades la se asigna default como calidad unica if len(quality_list) == 0: quality_list = ['default'] # 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 y marca como visto from platformcode import xbmc_videolibrary xbmc_videolibrary.mark_auto_as_watched(item) #platformtools.play_video(videoitem) videoitem.contentChannel = 'videolibrary' launcher.run(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 y Player Mode" en preferencias if user_config_setting_action != 2: config.set_setting("default_action", user_config_setting_action) if user_config_setting_player != 0: config.set_setting("player_mode", user_config_setting_player) # devuelve la lista de enlaces para la eleccion manual return itemlist